diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 25ae4110625608b553d170b6bb5c439215503afe..0000000000000000000000000000000000000000
--- a/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/client_test.py b/client_test.py
deleted file mode 100644
index 2ba7e199b0b1e2fc662a3c5b60bb2c6c7d56cad5..0000000000000000000000000000000000000000
--- a/client_test.py
+++ /dev/null
@@ -1,362 +0,0 @@
-"""
-Client test.
-
-Run server:
-
-python generate.py --base_model=h2oai/h2ogpt-oig-oasst1-512-6_9b
-
-NOTE: For private models, add --use-auth_token=True
-
-NOTE: --use_gpu_id=True (default) must be used for multi-GPU in case see failures with cuda:x cuda:y mismatches.
-Currently, this will force model to be on a single GPU.
-
-Then run this client as:
-
-python src/client_test.py
-
-
-
-For HF spaces:
-
-HOST="https://h2oai-h2ogpt-chatbot.hf.space" python src/client_test.py
-
-Result:
-
-Loaded as API: https://h2oai-h2ogpt-chatbot.hf.space ✔
-{'instruction_nochat': 'Who are you?', 'iinput_nochat': '', 'response': 'I am h2oGPT, a large language model developed by LAION.', 'sources': ''}
-
-
-For demo:
-
-HOST="https://gpt.h2o.ai" python src/client_test.py
-
-Result:
-
-Loaded as API: https://gpt.h2o.ai ✔
-{'instruction_nochat': 'Who are you?', 'iinput_nochat': '', 'response': 'I am h2oGPT, a chatbot created by LAION.', 'sources': ''}
-
-NOTE: Raw output from API for nochat case is a string of a python dict and will remain so if other entries are added to dict:
-
-{'response': "I'm h2oGPT, a large language model by H2O.ai, the visionary leader in democratizing AI.", 'sources': ''}
-
-
-"""
-import ast
-import time
-import os
-import markdown # pip install markdown
-import pytest
-from bs4 import BeautifulSoup # pip install beautifulsoup4
-
-from enums import DocumentSubset, LangChainAction
-
-debug = False
-
-os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
-
-
-def get_client(serialize=True):
- from gradio_client import Client
-
- client = Client(os.getenv('HOST', "http://localhost:7860"), serialize=serialize)
- if debug:
- print(client.view_api(all_endpoints=True))
- return client
-
-
-def get_args(prompt, prompt_type, chat=False, stream_output=False,
- max_new_tokens=50,
- top_k_docs=3,
- langchain_mode='Disabled',
- add_chat_history_to_context=True,
- langchain_action=LangChainAction.QUERY.value,
- langchain_agents=[],
- prompt_dict=None):
- from collections import OrderedDict
- kwargs = OrderedDict(instruction=prompt if chat else '', # only for chat=True
- iinput='', # only for chat=True
- context='',
- # streaming output is supported, loops over and outputs each generation in streaming mode
- # but leave stream_output=False for simple input/output mode
- stream_output=stream_output,
- prompt_type=prompt_type,
- prompt_dict=prompt_dict,
- temperature=0.1,
- top_p=0.75,
- top_k=40,
- num_beams=1,
- max_new_tokens=max_new_tokens,
- min_new_tokens=0,
- early_stopping=False,
- max_time=20,
- repetition_penalty=1.0,
- num_return_sequences=1,
- do_sample=True,
- chat=chat,
- instruction_nochat=prompt if not chat else '',
- iinput_nochat='', # only for chat=False
- langchain_mode=langchain_mode,
- add_chat_history_to_context=add_chat_history_to_context,
- langchain_action=langchain_action,
- langchain_agents=langchain_agents,
- top_k_docs=top_k_docs,
- chunk=True,
- chunk_size=512,
- document_subset=DocumentSubset.Relevant.name,
- document_choice=[],
- )
- from evaluate_params import eval_func_param_names
- assert len(set(eval_func_param_names).difference(set(list(kwargs.keys())))) == 0
- if chat:
- # add chatbot output on end. Assumes serialize=False
- kwargs.update(dict(chatbot=[]))
-
- return kwargs, list(kwargs.values())
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_basic(prompt_type='human_bot'):
- return run_client_nochat(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50)
-
-
-def run_client_nochat(prompt, prompt_type, max_new_tokens):
- kwargs, args = get_args(prompt, prompt_type, chat=False, max_new_tokens=max_new_tokens)
-
- api_name = '/submit_nochat'
- client = get_client(serialize=True)
- res = client.predict(
- *tuple(args),
- api_name=api_name,
- )
- print("Raw client result: %s" % res, flush=True)
- res_dict = dict(prompt=kwargs['instruction_nochat'], iinput=kwargs['iinput_nochat'],
- response=md_to_text(res))
- print(res_dict)
- return res_dict, client
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_basic_api(prompt_type='human_bot'):
- return run_client_nochat_api(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50)
-
-
-def run_client_nochat_api(prompt, prompt_type, max_new_tokens):
- kwargs, args = get_args(prompt, prompt_type, chat=False, max_new_tokens=max_new_tokens)
-
- api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing
- client = get_client(serialize=True)
- res = client.predict(
- str(dict(kwargs)),
- api_name=api_name,
- )
- print("Raw client result: %s" % res, flush=True)
- res_dict = dict(prompt=kwargs['instruction_nochat'], iinput=kwargs['iinput_nochat'],
- response=md_to_text(ast.literal_eval(res)['response']),
- sources=ast.literal_eval(res)['sources'])
- print(res_dict)
- return res_dict, client
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_basic_api_lean(prompt_type='human_bot'):
- return run_client_nochat_api_lean(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50)
-
-
-def run_client_nochat_api_lean(prompt, prompt_type, max_new_tokens):
- kwargs = dict(instruction_nochat=prompt)
-
- api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing
- client = get_client(serialize=True)
- res = client.predict(
- str(dict(kwargs)),
- api_name=api_name,
- )
- print("Raw client result: %s" % res, flush=True)
- res_dict = dict(prompt=kwargs['instruction_nochat'],
- response=md_to_text(ast.literal_eval(res)['response']),
- sources=ast.literal_eval(res)['sources'])
- print(res_dict)
- return res_dict, client
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_basic_api_lean_morestuff(prompt_type='human_bot'):
- return run_client_nochat_api_lean_morestuff(prompt='Who are you?', prompt_type=prompt_type, max_new_tokens=50)
-
-
-def run_client_nochat_api_lean_morestuff(prompt, prompt_type='human_bot', max_new_tokens=512):
- kwargs = dict(
- instruction='',
- iinput='',
- context='',
- stream_output=False,
- prompt_type=prompt_type,
- temperature=0.1,
- top_p=0.75,
- top_k=40,
- num_beams=1,
- max_new_tokens=256,
- min_new_tokens=0,
- early_stopping=False,
- max_time=20,
- repetition_penalty=1.0,
- num_return_sequences=1,
- do_sample=True,
- chat=False,
- instruction_nochat=prompt,
- iinput_nochat='',
- langchain_mode='Disabled',
- add_chat_history_to_context=True,
- langchain_action=LangChainAction.QUERY.value,
- langchain_agents=[],
- top_k_docs=4,
- document_subset=DocumentSubset.Relevant.name,
- document_choice=[],
- )
-
- api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing
- client = get_client(serialize=True)
- res = client.predict(
- str(dict(kwargs)),
- api_name=api_name,
- )
- print("Raw client result: %s" % res, flush=True)
- res_dict = dict(prompt=kwargs['instruction_nochat'],
- response=md_to_text(ast.literal_eval(res)['response']),
- sources=ast.literal_eval(res)['sources'])
- print(res_dict)
- return res_dict, client
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_chat(prompt_type='human_bot'):
- return run_client_chat(prompt='Who are you?', prompt_type=prompt_type, stream_output=False, max_new_tokens=50,
- langchain_mode='Disabled',
- langchain_action=LangChainAction.QUERY.value,
- langchain_agents=[])
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_chat_stream(prompt_type='human_bot'):
- return run_client_chat(prompt="Tell a very long kid's story about birds.", prompt_type=prompt_type,
- stream_output=True, max_new_tokens=512,
- langchain_mode='Disabled',
- langchain_action=LangChainAction.QUERY.value,
- langchain_agents=[])
-
-
-def run_client_chat(prompt, prompt_type, stream_output, max_new_tokens,
- langchain_mode, langchain_action, langchain_agents,
- prompt_dict=None):
- client = get_client(serialize=False)
-
- kwargs, args = get_args(prompt, prompt_type, chat=True, stream_output=stream_output,
- max_new_tokens=max_new_tokens,
- langchain_mode=langchain_mode,
- langchain_action=langchain_action,
- langchain_agents=langchain_agents,
- prompt_dict=prompt_dict)
- return run_client(client, prompt, args, kwargs)
-
-
-def run_client(client, prompt, args, kwargs, do_md_to_text=True, verbose=False):
- assert kwargs['chat'], "Chat mode only"
- res = client.predict(*tuple(args), api_name='/instruction')
- args[-1] += [res[-1]]
-
- res_dict = kwargs
- res_dict['prompt'] = prompt
- if not kwargs['stream_output']:
- res = client.predict(*tuple(args), api_name='/instruction_bot')
- res_dict['response'] = res[0][-1][1]
- print(md_to_text(res_dict['response'], do_md_to_text=do_md_to_text))
- return res_dict, client
- else:
- job = client.submit(*tuple(args), api_name='/instruction_bot')
- res1 = ''
- while not job.done():
- outputs_list = job.communicator.job.outputs
- if outputs_list:
- res = job.communicator.job.outputs[-1]
- res1 = res[0][-1][-1]
- res1 = md_to_text(res1, do_md_to_text=do_md_to_text)
- print(res1)
- time.sleep(0.1)
- full_outputs = job.outputs()
- if verbose:
- print('job.outputs: %s' % str(full_outputs))
- # ensure get ending to avoid race
- # -1 means last response if streaming
- # 0 means get text_output, ignore exception_text
- # 0 means get list within text_output that looks like [[prompt], [answer]]
- # 1 means get bot answer, so will have last bot answer
- res_dict['response'] = md_to_text(full_outputs[-1][0][0][1], do_md_to_text=do_md_to_text)
- return res_dict, client
-
-
-@pytest.mark.skip(reason="For manual use against some server, no server launched")
-def test_client_nochat_stream(prompt_type='human_bot'):
- return run_client_nochat_gen(prompt="Tell a very long kid's story about birds.", prompt_type=prompt_type,
- stream_output=True, max_new_tokens=512,
- langchain_mode='Disabled',
- langchain_action=LangChainAction.QUERY.value,
- langchain_agents=[])
-
-
-def run_client_nochat_gen(prompt, prompt_type, stream_output, max_new_tokens,
- langchain_mode, langchain_action, langchain_agents):
- client = get_client(serialize=False)
-
- kwargs, args = get_args(prompt, prompt_type, chat=False, stream_output=stream_output,
- max_new_tokens=max_new_tokens, langchain_mode=langchain_mode,
- langchain_action=langchain_action, langchain_agents=langchain_agents)
- return run_client_gen(client, prompt, args, kwargs)
-
-
-def run_client_gen(client, prompt, args, kwargs, do_md_to_text=True, verbose=False):
- res_dict = kwargs
- res_dict['prompt'] = prompt
- if not kwargs['stream_output']:
- res = client.predict(str(dict(kwargs)), api_name='/submit_nochat_api')
- res_dict['response'] = res[0]
- print(md_to_text(res_dict['response'], do_md_to_text=do_md_to_text))
- return res_dict, client
- else:
- job = client.submit(str(dict(kwargs)), api_name='/submit_nochat_api')
- while not job.done():
- outputs_list = job.communicator.job.outputs
- if outputs_list:
- res = job.communicator.job.outputs[-1]
- res_dict = ast.literal_eval(res)
- print('Stream: %s' % res_dict['response'])
- time.sleep(0.1)
- res_list = job.outputs()
- assert len(res_list) > 0, "No response, check server"
- res = res_list[-1]
- res_dict = ast.literal_eval(res)
- print('Final: %s' % res_dict['response'])
- return res_dict, client
-
-
-def md_to_text(md, do_md_to_text=True):
- if not do_md_to_text:
- return md
- assert md is not None, "Markdown is None"
- html = markdown.markdown(md)
- soup = BeautifulSoup(html, features='html.parser')
- return soup.get_text()
-
-
-def run_client_many(prompt_type='human_bot'):
- ret1, _ = test_client_chat(prompt_type=prompt_type)
- ret2, _ = test_client_chat_stream(prompt_type=prompt_type)
- ret3, _ = test_client_nochat_stream(prompt_type=prompt_type)
- ret4, _ = test_client_basic(prompt_type=prompt_type)
- ret5, _ = test_client_basic_api(prompt_type=prompt_type)
- ret6, _ = test_client_basic_api_lean(prompt_type=prompt_type)
- ret7, _ = test_client_basic_api_lean_morestuff(prompt_type=prompt_type)
- return ret1, ret2, ret3, ret4, ret5, ret6, ret7
-
-
-if __name__ == '__main__':
- run_client_many()
diff --git a/create_data.py b/create_data.py
deleted file mode 100644
index f16c519dcdd6b07dfd09f824e670401887f6eeaa..0000000000000000000000000000000000000000
--- a/create_data.py
+++ /dev/null
@@ -1,1809 +0,0 @@
-"""
-Dataset creation tools.
-
-Keep to-level imports clean of non-trivial imports for specific tools,
-because this file is imported for various purposes
-"""
-
-import ast
-import concurrent.futures
-import contextlib
-import hashlib
-import json
-import os
-import shutil
-import signal
-import sys
-import traceback
-from concurrent.futures import ProcessPoolExecutor
-
-import psutil
-import pytest
-import pandas as pd
-import numpy as np
-from tqdm import tqdm
-
-from utils import flatten_list, remove
-
-
-def parse_rst_file(filepath):
- with open(filepath, 'r') as f:
- input_data = f.read()
- settings_overrides = {'initial_header_level': 2}
- from docutils import core
- document = core.publish_doctree(
- source=input_data,
- source_path=filepath,
- settings_overrides=settings_overrides,
- )
- qa_pairs = []
- current_section = None
- current_question = ""
- current_answer = ""
- for node in document.traverse():
- if node.__class__.__name__ == 'section':
- current_section = ""
- elif current_section is not None:
- if node.__class__.__name__ == 'Text':
- if node.astext()[-1] == "?":
- if current_question:
- qa_pairs.append((current_question, current_answer))
- current_question = node.astext()
- current_answer = ""
- else:
- current_answer += node.astext()
- if current_answer:
- qa_pairs.append((current_question, current_answer))
- return {k: v for k, v in qa_pairs}
-
-
-def test_scrape_dai_docs():
- home = os.path.expanduser('~')
- file = os.path.join(home, 'h2oai/docs/faq.rst')
- qa_pairs = parse_rst_file(file)
- prompt_type = 'human_bot'
- from prompter import prompt_types
- assert prompt_type in prompt_types
- save_thing = [{"instruction": k, "output": v, 'prompt_type': prompt_type} for k, v in qa_pairs.items()]
- output_file = "dai_faq.json"
- with open(output_file, "wt") as f:
- f.write(json.dumps(save_thing, indent=2))
-
-
-def test_scrape_dai_docs_all():
- """
- pytest create_data.py::test_scrape_dai_docs_all
- """
- import glob
- import nltk
- nltk.download('punkt')
- dd = {}
- np.random.seed(1234)
- home = os.path.expanduser('~')
- files = list(glob.glob(os.path.join(home, "h2oai/docs/**/*rst")))
- np.random.shuffle(files)
- val_count = int(0.05 * len(files))
- train_files = files[val_count:]
- valid_files = files[:val_count]
- things = [
- ("dai_docs.train.json", train_files),
- ("dai_docs.valid.json", valid_files)
- ]
- for LEN in [100, 200, 500]:
- for output_file, ff in things:
- if output_file not in dd:
- dd[output_file] = []
- for f in ff:
- with open(f) as input:
- blob = input.read()
- blob = blob.replace("~~", "")
- blob = blob.replace("==", "")
- blob = blob.replace("''", "")
- blob = blob.replace("--", "")
- blob = blob.replace("**", "")
- dd[output_file].extend(get_sentences(blob, length=LEN))
- for output_file, _ in things:
- save_thing = [{"output": k.strip(), 'prompt_type': 'plain'} for k in dd[output_file]]
- with open(output_file, "wt") as f:
- f.write(json.dumps(save_thing, indent=2))
-
-
-def get_sentences(blob, length):
- """
- break-up input text into sentences and then output list of sentences of about length in size
- :param blob:
- :param length:
- :return:
- """
- import nltk
- nltk.download('punkt')
- from nltk.tokenize import sent_tokenize
- sentences = sent_tokenize(blob)
- my_sentences = []
- my_string = ""
- for sentence in sentences:
- if len(my_string) + len(sentence) <= length:
- if my_string:
- my_string += " " + sentence
- else:
- my_string = sentence
- else:
- my_sentences.append(my_string)
- my_string = ""
- return my_sentences or [my_string]
-
-
-def setup_dai_docs(path=None, dst="working_dir_docs", from_hf=False):
- """
- Only supported if have access to source code or HF token for HF spaces and from_hf=True
- :param path:
- :param dst:
- :param from_hf:
- :return:
- """
-
- home = os.path.expanduser('~')
-
- if from_hf:
- # assumes
- from huggingface_hub import hf_hub_download
- # True for case when locally already logged in with correct token, so don't have to set key
- token = os.getenv('HUGGINGFACE_API_TOKEN', True)
- path_to_zip_file = hf_hub_download('h2oai/dai_docs', 'dai_docs.zip', token=token, repo_type='dataset')
- path = 'h2oai'
- import zipfile
- with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
- zip_ref.extractall(path)
- path = os.path.join(path, 'docs/**/*')
-
- if path is None:
- if os.path.isdir(os.path.join(home, 'h2oai')):
- path = os.path.join(home, "h2oai/docs/**/*")
- else:
- assert os.path.isdir(os.path.join(home, 'h2oai.superclean')), '%s does not exist' % path
- path = os.path.join(home, "h2oai.superclean/docs/**/*")
- import glob
- files = list(glob.glob(path, recursive=True))
-
- # pandoc can't find include files
-
- remove(dst)
- os.makedirs(dst)
-
- # copy full tree, for absolute paths in rst
- for fil in files:
- if os.path.isfile(fil):
- shutil.copy(fil, dst)
-
- # hack for relative path
- scorers_dir = os.path.join(dst, 'scorers')
- makedirs(scorers_dir)
- for fil in glob.glob(os.path.join(dst, '*.frag')):
- shutil.copy(fil, scorers_dir)
-
- return dst
-
-
-def rst_to_outputs(files, min_len=30, max_len=2048 // 2 - 30):
- # account for sequence length (context window) including prompt and input and output
-
- # os.system('pandoc -f rst -t plain ./expert_settings/nlp_settings.rst')
- import pypandoc
- basedir = os.path.abspath(os.getcwd())
-
- outputs = []
- for fil in files:
- os.chdir(basedir)
- os.chdir(os.path.dirname(fil))
- fil = os.path.basename(fil)
- print("Processing %s" % fil, flush=True)
- # out_format can be one of: asciidoc, asciidoctor, beamer, biblatex, bibtex, commonmark, commonmark_x,
- # context, csljson, docbook, docbook4, docbook5, docx, dokuwiki,
- # dzslides, epub, epub2, epub3, fb2, gfm, haddock, html, html4, html5, icml,
- # ipynb, jats, jats_archiving, jats_articleauthoring, jats_publishing, jira,
- # json, latex, man,
- # markdown, markdown_github, markdown_mmd, markdown_phpextra, markdown_strict,
- # mediawiki, ms, muse, native, odt, opendocument, opml, org, pdf, plain, pptx,
- # revealjs, rst, rtf, s5, slideous, slidy, tei, texinfo, textile, xwiki, zimwiki
- out_format = 'plain'
- # avoid extra new lines injected into text
- extra_args = ['--wrap=preserve', '--resource path="%s" % dst']
-
- plain_list = []
- try:
- # valid for expert settings
- input_rst = pypandoc.convert_file(fil, 'rst')
- input_list = input_rst.split('\n``')
- for input_subrst in input_list:
- input_plain = pypandoc.convert_text(input_subrst, format='rst', to='plain')
- plain_list.append([input_plain, fil])
- except Exception as e:
- print("file exception: %s %s" % (fil, str(e)), flush=True)
-
- if not plain_list:
- # if failed to process as pieces of rst, then
- output = pypandoc.convert_file(fil, out_format, extra_args=extra_args, format='rst')
- outputs1 = get_sentences(output, length=max_len)
- for oi, output in enumerate(outputs1):
- output = output.replace('\n\n', '\n')
- plain_list.append([output, fil])
- outputs.extend(plain_list)
-
- # report:
- # [print(len(x)) for x in outputs]
-
- # deal with blocks longer than context size (sequence length) of 2048
- new_outputs = []
- num_truncated = 0
- num_orig = len(outputs)
- for output, fil in outputs:
- if len(output) < max_len:
- new_outputs.append([output, fil])
- continue
- outputs1 = get_sentences(output, length=max_len)
- for oi, output1 in enumerate(outputs1):
- output1 = output1.replace('\n\n', '\n')
- new_outputs.append([output1, fil])
- num_truncated += 1
- print('num_orig: %s num_truncated: %s' % (num_orig, num_truncated), flush=True)
-
- new_outputs = [[k.strip(), fil] for k, fil in new_outputs if len(k.strip()) > min_len]
-
- return new_outputs
-
-
-def test_scrape_dai_docs_all_pandoc():
- """
- pytest -s -v create_data.py::test_scrape_dai_docs_all_pandoc
- :return:
- """
-
- dst = setup_dai_docs()
-
- import glob
- files = list(glob.glob(os.path.join(dst, '*rst'), recursive=True))
-
- basedir = os.path.abspath(os.getcwd())
- new_outputs = rst_to_outputs(files)
- os.chdir(basedir)
-
- remove(dst)
- save_thing = [{"output": k.strip(), 'prompt_type': 'plain'} for k in new_outputs]
- output_file = "dai_docs.train_cleaned.json"
- with open(output_file, "wt") as f:
- f.write(json.dumps(save_thing, indent=2))
-
-
-def test_config_to_json():
- """
- Needs to run from Driverless AI source directory.
- E.g. (base) jon@gpu:~/h2oai$ pytest -s -v /data/jon/h2ogpt/create_data.py::test_config_to_json ; cp config.json /data/jon/h2ogpt/
- :return:
- """
- try:
- # Arrange
- import json
- from h2oaicore.systemutils import config
- toml_list = []
- for k, v in config.get_meta_dict().items():
- title = (v.title + ": ") if v.title else ''
- comment = v.comment or ''
- if not (title or comment):
- continue
- toml_list.extend(
- [
- {
- 'prompt_type': 'plain',
- 'instruction': f" "
diff --git a/evaluate_params.py b/evaluate_params.py
deleted file mode 100644
index 40f89ecb40ee60cb53ed12b8764e28b309979c63..0000000000000000000000000000000000000000
--- a/evaluate_params.py
+++ /dev/null
@@ -1,52 +0,0 @@
-input_args_list = ['model_state', 'my_db_state', 'selection_docs_state']
-
-
-no_default_param_names = [
- 'instruction',
- 'iinput',
- 'context',
- 'instruction_nochat',
- 'iinput_nochat',
-]
-
-gen_hyper = ['temperature',
- 'top_p',
- 'top_k',
- 'num_beams',
- 'max_new_tokens',
- 'min_new_tokens',
- 'early_stopping',
- 'max_time',
- 'repetition_penalty',
- 'num_return_sequences',
- 'do_sample',
- ]
-
-eval_func_param_names = ['instruction',
- 'iinput',
- 'context',
- 'stream_output',
- 'prompt_type',
- 'prompt_dict'] + \
- gen_hyper + \
- ['chat',
- 'instruction_nochat',
- 'iinput_nochat',
- 'langchain_mode',
- 'add_chat_history_to_context',
- 'langchain_action',
- 'langchain_agents',
- 'top_k_docs',
- 'chunk',
- 'chunk_size',
- 'document_subset',
- 'document_choice',
- ]
-
-# form evaluate defaults for submit_nochat_api
-eval_func_param_names_defaults = eval_func_param_names.copy()
-for k in no_default_param_names:
- if k in eval_func_param_names_defaults:
- eval_func_param_names_defaults.remove(k)
-
-eval_extra_columns = ['prompt', 'response', 'score']
diff --git a/gen.py b/gen.py
deleted file mode 100644
index 227286d0c311e96bca7cffdf01fb6aa7ed018cb6..0000000000000000000000000000000000000000
--- a/gen.py
+++ /dev/null
@@ -1,2641 +0,0 @@
-import ast
-import copy
-import functools
-import glob
-import inspect
-import queue
-import sys
-import os
-import time
-import traceback
-import typing
-import warnings
-from datetime import datetime
-import filelock
-import requests
-import psutil
-from requests import ConnectTimeout, JSONDecodeError
-from urllib3.exceptions import ConnectTimeoutError, MaxRetryError, ConnectionError
-from requests.exceptions import ConnectionError as ConnectionError2
-from requests.exceptions import ReadTimeout as ReadTimeout2
-
-if os.path.dirname(os.path.abspath(__file__)) not in sys.path:
- sys.path.append(os.path.dirname(os.path.abspath(__file__)))
-
-os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
-os.environ['BITSANDBYTES_NOWELCOME'] = '1'
-warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
-
-from evaluate_params import eval_func_param_names, no_default_param_names
-from enums import DocumentSubset, LangChainMode, no_lora_str, model_token_mapping, no_model_str, source_prefix, \
- source_postfix, LangChainAction, LangChainAgent, DocumentChoice
-from loaders import get_loaders
-from utils import set_seed, clear_torch_cache, save_generate_output, NullContext, wrapped_partial, EThread, get_githash, \
- import_matplotlib, get_device, makedirs, get_kwargs, start_faulthandler, get_hf_server, FakeTokenizer, remove, \
- have_langchain, set_openai, load_collection_enum
-
-start_faulthandler()
-import_matplotlib()
-
-SEED = 1236
-set_seed(SEED)
-
-from typing import Union
-
-import fire
-import torch
-from transformers import GenerationConfig, AutoModel, TextIteratorStreamer
-
-from prompter import Prompter, inv_prompt_type_to_model_lower, non_hf_types, PromptType, get_prompt, generate_prompt
-from stopping import get_stopping
-
-langchain_actions = [x.value for x in list(LangChainAction)]
-
-langchain_agents_list = [x.value for x in list(LangChainAgent)]
-
-scratch_base_dir = '/tmp/'
-
-
-def main(
- load_8bit: bool = False,
- load_4bit: bool = False,
- load_half: bool = True,
- load_gptq: str = '',
- use_safetensors: bool = False,
- use_gpu_id: bool = True,
- base_model: str = '',
- tokenizer_base_model: str = '',
- lora_weights: str = "",
- gpu_id: int = 0,
- compile_model: bool = True,
- use_cache: bool = None,
- inference_server: str = "",
- prompt_type: Union[int, str] = None,
- prompt_dict: typing.Dict = None,
-
- model_lock: typing.List[typing.Dict[str, str]] = None,
- model_lock_columns: int = None,
- fail_if_cannot_connect: bool = False,
-
- # input to generation
- temperature: float = None,
- top_p: float = None,
- top_k: int = None,
- num_beams: int = None,
- repetition_penalty: float = None,
- num_return_sequences: int = None,
- do_sample: bool = None,
- max_new_tokens: int = None,
- min_new_tokens: int = None,
- early_stopping: Union[bool, str] = None,
- max_time: float = None,
-
- memory_restriction_level: int = None,
- debug: bool = False,
- save_dir: str = None,
- share: bool = False,
- local_files_only: bool = False,
- resume_download: bool = True,
- use_auth_token: Union[str, bool] = False,
- trust_remote_code: Union[str, bool] = True,
- offload_folder: str = "offline_folder",
-
- src_lang: str = "English",
- tgt_lang: str = "Russian",
-
- cli: bool = False,
- cli_loop: bool = True,
- gradio: bool = True,
- gradio_offline_level: int = 0,
- chat: bool = True,
- chat_context: bool = False,
- stream_output: bool = True,
- show_examples: bool = None,
- verbose: bool = False,
- h2ocolors: bool = True,
- dark: bool = False, # light tends to be best
- height: int = 600,
- show_lora: bool = True,
- login_mode_if_model0: bool = False,
- block_gradio_exit: bool = True,
- concurrency_count: int = 1,
- api_open: bool = False,
- allow_api: bool = True,
- input_lines: int = 1,
- gradio_size: str = None,
- auth: typing.List[typing.Tuple[str, str]] = None,
- max_max_time=None,
- max_max_new_tokens=None,
-
- sanitize_user_prompt: bool = False,
- sanitize_bot_response: bool = False,
-
- extra_model_options: typing.List[str] = [],
- extra_lora_options: typing.List[str] = [],
- extra_server_options: typing.List[str] = [],
-
- score_model: str = 'auto',
-
- eval_filename: str = None,
- eval_prompts_only_num: int = 0,
- eval_prompts_only_seed: int = 1234,
- eval_as_output: bool = False,
-
- langchain_mode: str = None,
- langchain_action: str = LangChainAction.QUERY.value,
- langchain_agents: list = [],
- force_langchain_evaluate: bool = False,
- langchain_modes: list = [x.value for x in list(LangChainMode)],
- visible_langchain_modes: list = ['UserData', 'MyData'],
- # WIP:
- # visible_langchain_actions: list = langchain_actions.copy(),
- visible_langchain_actions: list = [LangChainAction.QUERY.value, LangChainAction.SUMMARIZE_MAP.value],
- visible_langchain_agents: list = langchain_agents_list.copy(),
- document_subset: str = DocumentSubset.Relevant.name,
- document_choice: list = [DocumentChoice.ALL.value],
- user_path: str = None,
- langchain_mode_paths: dict = {'UserData': None},
- detect_user_path_changes_every_query: bool = False,
- use_llm_if_no_docs: bool = False,
- load_db_if_exists: bool = True,
- keep_sources_in_context: bool = False,
- db_type: str = 'chroma',
- use_openai_embedding: bool = False,
- use_openai_model: bool = False,
- hf_embedding_model: str = None,
- cut_distance: float = 1.64,
- add_chat_history_to_context: bool = True,
- allow_upload_to_user_data: bool = True,
- reload_langchain_state: bool = True,
- allow_upload_to_my_data: bool = True,
- enable_url_upload: bool = True,
- enable_text_upload: bool = True,
- enable_sources_list: bool = True,
- chunk: bool = True,
- chunk_size: int = 512,
- top_k_docs: int = None,
- reverse_docs: bool = True,
- auto_reduce_chunks: bool = True,
- max_chunks: int = 100,
- n_jobs: int = -1,
- enable_captions: bool = True,
- captions_model: str = "Salesforce/blip-image-captioning-base",
- pre_load_caption_model: bool = False,
- caption_gpu: bool = True,
- enable_ocr: bool = False,
- enable_pdf_ocr: str = 'auto',
-):
- """
-
- :param load_8bit: load model in 8-bit using bitsandbytes
- :param load_4bit: load model in 4-bit using bitsandbytes
- :param load_half: load model in float16
- :param load_gptq: to load model with GPTQ, put model_basename here, e.g. gptq_model-4bit--1g
- :param use_safetensors: to use safetensors version (assumes file/HF points to safe tensors version)
- :param use_gpu_id: whether to control devices with gpu_id. If False, then spread across GPUs
- :param base_model: model HF-type name. If use --base_model to preload model, cannot unload in gradio in models tab
- :param tokenizer_base_model: tokenizer HF-type name. Usually not required, inferred from base_model.
- :param lora_weights: LORA weights path/HF link
- :param gpu_id: if use_gpu_id, then use gpu_id for cuda device ID, or auto mode if gpu_id != -1
- :param compile_model Whether to compile the model
- :param use_cache: Whether to use caching in model (some models fail when multiple threads use)
- :param inference_server: Consume base_model as type of model at this address
- Address can be text-generation-server hosting that base_model
- e.g. python generate.py --inference_server="http://192.168.1.46:6112" --base_model=h2oai/h2ogpt-oasst1-512-12b
- Or Address can be "openai_chat" or "openai" for OpenAI API
- e.g. python generate.py --inference_server="openai_chat" --base_model=gpt-3.5-turbo
- e.g. python generate.py --inference_server="openai" --base_model=text-davinci-003
- Or Address can be "vllm:IP:port" or "vllm:IP:port" for OpenAI-compliant vLLM endpoint
- Note: vllm_chat not supported by vLLM project.
- :param prompt_type: type of prompt, usually matched to fine-tuned model or plain for foundational model
- :param prompt_dict: If prompt_type=custom, then expects (some) items returned by get_prompt(..., return_dict=True)
- :param model_lock: Lock models to specific combinations, for ease of use and extending to many models
- Only used if gradio = True
- List of dicts, each dict has base_model, tokenizer_base_model, lora_weights, inference_server, prompt_type, and prompt_dict
- If all models have same prompt_type, and prompt_dict, can still specify that once in CLI outside model_lock as default for dict
- Can specify model_lock instead of those items on CLI
- As with CLI itself, base_model can infer prompt_type and prompt_dict if in prompter.py.
- Also, tokenizer_base_model and lora_weights are optional.
- Also, inference_server is optional if loading model from local system.
- All models provided will automatically appear in compare model mode
- Model loading-unloading and related choices will be disabled. Model/lora/server adding will be disabled
- :param model_lock_columns: How many columns to show if locking models (and so showing all at once)
- If None, then defaults to up to 3
- if -1, then all goes into 1 row
- Maximum value is 4 due to non-dynamic gradio rendering elements
- :param fail_if_cannot_connect: if doing model locking (e.g. with many models), fail if True. Otherwise ignore.
- Useful when many endpoints and want to just see what works, but still have to wait for timeout.
- :param temperature: generation temperature
- :param top_p: generation top_p
- :param top_k: generation top_k
- :param num_beams: generation number of beams
- :param repetition_penalty: generation repetition penalty
- :param num_return_sequences: generation number of sequences (1 forced for chat)
- :param do_sample: generation sample
- :param max_new_tokens: generation max new tokens
- :param min_new_tokens: generation min tokens
- :param early_stopping: generation early stopping
- :param max_time: maximum time to allow for generation
- :param memory_restriction_level: 0 = no restriction to tokens or model, 1 = some restrictions on token 2 = HF like restriction 3 = very low memory case
- :param debug: enable debug mode
- :param save_dir: directory chat data is saved to
- :param share: whether to share the gradio app with sharable URL
- :param local_files_only: whether to only use local files instead of doing to HF for models
- :param resume_download: whether to resume downloads from HF for models
- :param use_auth_token: whether to use HF auth token (requires CLI did huggingface-cli login before)
- :param trust_remote_code: whether to use trust any code needed for HF model
- :param offload_folder: path for spilling model onto disk
- :param src_lang: source languages to include if doing translation (None = all)
- :param tgt_lang: target languages to include if doing translation (None = all)
- :param cli: whether to use CLI (non-gradio) interface.
- :param cli_loop: whether to loop for CLI (False usually only for testing)
- :param gradio: whether to enable gradio, or to enable benchmark mode
- :param gradio_offline_level: > 0, then change fonts so full offline
- == 1 means backend won't need internet for fonts, but front-end UI might if font not cached
- == 2 means backend and frontend don't need internet to download any fonts.
- Note: Some things always disabled include HF telemetry, gradio telemetry, chromadb posthog that involve uploading.
- This option further disables google fonts for downloading, which is less intrusive than uploading,
- but still required in air-gapped case. The fonts don't look as nice as google fonts, but ensure full offline behavior.
- Also set --share=False to avoid sharing a gradio live link.
- :param chat: whether to enable chat mode with chat history
- :param chat_context: whether to use extra helpful context if human_bot
- :param stream_output: whether to stream output
- :param show_examples: whether to show clickable examples in gradio
- :param verbose: whether to show verbose prints
- :param h2ocolors: whether to use H2O.ai theme
- :param dark: whether to use dark mode for UI by default (still controlled in UI)
- :param height: height of chat window
- :param show_lora: whether to show LORA options in UI (expert so can be hard to understand)
- :param login_mode_if_model0: set to True to load --base_model after client logs in, to be able to free GPU memory when model is swapped
- :param block_gradio_exit: whether to block gradio exit (used for testing)
- :param concurrency_count: gradio concurrency count (1 is optimal for LLMs)
- :param api_open: If False, don't let API calls skip gradio queue
- :param allow_api: whether to allow API calls at all to gradio server
- :param input_lines: how many input lines to show for chat box (>1 forces shift-enter for submit, else enter is submit)
- :param gradio_size: Overall size of text and spaces: "xsmall", "small", "medium", "large".
- Small useful for many chatbots in model_lock mode
- :param auth: gradio auth for launcher in form [(user1, pass1), (user2, pass2), ...]
- e.g. --auth=[('jon','password')] with no spaces
- :param max_max_time: Maximum max_time for gradio slider
- :param max_max_new_tokens: Maximum max_new_tokens for gradio slider
- :param sanitize_user_prompt: whether to remove profanity from user input (slows down input processing)
- :param sanitize_bot_response: whether to remove profanity and repeat lines from bot output (about 2x slower generation for long streaming cases due to better_profanity being slow)
- :param extra_model_options: extra models to show in list in gradio
- :param extra_lora_options: extra LORA to show in list in gradio
- :param extra_server_options: extra servers to show in list in gradio
- :param score_model: which model to score responses
- None: no response scoring
- 'auto': auto mode, '' (no model) for CPU, 'OpenAssistant/reward-model-deberta-v3-large-v2' for GPU,
- because on CPU takes too much compute just for scoring response
- :param eval_filename: json file to use for evaluation, if None is sharegpt
- :param eval_prompts_only_num: for no gradio benchmark, if using eval_filename prompts for eval instead of examples
- :param eval_prompts_only_seed: for no gradio benchmark, seed for eval_filename sampling
- :param eval_as_output: for no gradio benchmark, whether to test eval_filename output itself
- :param langchain_mode: Data source to include. Choose "UserData" to only consume files from make_db.py.
- None: auto mode, check if langchain package exists, at least do LLM if so, else Disabled
- WARNING: wiki_full requires extra data processing via read_wiki_full.py and requires really good workstation to generate db, unless already present.
- :param langchain_action: Mode langchain operations in on documents.
- Query: Make query of document(s)
- Summarize or Summarize_map_reduce: Summarize document(s) via map_reduce
- Summarize_all: Summarize document(s) using entire document at once
- Summarize_refine: Summarize document(s) using entire document, and try to refine before returning summary
- :param langchain_agents: Which agents to use
- 'search': Use Web Search as context for LLM response, e.g. SERP if have SERPAPI_API_KEY in env
- :param force_langchain_evaluate: Whether to force langchain LLM use even if not doing langchain, mostly for testing.
- :param user_path: user path to glob from to generate db for vector search, for 'UserData' langchain mode.
- If already have db, any new/changed files are added automatically if path set, does not have to be same path used for prior db sources
- :param langchain_mode_paths: dict of langchain_mode keys and disk path values to use for source of documents
- E.g. "{'UserData2': 'userpath2'}"
- Can be None even if existing DB, to avoid new documents being added from that path, source links that are on disk still work.
- If user_path is not None, that path is used for 'UserData' instead of the value in this dict
- :param detect_user_path_changes_every_query: whether to detect if any files changed or added every similarity search (by file hashes).
- Expensive for large number of files, so not done by default. By default only detect changes during db loading.
- :param langchain_modes: names of collections/dbs to potentially have
- :param visible_langchain_modes: dbs to generate at launch to be ready for LLM
- Can be up to ['wiki', 'wiki_full', 'UserData', 'MyData', 'github h2oGPT', 'DriverlessAI docs']
- But wiki_full is expensive and requires preparation
- To allow scratch space only live in session, add 'MyData' to list
- Default: If only want to consume local files, e.g. prepared by make_db.py, only include ['UserData']
- If have own user modes, need to add these here or add in UI.
- A state file is stored in visible_langchain_modes.pkl containing last UI-selected values of:
- langchain_modes, visible_langchain_modes, and langchain_mode_paths
- Delete the file if you want to start fresh,
- but in any case the user_path passed in CLI is used for UserData even if was None or different
- :param visible_langchain_actions: Which actions to allow
- :param visible_langchain_agents: Which agents to allow
- :param document_subset: Default document choice when taking subset of collection
- :param document_choice: Chosen document(s) by internal name, 'All' means use all docs
- :param use_llm_if_no_docs: Whether to use LLM even if no documents, when langchain_mode=UserData or MyData or custom
- :param load_db_if_exists: Whether to load chroma db if exists or re-generate db
- :param keep_sources_in_context: Whether to keep url sources in context, not helpful usually
- :param db_type: 'faiss' for in-memory or 'chroma' or 'weaviate' for persisted on disk
- :param use_openai_embedding: Whether to use OpenAI embeddings for vector db
- :param use_openai_model: Whether to use OpenAI model for use with vector db
- :param hf_embedding_model: Which HF embedding model to use for vector db
- Default is instructor-large with 768 parameters per embedding if have GPUs, else all-MiniLM-L6-v2 if no GPUs
- Can also choose simpler model with 384 parameters per embedding: "sentence-transformers/all-MiniLM-L6-v2"
- Can also choose even better embedding with 1024 parameters: 'hkunlp/instructor-xl'
- We support automatically changing of embeddings for chroma, with a backup of db made if this is done
- :param cut_distance: Distance to cut off references with larger distances when showing references.
- 1.64 is good to avoid dropping references for all-MiniLM-L6-v2, but instructor-large will always show excessive references.
- For all-MiniLM-L6-v2, a value of 1.5 can push out even more references, or a large value of 100 can avoid any loss of references.
- :param add_chat_history_to_context: Include chat context when performing action
- Not supported yet for openai_chat when using document collection instead of LLM
- Also not supported when using CLI mode
- :param allow_upload_to_user_data: Whether to allow file uploads to update shared vector db (UserData or custom user dbs)
- :param reload_langchain_state: Whether to reload visible_langchain_modes.pkl file that contains any new user collections.
- :param allow_upload_to_my_data: Whether to allow file uploads to update scratch vector db
- :param enable_url_upload: Whether to allow upload from URL
- :param enable_text_upload: Whether to allow upload of text
- :param enable_sources_list: Whether to allow list (or download for non-shared db) of list of sources for chosen db
- :param chunk: Whether to chunk data (True unless know data is already optimally chunked)
- :param chunk_size: Size of chunks, with typically top-4 passed to LLM, so needs to be in context length
- :param top_k_docs: number of chunks to give LLM
- :param reverse_docs: whether to reverse docs order so most relevant is closest to question.
- Best choice for sufficiently smart model, and truncation occurs for oldest context, so best then too.
- But smaller 6_9 models fail to use newest context and can get stuck on old information.
- :param auto_reduce_chunks: Whether to automatically reduce top_k_docs to fit context given prompt
- :param max_chunks: If top_k_docs=-1, maximum number of chunks to allow
- :param n_jobs: Number of processors to use when consuming documents (-1 = all, is default)
- :param enable_captions: Whether to support captions using BLIP for image files as documents, then preloads that model
- :param captions_model: Which model to use for captions.
- captions_model: str = "Salesforce/blip-image-captioning-base", # continue capable
- captions_model: str = "Salesforce/blip2-flan-t5-xl", # question/answer capable, 16GB state
- captions_model: str = "Salesforce/blip2-flan-t5-xxl", # question/answer capable, 60GB state
- Note: opt-based blip2 are not permissive license due to opt and Meta license restrictions
- Disabled for CPU since BLIP requires CUDA
- :param pre_load_caption_model: Whether to preload caption model, or load after forking parallel doc loader
- parallel loading disabled if preload and have images, to prevent deadlocking on cuda context
- Recommended if using larger caption model
- :param caption_gpu: If support caption, then use GPU if exists
- :param enable_ocr: Whether to support OCR on images
- :param enable_pdf_ocr: 'auto' means only use OCR if normal text extraction fails. Useful for pure image-based PDFs with text
- 'on' means always do OCR as additional parsing of same documents
- 'off' means don't do OCR (e.g. because it's slow even if 'auto' only would trigger if nothing else worked)
- :return:
- """
- if base_model is None:
- base_model = ''
- if tokenizer_base_model is None:
- tokenizer_base_model = ''
- if lora_weights is None:
- lora_weights = ''
- if inference_server is None:
- inference_server = ''
-
- # listen to env if set
- model_lock = os.getenv('model_lock', str(model_lock))
- model_lock = ast.literal_eval(model_lock)
-
- if model_lock:
- assert gradio, "model_lock only supported for gradio=True"
- if len(model_lock) > 1:
- assert chat, "model_lock only works for multiple models for chat=True"
- assert not cli, "model_lock only supported for cli=False"
- assert not (not cli and not gradio), "model_lock only supported for eval (cli=gradio=False)"
- assert not base_model, "Don't specify model_lock and base_model"
- assert not tokenizer_base_model, "Don't specify model_lock and tokenizer_base_model"
- assert not lora_weights, "Don't specify model_lock and lora_weights"
- assert not inference_server, "Don't specify model_lock and inference_server"
- # assert not prompt_type, "Don't specify model_lock and prompt_type"
- # assert not prompt_dict, "Don't specify model_lock and prompt_dict"
-
- n_jobs = int(os.getenv('n_jobs', str(n_jobs)))
- is_hf = bool(int(os.getenv("HUGGINGFACE_SPACES", '0')))
- is_gpth2oai = bool(int(os.getenv("GPT_H2O_AI", '0')))
- is_public = is_hf or is_gpth2oai # multi-user case with fixed model and disclaimer
- if memory_restriction_level is None:
- memory_restriction_level = 2 if is_hf else 0 # 2 assumes run on 24GB consumer GPU
- else:
- assert 0 <= memory_restriction_level <= 3, "Bad memory_restriction_level=%s" % memory_restriction_level
- if is_public and os.getenv('n_jobs') is None:
- n_jobs = max(1, min(os.cpu_count() // 2, 8))
- admin_pass = os.getenv("ADMIN_PASS")
- # will sometimes appear in UI or sometimes actual generation, but maybe better than empty result
- # but becomes unrecoverable sometimes if raise, so just be silent for now
- raise_generate_gpu_exceptions = True
-
- # allow set token directly
- use_auth_token = os.environ.get("HUGGINGFACE_API_TOKEN", use_auth_token)
- allow_upload_to_user_data = bool(
- int(os.environ.get("allow_upload_to_user_data", str(int(allow_upload_to_user_data)))))
- allow_upload_to_my_data = bool(int(os.environ.get("allow_upload_to_my_data", str(int(allow_upload_to_my_data)))))
- height = int(os.environ.get("HEIGHT", height))
- h2ocolors = bool(int(os.getenv('h2ocolors', h2ocolors)))
-
- # allow enabling langchain via ENV
- # FIRST PLACE where LangChain referenced, but no imports related to it
- langchain_mode = os.environ.get("LANGCHAIN_MODE", langchain_mode)
- if langchain_mode is not None:
- assert langchain_mode in langchain_modes, "Invalid langchain_mode %s" % langchain_mode
- visible_langchain_modes = ast.literal_eval(os.environ.get("visible_langchain_modes", str(visible_langchain_modes)))
- if langchain_mode not in visible_langchain_modes and langchain_mode in langchain_modes:
- if langchain_mode is not None:
- visible_langchain_modes += [langchain_mode]
-
- # update
- if isinstance(langchain_mode_paths, str):
- langchain_mode_paths = ast.literal_eval(langchain_mode_paths)
- assert isinstance(langchain_mode_paths, dict)
- if user_path:
- langchain_mode_paths['UserData'] = user_path
- makedirs(user_path)
-
- if is_public:
- allow_upload_to_user_data = False
- if LangChainMode.USER_DATA.value in visible_langchain_modes:
- visible_langchain_modes.remove(LangChainMode.USER_DATA.value)
-
- # in-place, for non-scratch dbs
- if allow_upload_to_user_data:
- update_langchain(langchain_modes, visible_langchain_modes, langchain_mode_paths, '')
- # always listen to CLI-passed user_path if passed
- if user_path:
- langchain_mode_paths['UserData'] = user_path
-
- assert langchain_action in langchain_actions, "Invalid langchain_action %s" % langchain_action
- assert len(
- set(langchain_agents).difference(langchain_agents_list)) == 0, "Invalid langchain_agents %s" % langchain_agents
-
- # if specifically chose not to show My or User Data, disable upload, so gradio elements are simpler
- if LangChainMode.MY_DATA.value not in visible_langchain_modes:
- allow_upload_to_my_data = False
- if LangChainMode.USER_DATA.value not in visible_langchain_modes:
- allow_upload_to_user_data = False
-
- # auto-set langchain_mode
- if have_langchain and langchain_mode is None:
- # start in chat mode, in case just want to chat and don't want to get "No documents to query" by default.
- langchain_mode = LangChainMode.LLM.value
- if allow_upload_to_user_data and not is_public and langchain_mode_paths['UserData']:
- print("Auto set langchain_mode=%s. Could use UserData instead." % langchain_mode, flush=True)
- elif allow_upload_to_my_data:
- print("Auto set langchain_mode=%s. Could use MyData instead."
- " To allow UserData to pull files from disk,"
- " set user_path or langchain_mode_paths, and ensure allow_upload_to_user_data=True" % langchain_mode,
- flush=True)
- else:
- raise RuntimeError("Please pass --langchain_mode= '):
- prompt = prompt[:-4]
- prompt = prompt.replace(' ".join(answer_sources)
- sorted_sources_urls += f" DISCLAIMERS:
', chat_turn_sep)
- if not prompt.endswith(chat_turn_sep):
- prompt += chat_turn_sep
- # most recent first, add older if can
- # only include desired chat history
- if len(prompt + context1) > max_prompt_length:
- break
- context1 += prompt
-
- _, pre_response, terminate_response, chat_sep, chat_turn_sep = generate_prompt({}, prompt_type1, prompt_dict1,
- chat1, reduced=True,
- making_context=True)
- if context1 and not context1.endswith(chat_turn_sep):
- context1 += chat_turn_sep # ensure if terminates abruptly, then human continues on next line
- return context1
-
-
-def update_langchain(langchain_modes, visible_langchain_modes, langchain_mode_paths, extra):
- # update from saved state on disk
- langchain_modes_from_file, visible_langchain_modes_from_file, langchain_mode_paths_from_file = \
- load_collection_enum(extra)
-
- visible_langchain_modes_temp = visible_langchain_modes.copy() + visible_langchain_modes_from_file
- visible_langchain_modes.clear() # don't lose original reference
- [visible_langchain_modes.append(x) for x in visible_langchain_modes_temp if x not in visible_langchain_modes]
-
- langchain_mode_paths.update(langchain_mode_paths_from_file)
-
- langchain_modes_temp = langchain_modes.copy() + langchain_modes_from_file
- langchain_modes.clear() # don't lose original reference
- [langchain_modes.append(x) for x in langchain_modes_temp if x not in langchain_modes]
-
-
-def entrypoint_main():
- """
- Examples:
-
- WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 --master_port=1234 generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights=lora-alpaca_6B
- python generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights='lora-alpaca_6B'
- python generate.py --base_model='EleutherAI/gpt-neox-20b' --lora_weights='lora-alpaca_20B'
-
- # generate without lora weights, no prompt
- python generate.py --base_model='EleutherAI/gpt-neox-20b' --prompt_type='plain'
- python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='dai_faq'
-
- python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='dai_faq' --lora_weights='lora_20B_daifaq'
- # OpenChatKit settings:
- python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='human_bot --debug=True --num_beams=1 --temperature=0.6 --top_k=40 --top_p=1.0
-
- python generate.py --base_model='distilgpt2' --prompt_type='plain' --debug=True --num_beams=1 --temperature=0.6 --top_k=40 --top_p=1.0 --share=False
- python generate.py --base_model='t5-large' --prompt_type='simple_instruct'
- python generate.py --base_model='philschmid/bart-large-cnn-samsum'
- python generate.py --base_model='philschmid/flan-t5-base-samsum'
- python generate.py --base_model='facebook/mbart-large-50-many-to-many-mmt'
-
- python generate.py --base_model='togethercomputer/GPT-NeoXT-Chat-Base-20B' --prompt_type='human_bot' --lora_weights='GPT-NeoXT-Chat-Base-20B.merged.json.8_epochs.57b2892c53df5b8cefac45f84d019cace803ef26.28'
-
- must have 4*48GB GPU and run without 8bit in order for sharding to work with use_gpu_id=False
- can also pass --prompt_type='human_bot' and model can somewhat handle instructions without being instruct tuned
- python generate.py --base_model=decapoda-research/llama-65b-hf --load_8bit=False --use_gpu_id=False --prompt_type='human_bot'
-
- python generate.py --base_model=h2oai/h2ogpt-oig-oasst1-512-6_9b
- """
- fire.Fire(main)
-
-
-if __name__ == "__main__":
- entrypoint_main()
diff --git a/gpt4all_llm.py b/gpt4all_llm.py
deleted file mode 100644
index 125892d99621ca80ad4ea6efcc39b01fa5cead63..0000000000000000000000000000000000000000
--- a/gpt4all_llm.py
+++ /dev/null
@@ -1,316 +0,0 @@
-import inspect
-import os
-from functools import partial
-from typing import Dict, Any, Optional, List
-from langchain.callbacks.manager import CallbackManagerForLLMRun
-from pydantic import root_validator
-from langchain.llms import gpt4all
-from dotenv import dotenv_values
-
-from utils import FakeTokenizer
-
-
-def get_model_tokenizer_gpt4all(base_model, **kwargs):
- # defaults (some of these are generation parameters, so need to be passed in at generation time)
- model_kwargs = dict(n_threads=os.cpu_count() // 2,
- temp=kwargs.get('temperature', 0.2),
- top_p=kwargs.get('top_p', 0.75),
- top_k=kwargs.get('top_k', 40),
- n_ctx=2048 - 256)
- env_gpt4all_file = ".env_gpt4all"
- model_kwargs.update(dotenv_values(env_gpt4all_file))
- # make int or float if can to satisfy types for class
- for k, v in model_kwargs.items():
- try:
- if float(v) == int(v):
- model_kwargs[k] = int(v)
- else:
- model_kwargs[k] = float(v)
- except:
- pass
-
- if base_model == "llama":
- if 'model_path_llama' not in model_kwargs:
- raise ValueError("No model_path_llama in %s" % env_gpt4all_file)
- model_path = model_kwargs.pop('model_path_llama')
- # FIXME: GPT4All version of llama doesn't handle new quantization, so use llama_cpp_python
- from llama_cpp import Llama
- # llama sets some things at init model time, not generation time
- func_names = list(inspect.signature(Llama.__init__).parameters)
- model_kwargs = {k: v for k, v in model_kwargs.items() if k in func_names}
- model_kwargs['n_ctx'] = int(model_kwargs['n_ctx'])
- model = Llama(model_path=model_path, **model_kwargs)
- elif base_model in "gpt4all_llama":
- if 'model_name_gpt4all_llama' not in model_kwargs and 'model_path_gpt4all_llama' not in model_kwargs:
- raise ValueError("No model_name_gpt4all_llama or model_path_gpt4all_llama in %s" % env_gpt4all_file)
- model_name = model_kwargs.pop('model_name_gpt4all_llama')
- model_type = 'llama'
- from gpt4all import GPT4All as GPT4AllModel
- model = GPT4AllModel(model_name=model_name, model_type=model_type)
- elif base_model in "gptj":
- if 'model_name_gptj' not in model_kwargs and 'model_path_gptj' not in model_kwargs:
- raise ValueError("No model_name_gpt4j or model_path_gpt4j in %s" % env_gpt4all_file)
- model_name = model_kwargs.pop('model_name_gptj')
- model_type = 'gptj'
- from gpt4all import GPT4All as GPT4AllModel
- model = GPT4AllModel(model_name=model_name, model_type=model_type)
- else:
- raise ValueError("No such base_model %s" % base_model)
- return model, FakeTokenizer(), 'cpu'
-
-
-from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
-
-
-class H2OStreamingStdOutCallbackHandler(StreamingStdOutCallbackHandler):
-
- def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
- """Run on new LLM token. Only available when streaming is enabled."""
- # streaming to std already occurs without this
- # sys.stdout.write(token)
- # sys.stdout.flush()
- pass
-
-
-def get_model_kwargs(env_kwargs, default_kwargs, cls, exclude_list=[]):
- # default from class
- model_kwargs = {k: v.default for k, v in dict(inspect.signature(cls).parameters).items() if k not in exclude_list}
- # from our defaults
- model_kwargs.update(default_kwargs)
- # from user defaults
- model_kwargs.update(env_kwargs)
- # ensure only valid keys
- func_names = list(inspect.signature(cls).parameters)
- model_kwargs = {k: v for k, v in model_kwargs.items() if k in func_names}
- return model_kwargs
-
-
-def get_llm_gpt4all(model_name,
- model=None,
- max_new_tokens=256,
- temperature=0.1,
- repetition_penalty=1.0,
- top_k=40,
- top_p=0.7,
- streaming=False,
- callbacks=None,
- prompter=None,
- context='',
- iinput='',
- verbose=False,
- ):
- assert prompter is not None
- env_gpt4all_file = ".env_gpt4all"
- env_kwargs = dotenv_values(env_gpt4all_file)
- max_tokens = env_kwargs.pop('max_tokens', 2048 - max_new_tokens)
- default_kwargs = dict(context_erase=0.5,
- n_batch=1,
- max_tokens=max_tokens,
- n_predict=max_new_tokens,
- repeat_last_n=64 if repetition_penalty != 1.0 else 0,
- repeat_penalty=repetition_penalty,
- temp=temperature,
- temperature=temperature,
- top_k=top_k,
- top_p=top_p,
- use_mlock=True,
- verbose=verbose)
- if model_name == 'llama':
- cls = H2OLlamaCpp
- model_path = env_kwargs.pop('model_path_llama') if model is None else model
- model_kwargs = get_model_kwargs(env_kwargs, default_kwargs, cls, exclude_list=['lc_kwargs'])
- model_kwargs.update(dict(model_path=model_path, callbacks=callbacks, streaming=streaming,
- prompter=prompter, context=context, iinput=iinput))
- llm = cls(**model_kwargs)
- llm.client.verbose = verbose
- elif model_name == 'gpt4all_llama':
- cls = H2OGPT4All
- model_path = env_kwargs.pop('model_path_gpt4all_llama') if model is None else model
- model_kwargs = get_model_kwargs(env_kwargs, default_kwargs, cls, exclude_list=['lc_kwargs'])
- model_kwargs.update(
- dict(model=model_path, backend='llama', callbacks=callbacks, streaming=streaming,
- prompter=prompter, context=context, iinput=iinput))
- llm = cls(**model_kwargs)
- elif model_name == 'gptj':
- cls = H2OGPT4All
- model_path = env_kwargs.pop('model_path_gptj') if model is None else model
- model_kwargs = get_model_kwargs(env_kwargs, default_kwargs, cls, exclude_list=['lc_kwargs'])
- model_kwargs.update(
- dict(model=model_path, backend='gptj', callbacks=callbacks, streaming=streaming,
- prompter=prompter, context=context, iinput=iinput))
- llm = cls(**model_kwargs)
- else:
- raise RuntimeError("No such model_name %s" % model_name)
- return llm
-
-
-class H2OGPT4All(gpt4all.GPT4All):
- model: Any
- prompter: Any
- context: Any = ''
- iinput: Any = ''
- """Path to the pre-trained GPT4All model file."""
-
- @root_validator()
- def validate_environment(cls, values: Dict) -> Dict:
- """Validate that the python package exists in the environment."""
- try:
- if isinstance(values["model"], str):
- from gpt4all import GPT4All as GPT4AllModel
-
- full_path = values["model"]
- model_path, delimiter, model_name = full_path.rpartition("/")
- model_path += delimiter
-
- values["client"] = GPT4AllModel(
- model_name=model_name,
- model_path=model_path or None,
- model_type=values["backend"],
- allow_download=False,
- )
- if values["n_threads"] is not None:
- # set n_threads
- values["client"].model.set_thread_count(values["n_threads"])
- else:
- values["client"] = values["model"]
- try:
- values["backend"] = values["client"].model_type
- except AttributeError:
- # The below is for compatibility with GPT4All Python bindings <= 0.2.3.
- values["backend"] = values["client"].model.model_type
-
- except ImportError:
- raise ValueError(
- "Could not import gpt4all python package. "
- "Please install it with `pip install gpt4all`."
- )
- return values
-
- def _call(
- self,
- prompt: str,
- stop: Optional[List[str]] = None,
- run_manager: Optional[CallbackManagerForLLMRun] = None,
- **kwargs,
- ) -> str:
- # Roughly 4 chars per token if natural language
- n_ctx = 2048
- prompt = prompt[-self.max_tokens * 4:]
-
- # use instruct prompting
- data_point = dict(context=self.context, instruction=prompt, input=self.iinput)
- prompt = self.prompter.generate_prompt(data_point)
-
- verbose = False
- if verbose:
- print("_call prompt: %s" % prompt, flush=True)
- # FIXME: GPT4ALl doesn't support yield during generate, so cannot support streaming except via itself to stdout
- return super()._call(prompt, stop=stop, run_manager=run_manager)
-
-
-from langchain.llms import LlamaCpp
-
-
-class H2OLlamaCpp(LlamaCpp):
- model_path: Any
- prompter: Any
- context: Any
- iinput: Any
- """Path to the pre-trained GPT4All model file."""
-
- @root_validator()
- def validate_environment(cls, values: Dict) -> Dict:
- """Validate that llama-cpp-python library is installed."""
- if isinstance(values["model_path"], str):
- model_path = values["model_path"]
- model_param_names = [
- "lora_path",
- "lora_base",
- "n_ctx",
- "n_parts",
- "seed",
- "f16_kv",
- "logits_all",
- "vocab_only",
- "use_mlock",
- "n_threads",
- "n_batch",
- "use_mmap",
- "last_n_tokens_size",
- ]
- model_params = {k: values[k] for k in model_param_names}
- # For backwards compatibility, only include if non-null.
- if values["n_gpu_layers"] is not None:
- model_params["n_gpu_layers"] = values["n_gpu_layers"]
-
- try:
- from llama_cpp import Llama
-
- values["client"] = Llama(model_path, **model_params)
- except ImportError:
- raise ModuleNotFoundError(
- "Could not import llama-cpp-python library. "
- "Please install the llama-cpp-python library to "
- "use this embedding model: pip install llama-cpp-python"
- )
- except Exception as e:
- raise ValueError(
- f"Could not load Llama model from path: {model_path}. "
- f"Received error {e}"
- )
- else:
- values["client"] = values["model_path"]
- return values
-
- def _call(
- self,
- prompt: str,
- stop: Optional[List[str]] = None,
- run_manager: Optional[CallbackManagerForLLMRun] = None,
- **kwargs,
- ) -> str:
- verbose = False
- # tokenize twice, just to count tokens, since llama cpp python wrapper has no way to truncate
- # still have to avoid crazy sizes, else hit llama_tokenize: too many tokens -- might still hit, not fatal
- prompt = prompt[-self.n_ctx * 4:]
- prompt_tokens = self.client.tokenize(b" " + prompt.encode("utf-8"))
- num_prompt_tokens = len(prompt_tokens)
- if num_prompt_tokens > self.n_ctx:
- # conservative by using int()
- chars_per_token = int(len(prompt) / num_prompt_tokens)
- prompt = prompt[-self.n_ctx * chars_per_token:]
- if verbose:
- print("reducing tokens, assuming average of %s chars/token: %s" % chars_per_token, flush=True)
- prompt_tokens2 = self.client.tokenize(b" " + prompt.encode("utf-8"))
- num_prompt_tokens2 = len(prompt_tokens2)
- print("reduced tokens from %d -> %d" % (num_prompt_tokens, num_prompt_tokens2), flush=True)
-
- # use instruct prompting
- data_point = dict(context=self.context, instruction=prompt, input=self.iinput)
- prompt = self.prompter.generate_prompt(data_point)
-
- if verbose:
- print("_call prompt: %s" % prompt, flush=True)
-
- if self.streaming:
- text_callback = None
- if run_manager:
- text_callback = partial(
- run_manager.on_llm_new_token, verbose=self.verbose
- )
- # parent handler of streamer expects to see prompt first else output="" and lose if prompt=None in prompter
- if text_callback:
- text_callback(prompt)
- text = ""
- for token in self.stream(prompt=prompt, stop=stop, run_manager=run_manager):
- text_chunk = token["choices"][0]["text"]
- # self.stream already calls text_callback
- # if text_callback:
- # text_callback(text_chunk)
- text += text_chunk
- return text
- else:
- params = self._get_parameters(stop)
- params = {**params, **kwargs}
- result = self.client(prompt=prompt, **params)
- return result["choices"][0]["text"]
diff --git a/gpt_langchain.py b/gpt_langchain.py
deleted file mode 100644
index c2a3438e865fac91693a84625bc0709332ba6e82..0000000000000000000000000000000000000000
--- a/gpt_langchain.py
+++ /dev/null
@@ -1,2559 +0,0 @@
-import ast
-import glob
-import inspect
-import os
-import pathlib
-import pickle
-import shutil
-import subprocess
-import tempfile
-import time
-import traceback
-import types
-import uuid
-import zipfile
-from collections import defaultdict
-from datetime import datetime
-from functools import reduce
-from operator import concat
-import filelock
-
-from joblib import delayed
-from langchain.callbacks import streaming_stdout
-from langchain.embeddings import HuggingFaceInstructEmbeddings
-from langchain.schema import LLMResult
-from tqdm import tqdm
-
-from enums import DocumentSubset, no_lora_str, model_token_mapping, source_prefix, source_postfix, non_query_commands, \
- LangChainAction, LangChainMode, DocumentChoice
-from evaluate_params import gen_hyper
-from gen import get_model, SEED
-from prompter import non_hf_types, PromptType, Prompter
-from utils import wrapped_partial, EThread, import_matplotlib, sanitize_filename, makedirs, get_url, flatten_list, \
- get_device, ProgressParallel, remove, hash_file, clear_torch_cache, NullContext, get_hf_server, FakeTokenizer, \
- have_libreoffice, have_arxiv, have_playwright, have_selenium, have_tesseract, have_pymupdf, set_openai
-from utils_langchain import StreamingGradioCallbackHandler
-
-import_matplotlib()
-
-import numpy as np
-import pandas as pd
-import requests
-from langchain.chains.qa_with_sources import load_qa_with_sources_chain
-# , GCSDirectoryLoader, GCSFileLoader
-# , OutlookMessageLoader # GPL3
-# ImageCaptionLoader, # use our own wrapper
-# ReadTheDocsLoader, # no special file, some path, so have to give as special option
-from langchain.document_loaders import PyPDFLoader, TextLoader, CSVLoader, PythonLoader, TomlLoader, \
- UnstructuredURLLoader, UnstructuredHTMLLoader, UnstructuredWordDocumentLoader, UnstructuredMarkdownLoader, \
- EverNoteLoader, UnstructuredEmailLoader, UnstructuredODTLoader, UnstructuredPowerPointLoader, \
- UnstructuredEPubLoader, UnstructuredImageLoader, UnstructuredRTFLoader, ArxivLoader, UnstructuredPDFLoader, \
- UnstructuredExcelLoader
-from langchain.text_splitter import RecursiveCharacterTextSplitter, Language
-from langchain.chains.question_answering import load_qa_chain
-from langchain.docstore.document import Document
-from langchain import PromptTemplate, HuggingFaceTextGenInference
-from langchain.vectorstores import Chroma
-
-
-def get_db(sources, use_openai_embedding=False, db_type='faiss',
- persist_directory="db_dir", load_db_if_exists=True,
- langchain_mode='notset',
- collection_name=None,
- hf_embedding_model="sentence-transformers/all-MiniLM-L6-v2"):
- if not sources:
- return None
-
- # get embedding model
- embedding = get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model)
- assert collection_name is not None or langchain_mode != 'notset'
- if collection_name is None:
- collection_name = langchain_mode.replace(' ', '_')
-
- # Create vector database
- if db_type == 'faiss':
- from langchain.vectorstores import FAISS
- db = FAISS.from_documents(sources, embedding)
- elif db_type == 'weaviate':
- import weaviate
- from weaviate.embedded import EmbeddedOptions
- from langchain.vectorstores import Weaviate
-
- if os.getenv('WEAVIATE_URL', None):
- client = _create_local_weaviate_client()
- else:
- client = weaviate.Client(
- embedded_options=EmbeddedOptions()
- )
- index_name = collection_name.capitalize()
- db = Weaviate.from_documents(documents=sources, embedding=embedding, client=client, by_text=False,
- index_name=index_name)
- elif db_type == 'chroma':
- assert persist_directory is not None
- os.makedirs(persist_directory, exist_ok=True)
-
- # see if already actually have persistent db, and deal with possible changes in embedding
- db = get_existing_db(None, persist_directory, load_db_if_exists, db_type, use_openai_embedding, langchain_mode,
- hf_embedding_model, verbose=False)
- if db is None:
- from chromadb.config import Settings
- client_settings = Settings(anonymized_telemetry=False,
- chroma_db_impl="duckdb+parquet",
- persist_directory=persist_directory)
- db = Chroma.from_documents(documents=sources,
- embedding=embedding,
- persist_directory=persist_directory,
- collection_name=collection_name,
- client_settings=client_settings)
- db.persist()
- clear_embedding(db)
- save_embed(db, use_openai_embedding, hf_embedding_model)
- else:
- # then just add
- db, num_new_sources, new_sources_metadata = add_to_db(db, sources, db_type=db_type,
- use_openai_embedding=use_openai_embedding,
- hf_embedding_model=hf_embedding_model)
- else:
- raise RuntimeError("No such db_type=%s" % db_type)
-
- return db
-
-
-def _get_unique_sources_in_weaviate(db):
- batch_size = 100
- id_source_list = []
- result = db._client.data_object.get(class_name=db._index_name, limit=batch_size)
-
- while result['objects']:
- id_source_list += [(obj['id'], obj['properties']['source']) for obj in result['objects']]
- last_id = id_source_list[-1][0]
- result = db._client.data_object.get(class_name=db._index_name, limit=batch_size, after=last_id)
-
- unique_sources = {source for _, source in id_source_list}
- return unique_sources
-
-
-def add_to_db(db, sources, db_type='faiss',
- avoid_dup_by_file=False,
- avoid_dup_by_content=True,
- use_openai_embedding=False,
- hf_embedding_model=None):
- assert hf_embedding_model is not None
- num_new_sources = len(sources)
- if not sources:
- return db, num_new_sources, []
- if db_type == 'faiss':
- db.add_documents(sources)
- elif db_type == 'weaviate':
- # FIXME: only control by file name, not hash yet
- if avoid_dup_by_file or avoid_dup_by_content:
- unique_sources = _get_unique_sources_in_weaviate(db)
- sources = [x for x in sources if x.metadata['source'] not in unique_sources]
- num_new_sources = len(sources)
- if num_new_sources == 0:
- return db, num_new_sources, []
- db.add_documents(documents=sources)
- elif db_type == 'chroma':
- collection = get_documents(db)
- # files we already have:
- metadata_files = set([x['source'] for x in collection['metadatas']])
- if avoid_dup_by_file:
- # Too weak in case file changed content, assume parent shouldn't pass true for this for now
- raise RuntimeError("Not desired code path")
- sources = [x for x in sources if x.metadata['source'] not in metadata_files]
- if avoid_dup_by_content:
- # look at hash, instead of page_content
- # migration: If no hash previously, avoid updating,
- # since don't know if need to update and may be expensive to redo all unhashed files
- metadata_hash_ids = set(
- [x['hashid'] for x in collection['metadatas'] if 'hashid' in x and x['hashid'] not in ["None", None]])
- # avoid sources with same hash
- sources = [x for x in sources if x.metadata.get('hashid') not in metadata_hash_ids]
- num_nohash = len([x for x in sources if not x.metadata.get('hashid')])
- print("Found %s new sources (%d have no hash in original source,"
- " so have to reprocess for migration to sources with hash)" % (len(sources), num_nohash), flush=True)
- # get new file names that match existing file names. delete existing files we are overridding
- dup_metadata_files = set([x.metadata['source'] for x in sources if x.metadata['source'] in metadata_files])
- print("Removing %s duplicate files from db because ingesting those as new documents" % len(
- dup_metadata_files), flush=True)
- client_collection = db._client.get_collection(name=db._collection.name,
- embedding_function=db._collection._embedding_function)
- for dup_file in dup_metadata_files:
- dup_file_meta = dict(source=dup_file)
- try:
- client_collection.delete(where=dup_file_meta)
- except KeyError:
- pass
- num_new_sources = len(sources)
- if num_new_sources == 0:
- return db, num_new_sources, []
- db.add_documents(documents=sources)
- db.persist()
- clear_embedding(db)
- save_embed(db, use_openai_embedding, hf_embedding_model)
- else:
- raise RuntimeError("No such db_type=%s" % db_type)
-
- new_sources_metadata = [x.metadata for x in sources]
-
- return db, num_new_sources, new_sources_metadata
-
-
-def create_or_update_db(db_type, persist_directory, collection_name,
- sources, use_openai_embedding, add_if_exists, verbose, hf_embedding_model):
- if db_type == 'weaviate':
- import weaviate
- from weaviate.embedded import EmbeddedOptions
-
- if os.getenv('WEAVIATE_URL', None):
- client = _create_local_weaviate_client()
- else:
- client = weaviate.Client(
- embedded_options=EmbeddedOptions()
- )
-
- index_name = collection_name.replace(' ', '_').capitalize()
- if client.schema.exists(index_name) and not add_if_exists:
- client.schema.delete_class(index_name)
- if verbose:
- print("Removing %s" % index_name, flush=True)
- elif db_type == 'chroma':
- if not os.path.isdir(persist_directory) or not add_if_exists:
- if os.path.isdir(persist_directory):
- if verbose:
- print("Removing %s" % persist_directory, flush=True)
- remove(persist_directory)
- if verbose:
- print("Generating db", flush=True)
-
- if not add_if_exists:
- if verbose:
- print("Generating db", flush=True)
- else:
- if verbose:
- print("Loading and updating db", flush=True)
-
- db = get_db(sources,
- use_openai_embedding=use_openai_embedding,
- db_type=db_type,
- persist_directory=persist_directory,
- langchain_mode=collection_name,
- hf_embedding_model=hf_embedding_model)
-
- return db
-
-
-def get_embedding(use_openai_embedding, hf_embedding_model="sentence-transformers/all-MiniLM-L6-v2"):
- # Get embedding model
- if use_openai_embedding:
- assert os.getenv("OPENAI_API_KEY") is not None, "Set ENV OPENAI_API_KEY"
- from langchain.embeddings import OpenAIEmbeddings
- embedding = OpenAIEmbeddings(disallowed_special=())
- else:
- # to ensure can fork without deadlock
- from langchain.embeddings import HuggingFaceEmbeddings
-
- device, torch_dtype, context_class = get_device_dtype()
- model_kwargs = dict(device=device)
- if 'instructor' in hf_embedding_model:
- encode_kwargs = {'normalize_embeddings': True}
- embedding = HuggingFaceInstructEmbeddings(model_name=hf_embedding_model,
- model_kwargs=model_kwargs,
- encode_kwargs=encode_kwargs)
- else:
- embedding = HuggingFaceEmbeddings(model_name=hf_embedding_model, model_kwargs=model_kwargs)
- return embedding
-
-
-def get_answer_from_sources(chain, sources, question):
- return chain(
- {
- "input_documents": sources,
- "question": question,
- },
- return_only_outputs=True,
- )["output_text"]
-
-
-"""Wrapper around Huggingface text generation inference API."""
-from functools import partial
-from typing import Any, Dict, List, Optional, Set
-
-from pydantic import Extra, Field, root_validator
-
-from langchain.callbacks.manager import CallbackManagerForLLMRun, Callbacks
-from langchain.llms.base import LLM
-
-
-class GradioInference(LLM):
- """
- Gradio generation inference API.
- """
- inference_server_url: str = ""
-
- temperature: float = 0.8
- top_p: Optional[float] = 0.95
- top_k: Optional[int] = None
- num_beams: Optional[int] = 1
- max_new_tokens: int = 512
- min_new_tokens: int = 1
- early_stopping: bool = False
- max_time: int = 180
- repetition_penalty: Optional[float] = None
- num_return_sequences: Optional[int] = 1
- do_sample: bool = False
- chat_client: bool = False
-
- return_full_text: bool = True
- stream: bool = False
- sanitize_bot_response: bool = False
-
- prompter: Any = None
- context: Any = ''
- iinput: Any = ''
- client: Any = None
-
- class Config:
- """Configuration for this pydantic object."""
-
- extra = Extra.forbid
-
- @root_validator()
- def validate_environment(cls, values: Dict) -> Dict:
- """Validate that python package exists in environment."""
-
- try:
- if values['client'] is None:
- import gradio_client
- values["client"] = gradio_client.Client(
- values["inference_server_url"]
- )
- except ImportError:
- raise ImportError(
- "Could not import gradio_client python package. "
- "Please install it with `pip install gradio_client`."
- )
- return values
-
- @property
- def _llm_type(self) -> str:
- """Return type of llm."""
- return "gradio_inference"
-
- def _call(
- self,
- prompt: str,
- stop: Optional[List[str]] = None,
- run_manager: Optional[CallbackManagerForLLMRun] = None,
- **kwargs: Any,
- ) -> str:
- # NOTE: prompt here has no prompt_type (e.g. human: bot:) prompt injection,
- # so server should get prompt_type or '', not plain
- # This is good, so gradio server can also handle stopping.py conditions
- # this is different than TGI server that uses prompter to inject prompt_type prompting
- stream_output = self.stream
- gr_client = self.client
- client_langchain_mode = 'Disabled'
- client_add_chat_history_to_context = True
- client_langchain_action = LangChainAction.QUERY.value
- client_langchain_agents = []
- top_k_docs = 1
- chunk = True
- chunk_size = 512
- client_kwargs = dict(instruction=prompt if self.chat_client else '', # only for chat=True
- iinput=self.iinput if self.chat_client else '', # only for chat=True
- context=self.context,
- # streaming output is supported, loops over and outputs each generation in streaming mode
- # but leave stream_output=False for simple input/output mode
- stream_output=stream_output,
- prompt_type=self.prompter.prompt_type,
- prompt_dict='',
-
- temperature=self.temperature,
- top_p=self.top_p,
- top_k=self.top_k,
- num_beams=self.num_beams,
- max_new_tokens=self.max_new_tokens,
- min_new_tokens=self.min_new_tokens,
- early_stopping=self.early_stopping,
- max_time=self.max_time,
- repetition_penalty=self.repetition_penalty,
- num_return_sequences=self.num_return_sequences,
- do_sample=self.do_sample,
- chat=self.chat_client,
-
- instruction_nochat=prompt if not self.chat_client else '',
- iinput_nochat=self.iinput if not self.chat_client else '',
- langchain_mode=client_langchain_mode,
- add_chat_history_to_context=client_add_chat_history_to_context,
- langchain_action=client_langchain_action,
- langchain_agents=client_langchain_agents,
- top_k_docs=top_k_docs,
- chunk=chunk,
- chunk_size=chunk_size,
- document_subset=DocumentSubset.Relevant.name,
- document_choice=[DocumentChoice.ALL.value],
- )
- api_name = '/submit_nochat_api' # NOTE: like submit_nochat but stable API for string dict passing
- if not stream_output:
- res = gr_client.predict(str(dict(client_kwargs)), api_name=api_name)
- res_dict = ast.literal_eval(res)
- text = res_dict['response']
- return self.prompter.get_response(prompt + text, prompt=prompt,
- sanitize_bot_response=self.sanitize_bot_response)
- else:
- text_callback = None
- if run_manager:
- text_callback = partial(
- run_manager.on_llm_new_token, verbose=self.verbose
- )
-
- job = gr_client.submit(str(dict(client_kwargs)), api_name=api_name)
- text0 = ''
- while not job.done():
- outputs_list = job.communicator.job.outputs
- if outputs_list:
- res = job.communicator.job.outputs[-1]
- res_dict = ast.literal_eval(res)
- text = res_dict['response']
- text = self.prompter.get_response(prompt + text, prompt=prompt,
- sanitize_bot_response=self.sanitize_bot_response)
- # FIXME: derive chunk from full for now
- text_chunk = text[len(text0):]
- # save old
- text0 = text
-
- if text_callback:
- text_callback(text_chunk)
-
- time.sleep(0.01)
-
- # ensure get last output to avoid race
- res_all = job.outputs()
- if len(res_all) > 0:
- res = res_all[-1]
- res_dict = ast.literal_eval(res)
- text = res_dict['response']
- # FIXME: derive chunk from full for now
- else:
- # go with old if failure
- text = text0
- text_chunk = text[len(text0):]
- if text_callback:
- text_callback(text_chunk)
- return self.prompter.get_response(prompt + text, prompt=prompt,
- sanitize_bot_response=self.sanitize_bot_response)
-
-
-class H2OHuggingFaceTextGenInference(HuggingFaceTextGenInference):
- max_new_tokens: int = 512
- do_sample: bool = False
- top_k: Optional[int] = None
- top_p: Optional[float] = 0.95
- typical_p: Optional[float] = 0.95
- temperature: float = 0.8
- repetition_penalty: Optional[float] = None
- return_full_text: bool = False
- stop_sequences: List[str] = Field(default_factory=list)
- seed: Optional[int] = None
- inference_server_url: str = ""
- timeout: int = 300
- headers: dict = None
- stream: bool = False
- sanitize_bot_response: bool = False
- prompter: Any = None
- context: Any = ''
- iinput: Any = ''
- tokenizer: Any = None
- client: Any = None
-
- @root_validator()
- def validate_environment(cls, values: Dict) -> Dict:
- """Validate that python package exists in environment."""
-
- try:
- if values['client'] is None:
- import text_generation
-
- values["client"] = text_generation.Client(
- values["inference_server_url"],
- timeout=values["timeout"],
- headers=values["headers"],
- )
- except ImportError:
- raise ImportError(
- "Could not import text_generation python package. "
- "Please install it with `pip install text_generation`."
- )
- return values
-
- def _call(
- self,
- prompt: str,
- stop: Optional[List[str]] = None,
- run_manager: Optional[CallbackManagerForLLMRun] = None,
- **kwargs: Any,
- ) -> str:
- if stop is None:
- stop = self.stop_sequences
- else:
- stop += self.stop_sequences
-
- # HF inference server needs control over input tokens
- assert self.tokenizer is not None
- from h2oai_pipeline import H2OTextGenerationPipeline
- prompt, num_prompt_tokens = H2OTextGenerationPipeline.limit_prompt(prompt, self.tokenizer)
-
- # NOTE: TGI server does not add prompting, so must do here
- data_point = dict(context=self.context, instruction=prompt, input=self.iinput)
- prompt = self.prompter.generate_prompt(data_point)
-
- gen_server_kwargs = dict(do_sample=self.do_sample,
- stop_sequences=stop,
- max_new_tokens=self.max_new_tokens,
- top_k=self.top_k,
- top_p=self.top_p,
- typical_p=self.typical_p,
- temperature=self.temperature,
- repetition_penalty=self.repetition_penalty,
- return_full_text=self.return_full_text,
- seed=self.seed,
- )
- gen_server_kwargs.update(kwargs)
-
- # lower bound because client is re-used if multi-threading
- self.client.timeout = max(300, self.timeout)
-
- if not self.stream:
- res = self.client.generate(
- prompt,
- **gen_server_kwargs,
- )
- if self.return_full_text:
- gen_text = res.generated_text[len(prompt):]
- else:
- gen_text = res.generated_text
- # remove stop sequences from the end of the generated text
- for stop_seq in stop:
- if stop_seq in gen_text:
- gen_text = gen_text[:gen_text.index(stop_seq)]
- text = prompt + gen_text
- text = self.prompter.get_response(text, prompt=prompt,
- sanitize_bot_response=self.sanitize_bot_response)
- else:
- text_callback = None
- if run_manager:
- text_callback = partial(
- run_manager.on_llm_new_token, verbose=self.verbose
- )
- # parent handler of streamer expects to see prompt first else output="" and lose if prompt=None in prompter
- if text_callback:
- text_callback(prompt)
- text = ""
- # Note: Streaming ignores return_full_text=True
- for response in self.client.generate_stream(prompt, **gen_server_kwargs):
- text_chunk = response.token.text
- text += text_chunk
- text = self.prompter.get_response(prompt + text, prompt=prompt,
- sanitize_bot_response=self.sanitize_bot_response)
- # stream part
- is_stop = False
- for stop_seq in stop:
- if stop_seq in response.token.text:
- is_stop = True
- break
- if is_stop:
- break
- if not response.token.special:
- if text_callback:
- text_callback(response.token.text)
- return text
-
-
-from langchain.chat_models import ChatOpenAI
-from langchain.llms import OpenAI
-from langchain.llms.openai import _streaming_response_template, completion_with_retry, _update_response, \
- update_token_usage
-
-
-class H2OOpenAI(OpenAI):
- """
- New class to handle vLLM's use of OpenAI, no vllm_chat supported, so only need here
- Handles prompting that OpenAI doesn't need, stopping as well
- """
- stop_sequences: Any = None
- sanitize_bot_response: bool = False
- prompter: Any = None
- context: Any = ''
- iinput: Any = ''
- tokenizer: Any = None
-
- @classmethod
- def all_required_field_names(cls) -> Set:
- all_required_field_names = super(OpenAI, cls).all_required_field_names()
- all_required_field_names.update(
- {'top_p', 'frequency_penalty', 'presence_penalty', 'stop_sequences', 'sanitize_bot_response', 'prompter',
- 'tokenizer'})
- return all_required_field_names
-
- def _generate(
- self,
- prompts: List[str],
- stop: Optional[List[str]] = None,
- run_manager: Optional[CallbackManagerForLLMRun] = None,
- **kwargs: Any,
- ) -> LLMResult:
- stop = self.stop_sequences if not stop else self.stop_sequences + stop
-
- # HF inference server needs control over input tokens
- assert self.tokenizer is not None
- from h2oai_pipeline import H2OTextGenerationPipeline
- for prompti, prompt in enumerate(prompts):
- prompt, num_prompt_tokens = H2OTextGenerationPipeline.limit_prompt(prompt, self.tokenizer)
- # NOTE: OpenAI/vLLM server does not add prompting, so must do here
- data_point = dict(context=self.context, instruction=prompt, input=self.iinput)
- prompt = self.prompter.generate_prompt(data_point)
- prompts[prompti] = prompt
-
- params = self._invocation_params
- params = {**params, **kwargs}
- sub_prompts = self.get_sub_prompts(params, prompts, stop)
- choices = []
- token_usage: Dict[str, int] = {}
- # Get the token usage from the response.
- # Includes prompt, completion, and total tokens used.
- _keys = {"completion_tokens", "prompt_tokens", "total_tokens"}
- text = ''
- for _prompts in sub_prompts:
- if self.streaming:
- text_with_prompt = ""
- prompt = _prompts[0]
- if len(_prompts) > 1:
- raise ValueError("Cannot stream results with multiple prompts.")
- params["stream"] = True
- response = _streaming_response_template()
- first = True
- for stream_resp in completion_with_retry(
- self, prompt=_prompts, **params
- ):
- if first:
- stream_resp["choices"][0]["text"] = prompt + stream_resp["choices"][0]["text"]
- first = False
- text_chunk = stream_resp["choices"][0]["text"]
- text_with_prompt += text_chunk
- text = self.prompter.get_response(text_with_prompt, prompt=prompt,
- sanitize_bot_response=self.sanitize_bot_response)
- if run_manager:
- run_manager.on_llm_new_token(
- text_chunk,
- verbose=self.verbose,
- logprobs=stream_resp["choices"][0]["logprobs"],
- )
- _update_response(response, stream_resp)
- choices.extend(response["choices"])
- else:
- response = completion_with_retry(self, prompt=_prompts, **params)
- choices.extend(response["choices"])
- if not self.streaming:
- # Can't update token usage if streaming
- update_token_usage(_keys, response, token_usage)
- choices[0]['text'] = text
- return self.create_llm_result(choices, prompts, token_usage)
-
-
-class H2OChatOpenAI(ChatOpenAI):
- @classmethod
- def all_required_field_names(cls) -> Set:
- all_required_field_names = super(ChatOpenAI, cls).all_required_field_names()
- all_required_field_names.update({'top_p', 'frequency_penalty', 'presence_penalty'})
- return all_required_field_names
-
-
-def get_llm(use_openai_model=False,
- model_name=None,
- model=None,
- tokenizer=None,
- inference_server=None,
- stream_output=False,
- do_sample=False,
- temperature=0.1,
- top_k=40,
- top_p=0.7,
- num_beams=1,
- max_new_tokens=256,
- min_new_tokens=1,
- early_stopping=False,
- max_time=180,
- repetition_penalty=1.0,
- num_return_sequences=1,
- prompt_type=None,
- prompt_dict=None,
- prompter=None,
- context=None,
- iinput=None,
- sanitize_bot_response=False,
- verbose=False,
- ):
- if inference_server is None:
- inference_server = ''
- if use_openai_model or inference_server.startswith('openai') or inference_server.startswith('vllm'):
- if use_openai_model and model_name is None:
- model_name = "gpt-3.5-turbo"
- # FIXME: Will later import be ignored? I think so, so should be fine
- openai, inf_type = set_openai(inference_server)
- kwargs_extra = {}
- if inference_server == 'openai_chat' or inf_type == 'vllm_chat':
- cls = H2OChatOpenAI
- # FIXME: Support context, iinput
- else:
- cls = H2OOpenAI
- if inf_type == 'vllm':
- terminate_response = prompter.terminate_response or []
- stop_sequences = list(set(terminate_response + [prompter.PreResponse]))
- stop_sequences = [x for x in stop_sequences if x]
- kwargs_extra = dict(stop_sequences=stop_sequences,
- sanitize_bot_response=sanitize_bot_response,
- prompter=prompter,
- context=context,
- iinput=iinput,
- tokenizer=tokenizer,
- client=None)
-
- callbacks = [StreamingGradioCallbackHandler()]
- llm = cls(model_name=model_name,
- temperature=temperature if do_sample else 0,
- # FIXME: Need to count tokens and reduce max_new_tokens to fit like in generate.py
- max_tokens=max_new_tokens,
- top_p=top_p if do_sample else 1,
- frequency_penalty=0,
- presence_penalty=1.07 - repetition_penalty + 0.6, # so good default
- callbacks=callbacks if stream_output else None,
- openai_api_key=openai.api_key,
- openai_api_base=openai.api_base,
- logit_bias=None if inf_type == 'vllm' else {},
- max_retries=2,
- streaming=stream_output,
- **kwargs_extra
- )
- streamer = callbacks[0] if stream_output else None
- if inference_server in ['openai', 'openai_chat']:
- prompt_type = inference_server
- else:
- # vllm goes here
- prompt_type = prompt_type or 'plain'
- elif inference_server:
- assert inference_server.startswith(
- 'http'), "Malformed inference_server=%s. Did you add http:// in front?" % inference_server
-
- from gradio_utils.grclient import GradioClient
- from text_generation import Client as HFClient
- if isinstance(model, GradioClient):
- gr_client = model
- hf_client = None
- else:
- gr_client = None
- hf_client = model
- assert isinstance(hf_client, HFClient)
-
- inference_server, headers = get_hf_server(inference_server)
-
- # quick sanity check to avoid long timeouts, just see if can reach server
- requests.get(inference_server, timeout=int(os.getenv('REQUEST_TIMEOUT_FAST', '10')))
-
- callbacks = [StreamingGradioCallbackHandler()]
- assert prompter is not None
- terminate_response = prompter.terminate_response or []
- stop_sequences = list(set(terminate_response + [prompter.PreResponse]))
- stop_sequences = [x for x in stop_sequences if x]
-
- if gr_client:
- chat_client = False
- llm = GradioInference(
- inference_server_url=inference_server,
- return_full_text=True,
-
- temperature=temperature,
- top_p=top_p,
- top_k=top_k,
- num_beams=num_beams,
- max_new_tokens=max_new_tokens,
- min_new_tokens=min_new_tokens,
- early_stopping=early_stopping,
- max_time=max_time,
- repetition_penalty=repetition_penalty,
- num_return_sequences=num_return_sequences,
- do_sample=do_sample,
- chat_client=chat_client,
-
- callbacks=callbacks if stream_output else None,
- stream=stream_output,
- prompter=prompter,
- context=context,
- iinput=iinput,
- client=gr_client,
- sanitize_bot_response=sanitize_bot_response,
- )
- elif hf_client:
- llm = H2OHuggingFaceTextGenInference(
- inference_server_url=inference_server,
- do_sample=do_sample,
- max_new_tokens=max_new_tokens,
- repetition_penalty=repetition_penalty,
- return_full_text=True,
- seed=SEED,
-
- stop_sequences=stop_sequences,
- temperature=temperature,
- top_k=top_k,
- top_p=top_p,
- # typical_p=top_p,
- callbacks=callbacks if stream_output else None,
- stream=stream_output,
- prompter=prompter,
- context=context,
- iinput=iinput,
- tokenizer=tokenizer,
- client=hf_client,
- timeout=max_time,
- sanitize_bot_response=sanitize_bot_response,
- )
- else:
- raise RuntimeError("No defined client")
- streamer = callbacks[0] if stream_output else None
- elif model_name in non_hf_types:
- if model_name == 'llama':
- callbacks = [StreamingGradioCallbackHandler()]
- streamer = callbacks[0] if stream_output else None
- else:
- # stream_output = False
- # doesn't stream properly as generator, but at least
- callbacks = [streaming_stdout.StreamingStdOutCallbackHandler()]
- streamer = None
- if prompter:
- prompt_type = prompter.prompt_type
- else:
- prompter = Prompter(prompt_type, prompt_dict, debug=False, chat=False, stream_output=stream_output)
- pass # assume inputted prompt_type is correct
- from gpt4all_llm import get_llm_gpt4all
- llm = get_llm_gpt4all(model_name, model=model, max_new_tokens=max_new_tokens,
- temperature=temperature,
- repetition_penalty=repetition_penalty,
- top_k=top_k,
- top_p=top_p,
- callbacks=callbacks,
- verbose=verbose,
- streaming=stream_output,
- prompter=prompter,
- context=context,
- iinput=iinput,
- )
- else:
- if model is None:
- # only used if didn't pass model in
- assert tokenizer is None
- prompt_type = 'human_bot'
- if model_name is None:
- model_name = 'h2oai/h2ogpt-oasst1-512-12b'
- # model_name = 'h2oai/h2ogpt-oig-oasst1-512-6_9b'
- # model_name = 'h2oai/h2ogpt-oasst1-512-20b'
- inference_server = ''
- model, tokenizer, device = get_model(load_8bit=True, base_model=model_name,
- inference_server=inference_server, gpu_id=0)
-
- max_max_tokens = tokenizer.model_max_length
- gen_kwargs = dict(do_sample=do_sample,
- temperature=temperature,
- top_k=top_k,
- top_p=top_p,
- num_beams=num_beams,
- max_new_tokens=max_new_tokens,
- min_new_tokens=min_new_tokens,
- early_stopping=early_stopping,
- max_time=max_time,
- repetition_penalty=repetition_penalty,
- num_return_sequences=num_return_sequences,
- return_full_text=True,
- handle_long_generation=None)
- assert len(set(gen_hyper).difference(gen_kwargs.keys())) == 0
-
- if stream_output:
- skip_prompt = False
- from gen import H2OTextIteratorStreamer
- decoder_kwargs = {}
- streamer = H2OTextIteratorStreamer(tokenizer, skip_prompt=skip_prompt, block=False, **decoder_kwargs)
- gen_kwargs.update(dict(streamer=streamer))
- else:
- streamer = None
-
- from h2oai_pipeline import H2OTextGenerationPipeline
- pipe = H2OTextGenerationPipeline(model=model, use_prompter=True,
- prompter=prompter,
- context=context,
- iinput=iinput,
- prompt_type=prompt_type,
- prompt_dict=prompt_dict,
- sanitize_bot_response=sanitize_bot_response,
- chat=False, stream_output=stream_output,
- tokenizer=tokenizer,
- # leave some room for 1 paragraph, even if min_new_tokens=0
- max_input_tokens=max_max_tokens - max(min_new_tokens, 256),
- **gen_kwargs)
- # pipe.task = "text-generation"
- # below makes it listen only to our prompt removal,
- # not built in prompt removal that is less general and not specific for our model
- pipe.task = "text2text-generation"
-
- from langchain.llms import HuggingFacePipeline
- llm = HuggingFacePipeline(pipeline=pipe)
- return llm, model_name, streamer, prompt_type
-
-
-def get_device_dtype():
- # torch.device("cuda") leads to cuda:x cuda:y mismatches for multi-GPU consistently
- import torch
- n_gpus = torch.cuda.device_count() if torch.cuda.is_available else 0
- device = 'cpu' if n_gpus == 0 else 'cuda'
- # from utils import NullContext
- # context_class = NullContext if n_gpus > 1 or n_gpus == 0 else context_class
- context_class = torch.device
- torch_dtype = torch.float16 if device == 'cuda' else torch.float32
- return device, torch_dtype, context_class
-
-
-def get_wiki_data(title, first_paragraph_only, text_limit=None, take_head=True):
- """
- Get wikipedia data from online
- :param title:
- :param first_paragraph_only:
- :param text_limit:
- :param take_head:
- :return:
- """
- filename = 'wiki_%s_%s_%s_%s.data' % (first_paragraph_only, title, text_limit, take_head)
- url = f"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&titles={title}"
- if first_paragraph_only:
- url += "&exintro=1"
- import json
- if not os.path.isfile(filename):
- data = requests.get(url).json()
- json.dump(data, open(filename, 'wt'))
- else:
- data = json.load(open(filename, "rt"))
- page_content = list(data["query"]["pages"].values())[0]["extract"]
- if take_head is not None and text_limit is not None:
- page_content = page_content[:text_limit] if take_head else page_content[-text_limit:]
- title_url = str(title).replace(' ', '_')
- return Document(
- page_content=page_content,
- metadata={"source": f"https://en.wikipedia.org/wiki/{title_url}"},
- )
-
-
-def get_wiki_sources(first_para=True, text_limit=None):
- """
- Get specific named sources from wikipedia
- :param first_para:
- :param text_limit:
- :return:
- """
- default_wiki_sources = ['Unix', 'Microsoft_Windows', 'Linux']
- wiki_sources = list(os.getenv('WIKI_SOURCES', default_wiki_sources))
- return [get_wiki_data(x, first_para, text_limit=text_limit) for x in wiki_sources]
-
-
-def get_github_docs(repo_owner, repo_name):
- """
- Access github from specific repo
- :param repo_owner:
- :param repo_name:
- :return:
- """
- with tempfile.TemporaryDirectory() as d:
- subprocess.check_call(
- f"git clone --depth 1 https://github.com/{repo_owner}/{repo_name}.git .",
- cwd=d,
- shell=True,
- )
- git_sha = (
- subprocess.check_output("git rev-parse HEAD", shell=True, cwd=d)
- .decode("utf-8")
- .strip()
- )
- repo_path = pathlib.Path(d)
- markdown_files = list(repo_path.glob("*/*.md")) + list(
- repo_path.glob("*/*.mdx")
- )
- for markdown_file in markdown_files:
- with open(markdown_file, "r") as f:
- relative_path = markdown_file.relative_to(repo_path)
- github_url = f"https://github.com/{repo_owner}/{repo_name}/blob/{git_sha}/{relative_path}"
- yield Document(page_content=f.read(), metadata={"source": github_url})
-
-
-def get_dai_pickle(dest="."):
- from huggingface_hub import hf_hub_download
- # True for case when locally already logged in with correct token, so don't have to set key
- token = os.getenv('HUGGINGFACE_API_TOKEN', True)
- path_to_zip_file = hf_hub_download('h2oai/dai_docs', 'dai_docs.pickle', token=token, repo_type='dataset')
- shutil.copy(path_to_zip_file, dest)
-
-
-def get_dai_docs(from_hf=False, get_pickle=True):
- """
- Consume DAI documentation, or consume from public pickle
- :param from_hf: get DAI docs from HF, then generate pickle for later use by LangChain
- :param get_pickle: Avoid raw DAI docs, just get pickle directly from HF
- :return:
- """
- import pickle
-
- if get_pickle:
- get_dai_pickle()
-
- dai_store = 'dai_docs.pickle'
- dst = "working_dir_docs"
- if not os.path.isfile(dai_store):
- from create_data import setup_dai_docs
- dst = setup_dai_docs(dst=dst, from_hf=from_hf)
-
- import glob
- files = list(glob.glob(os.path.join(dst, '*rst'), recursive=True))
-
- basedir = os.path.abspath(os.getcwd())
- from create_data import rst_to_outputs
- new_outputs = rst_to_outputs(files)
- os.chdir(basedir)
-
- pickle.dump(new_outputs, open(dai_store, 'wb'))
- else:
- new_outputs = pickle.load(open(dai_store, 'rb'))
-
- sources = []
- for line, file in new_outputs:
- # gradio requires any linked file to be with app.py
- sym_src = os.path.abspath(os.path.join(dst, file))
- sym_dst = os.path.abspath(os.path.join(os.getcwd(), file))
- if os.path.lexists(sym_dst):
- os.remove(sym_dst)
- os.symlink(sym_src, sym_dst)
- itm = Document(page_content=line, metadata={"source": file})
- # NOTE: yield has issues when going into db, loses metadata
- # yield itm
- sources.append(itm)
- return sources
-
-
-image_types = ["png", "jpg", "jpeg"]
-non_image_types = ["pdf", "txt", "csv", "toml", "py", "rst", "rtf",
- "md",
- "html", "mhtml",
- "enex", "eml", "epub", "odt", "pptx", "ppt",
- "zip", "urls",
-
- ]
-# "msg", GPL3
-
-if have_libreoffice or True:
- # or True so it tries to load, e.g. on MAC/Windows, even if don't have libreoffice since works without that
- non_image_types.extend(["docx", "doc", "xls", "xlsx"])
-
-file_types = non_image_types + image_types
-
-
-def add_meta(docs1, file):
- file_extension = pathlib.Path(file).suffix
- hashid = hash_file(file)
- doc_hash = str(uuid.uuid4())[:10]
- if not isinstance(docs1, (list, tuple, types.GeneratorType)):
- docs1 = [docs1]
- [x.metadata.update(dict(input_type=file_extension, date=str(datetime.now()), hashid=hashid, doc_hash=doc_hash)) for
- x in docs1]
-
-
-def file_to_doc(file, base_path=None, verbose=False, fail_any_exception=False,
- chunk=True, chunk_size=512, n_jobs=-1,
- is_url=False, is_txt=False,
- enable_captions=True,
- captions_model=None,
- enable_ocr=False, enable_pdf_ocr='auto', caption_loader=None,
- headsize=50):
- if file is None:
- if fail_any_exception:
- raise RuntimeError("Unexpected None file")
- else:
- return []
- doc1 = [] # in case no support, or disabled support
- if base_path is None and not is_txt and not is_url:
- # then assume want to persist but don't care which path used
- # can't be in base_path
- dir_name = os.path.dirname(file)
- base_name = os.path.basename(file)
- # if from gradio, will have its own temp uuid too, but that's ok
- base_name = sanitize_filename(base_name) + "_" + str(uuid.uuid4())[:10]
- base_path = os.path.join(dir_name, base_name)
- if is_url:
- file = file.strip() # in case accidental spaces in front or at end
- if file.lower().startswith('arxiv:'):
- query = file.lower().split('arxiv:')
- if len(query) == 2 and have_arxiv:
- query = query[1]
- docs1 = ArxivLoader(query=query, load_max_docs=20, load_all_available_meta=True).load()
- # ensure string, sometimes None
- [[x.metadata.update({k: str(v)}) for k, v in x.metadata.items()] for x in docs1]
- query_url = f"https://arxiv.org/abs/{query}"
- [x.metadata.update(
- dict(source=x.metadata.get('entry_id', query_url), query=query_url,
- input_type='arxiv', head=x.metadata.get('Title', ''), date=str(datetime.now))) for x in
- docs1]
- else:
- docs1 = []
- else:
- if not (file.startswith("http://") or file.startswith("file://") or file.startswith("https://")):
- file = 'http://' + file
- docs1 = UnstructuredURLLoader(urls=[file]).load()
- if len(docs1) == 0 and have_playwright:
- # then something went wrong, try another loader:
- from langchain.document_loaders import PlaywrightURLLoader
- docs1 = PlaywrightURLLoader(urls=[file]).load()
- if len(docs1) == 0 and have_selenium:
- # then something went wrong, try another loader:
- # but requires Chrome binary, else get: selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary
- from langchain.document_loaders import SeleniumURLLoader
- from selenium.common.exceptions import WebDriverException
- try:
- docs1 = SeleniumURLLoader(urls=[file]).load()
- except WebDriverException as e:
- print("No web driver: %s" % str(e), flush=True)
- [x.metadata.update(dict(input_type='url', date=str(datetime.now))) for x in docs1]
- docs1 = clean_doc(docs1)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif is_txt:
- base_path = "user_paste"
- source_file = os.path.join(base_path, "_%s" % str(uuid.uuid4())[:10])
- makedirs(os.path.dirname(source_file), exist_ok=True)
- with open(source_file, "wt") as f:
- f.write(file)
- metadata = dict(source=source_file, date=str(datetime.now()), input_type='pasted txt')
- doc1 = Document(page_content=file, metadata=metadata)
- doc1 = clean_doc(doc1)
- elif file.lower().endswith('.html') or file.lower().endswith('.mhtml'):
- docs1 = UnstructuredHTMLLoader(file_path=file).load()
- add_meta(docs1, file)
- docs1 = clean_doc(docs1)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size, language=Language.HTML)
- elif (file.lower().endswith('.docx') or file.lower().endswith('.doc')) and (have_libreoffice or True):
- docs1 = UnstructuredWordDocumentLoader(file_path=file).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif (file.lower().endswith('.xlsx') or file.lower().endswith('.xls')) and (have_libreoffice or True):
- docs1 = UnstructuredExcelLoader(file_path=file).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.odt'):
- docs1 = UnstructuredODTLoader(file_path=file).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('pptx') or file.lower().endswith('ppt'):
- docs1 = UnstructuredPowerPointLoader(file_path=file).load()
- add_meta(docs1, file)
- docs1 = clean_doc(docs1)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.txt'):
- # use UnstructuredFileLoader ?
- docs1 = TextLoader(file, encoding="utf8", autodetect_encoding=True).load()
- # makes just one, but big one
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- doc1 = clean_doc(doc1)
- add_meta(doc1, file)
- elif file.lower().endswith('.rtf'):
- docs1 = UnstructuredRTFLoader(file).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.md'):
- docs1 = UnstructuredMarkdownLoader(file).load()
- add_meta(docs1, file)
- docs1 = clean_doc(docs1)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size, language=Language.MARKDOWN)
- elif file.lower().endswith('.enex'):
- docs1 = EverNoteLoader(file).load()
- add_meta(doc1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.epub'):
- docs1 = UnstructuredEPubLoader(file).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.jpeg') or file.lower().endswith('.jpg') or file.lower().endswith('.png'):
- docs1 = []
- if have_tesseract and enable_ocr:
- # OCR, somewhat works, but not great
- docs1.extend(UnstructuredImageLoader(file).load())
- add_meta(docs1, file)
- if enable_captions:
- # BLIP
- if caption_loader is not None and not isinstance(caption_loader, (str, bool)):
- # assumes didn't fork into this process with joblib, else can deadlock
- caption_loader.set_image_paths([file])
- docs1c = caption_loader.load()
- add_meta(docs1c, file)
- [x.metadata.update(dict(head=x.page_content[:headsize].strip())) for x in docs1c]
- docs1.extend(docs1c)
- else:
- from image_captions import H2OImageCaptionLoader
- caption_loader = H2OImageCaptionLoader(caption_gpu=caption_loader == 'gpu',
- blip_model=captions_model,
- blip_processor=captions_model)
- caption_loader.set_image_paths([file])
- docs1c = caption_loader.load()
- add_meta(docs1c, file)
- [x.metadata.update(dict(head=x.page_content[:headsize].strip())) for x in docs1c]
- docs1.extend(docs1c)
- for doci in docs1:
- doci.metadata['source'] = doci.metadata['image_path']
- doci.metadata['hash'] = hash_file(doci.metadata['source'])
- if docs1:
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.msg'):
- raise RuntimeError("Not supported, GPL3 license")
- # docs1 = OutlookMessageLoader(file).load()
- # docs1[0].metadata['source'] = file
- elif file.lower().endswith('.eml'):
- try:
- docs1 = UnstructuredEmailLoader(file).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- except ValueError as e:
- if 'text/html content not found in email' in str(e):
- # e.g. plain/text dict key exists, but not
- # doc1 = TextLoader(file, encoding="utf8").load()
- docs1 = UnstructuredEmailLoader(file, content_source="text/plain").load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- else:
- raise
- # elif file.lower().endswith('.gcsdir'):
- # doc1 = GCSDirectoryLoader(project_name, bucket, prefix).load()
- # elif file.lower().endswith('.gcsfile'):
- # doc1 = GCSFileLoader(project_name, bucket, blob).load()
- elif file.lower().endswith('.rst'):
- with open(file, "r") as f:
- doc1 = Document(page_content=f.read(), metadata={"source": file})
- add_meta(doc1, file)
- doc1 = chunk_sources(doc1, chunk=chunk, chunk_size=chunk_size, language=Language.RST)
- elif file.lower().endswith('.pdf'):
- env_gpt4all_file = ".env_gpt4all"
- from dotenv import dotenv_values
- env_kwargs = dotenv_values(env_gpt4all_file)
- pdf_class_name = env_kwargs.get('PDF_CLASS_NAME', 'PyMuPDFParser')
- doc1 = []
- handled = False
- if have_pymupdf and pdf_class_name == 'PyMuPDFParser':
- # GPL, only use if installed
- from langchain.document_loaders import PyMuPDFLoader
- # load() still chunks by pages, but every page has title at start to help
- doc1 = PyMuPDFLoader(file).load()
- # remove empty documents
- handled |= len(doc1) > 0
- doc1 = [x for x in doc1 if x.page_content]
- doc1 = clean_doc(doc1)
- if len(doc1) == 0:
- doc1 = UnstructuredPDFLoader(file).load()
- handled |= len(doc1) > 0
- # remove empty documents
- doc1 = [x for x in doc1 if x.page_content]
- # seems to not need cleaning in most cases
- if len(doc1) == 0:
- # open-source fallback
- # load() still chunks by pages, but every page has title at start to help
- doc1 = PyPDFLoader(file).load()
- handled |= len(doc1) > 0
- # remove empty documents
- doc1 = [x for x in doc1 if x.page_content]
- doc1 = clean_doc(doc1)
- if have_pymupdf and len(doc1) == 0:
- # GPL, only use if installed
- from langchain.document_loaders import PyMuPDFLoader
- # load() still chunks by pages, but every page has title at start to help
- doc1 = PyMuPDFLoader(file).load()
- handled |= len(doc1) > 0
- # remove empty documents
- doc1 = [x for x in doc1 if x.page_content]
- doc1 = clean_doc(doc1)
- if len(doc1) == 0 and enable_pdf_ocr == 'auto' or enable_pdf_ocr == 'on':
- # try OCR in end since slowest, but works on pure image pages well
- doc1 = UnstructuredPDFLoader(file, strategy='ocr_only').load()
- handled |= len(doc1) > 0
- # remove empty documents
- doc1 = [x for x in doc1 if x.page_content]
- # seems to not need cleaning in most cases
- # Some PDFs return nothing or junk from PDFMinerLoader
- if len(doc1) == 0:
- # if literally nothing, show failed to parse so user knows, since unlikely nothing in PDF at all.
- if handled:
- raise ValueError("%s had no valid text, but meta data was parsed" % file)
- else:
- raise ValueError("%s had no valid text and no meta data was parsed" % file)
- doc1 = chunk_sources(doc1, chunk=chunk, chunk_size=chunk_size)
- add_meta(doc1, file)
- elif file.lower().endswith('.csv'):
- doc1 = CSVLoader(file).load()
- add_meta(doc1, file)
- elif file.lower().endswith('.py'):
- doc1 = PythonLoader(file).load()
- add_meta(doc1, file)
- doc1 = chunk_sources(doc1, chunk=chunk, chunk_size=chunk_size, language=Language.PYTHON)
- elif file.lower().endswith('.toml'):
- doc1 = TomlLoader(file).load()
- add_meta(doc1, file)
- elif file.lower().endswith('.urls'):
- with open(file, "r") as f:
- docs1 = UnstructuredURLLoader(urls=f.readlines()).load()
- add_meta(docs1, file)
- doc1 = chunk_sources(docs1, chunk=chunk, chunk_size=chunk_size)
- elif file.lower().endswith('.zip'):
- with zipfile.ZipFile(file, 'r') as zip_ref:
- # don't put into temporary path, since want to keep references to docs inside zip
- # so just extract in path where
- zip_ref.extractall(base_path)
- # recurse
- doc1 = path_to_docs(base_path, verbose=verbose, fail_any_exception=fail_any_exception, n_jobs=n_jobs)
- else:
- raise RuntimeError("No file handler for %s" % os.path.basename(file))
-
- # allow doc1 to be list or not. If not list, did not chunk yet, so chunk now
- # if list of length one, don't trust and chunk it
- if not isinstance(doc1, list):
- if chunk:
- docs = chunk_sources([doc1], chunk=chunk, chunk_size=chunk_size)
- else:
- docs = [doc1]
- elif isinstance(doc1, list) and len(doc1) == 1:
- if chunk:
- docs = chunk_sources(doc1, chunk=chunk, chunk_size=chunk_size)
- else:
- docs = doc1
- else:
- docs = doc1
-
- assert isinstance(docs, list)
- return docs
-
-
-def path_to_doc1(file, verbose=False, fail_any_exception=False, return_file=True,
- chunk=True, chunk_size=512,
- n_jobs=-1,
- is_url=False, is_txt=False,
- enable_captions=True,
- captions_model=None,
- enable_ocr=False, enable_pdf_ocr='auto', caption_loader=None):
- if verbose:
- if is_url:
- print("Ingesting URL: %s" % file, flush=True)
- elif is_txt:
- print("Ingesting Text: %s" % file, flush=True)
- else:
- print("Ingesting file: %s" % file, flush=True)
- res = None
- try:
- # don't pass base_path=path, would infinitely recurse
- res = file_to_doc(file, base_path=None, verbose=verbose, fail_any_exception=fail_any_exception,
- chunk=chunk, chunk_size=chunk_size,
- n_jobs=n_jobs,
- is_url=is_url, is_txt=is_txt,
- enable_captions=enable_captions,
- captions_model=captions_model,
- enable_ocr=enable_ocr,
- enable_pdf_ocr=enable_pdf_ocr,
- caption_loader=caption_loader)
- except BaseException as e:
- print("Failed to ingest %s due to %s" % (file, traceback.format_exc()))
- if fail_any_exception:
- raise
- else:
- exception_doc = Document(
- page_content='',
- metadata={"source": file, "exception": '%s Exception: %s' % (file, str(e)),
- "traceback": traceback.format_exc()})
- res = [exception_doc]
- if return_file:
- base_tmp = "temp_path_to_doc1"
- if not os.path.isdir(base_tmp):
- os.makedirs(base_tmp, exist_ok=True)
- filename = os.path.join(base_tmp, str(uuid.uuid4()) + ".tmp.pickle")
- with open(filename, 'wb') as f:
- pickle.dump(res, f)
- return filename
- return res
-
-
-def path_to_docs(path_or_paths, verbose=False, fail_any_exception=False, n_jobs=-1,
- chunk=True, chunk_size=512,
- url=None, text=None,
- enable_captions=True,
- captions_model=None,
- caption_loader=None,
- enable_ocr=False,
- enable_pdf_ocr='auto',
- existing_files=[],
- existing_hash_ids={},
- ):
- # path_or_paths could be str, list, tuple, generator
- globs_image_types = []
- globs_non_image_types = []
- if not path_or_paths and not url and not text:
- return []
- elif url:
- globs_non_image_types = url if isinstance(url, (list, tuple, types.GeneratorType)) else [url]
- elif text:
- globs_non_image_types = text if isinstance(text, (list, tuple, types.GeneratorType)) else [text]
- elif isinstance(path_or_paths, str) and os.path.isdir(path_or_paths):
- # single path, only consume allowed files
- path = path_or_paths
- # Below globs should match patterns in file_to_doc()
- [globs_image_types.extend(glob.glob(os.path.join(path, "./**/*.%s" % ftype), recursive=True))
- for ftype in image_types]
- [globs_non_image_types.extend(glob.glob(os.path.join(path, "./**/*.%s" % ftype), recursive=True))
- for ftype in non_image_types]
- else:
- if isinstance(path_or_paths, str):
- if os.path.isfile(path_or_paths) or os.path.isdir(path_or_paths):
- path_or_paths = [path_or_paths]
- else:
- # path was deleted etc.
- return []
- # list/tuple of files (consume what can, and exception those that selected but cannot consume so user knows)
- assert isinstance(path_or_paths, (list, tuple, types.GeneratorType)), \
- "Wrong type for path_or_paths: %s %s" % (path_or_paths, type(path_or_paths))
- # reform out of allowed types
- globs_image_types.extend(flatten_list([[x for x in path_or_paths if x.endswith(y)] for y in image_types]))
- # could do below:
- # globs_non_image_types = flatten_list([[x for x in path_or_paths if x.endswith(y)] for y in non_image_types])
- # But instead, allow fail so can collect unsupported too
- set_globs_image_types = set(globs_image_types)
- globs_non_image_types.extend([x for x in path_or_paths if x not in set_globs_image_types])
-
- # filter out any files to skip (e.g. if already processed them)
- # this is easy, but too aggressive in case a file changed, so parent probably passed existing_files=[]
- assert not existing_files, "DEV: assume not using this approach"
- if existing_files:
- set_skip_files = set(existing_files)
- globs_image_types = [x for x in globs_image_types if x not in set_skip_files]
- globs_non_image_types = [x for x in globs_non_image_types if x not in set_skip_files]
- if existing_hash_ids:
- # assume consistent with add_meta() use of hash_file(file)
- # also assume consistent with get_existing_hash_ids for dict creation
- # assume hashable values
- existing_hash_ids_set = set(existing_hash_ids.items())
- hash_ids_all_image = set({x: hash_file(x) for x in globs_image_types}.items())
- hash_ids_all_non_image = set({x: hash_file(x) for x in globs_non_image_types}.items())
- # don't use symmetric diff. If file is gone, ignore and don't remove or something
- # just consider existing files (key) having new hash or not (value)
- new_files_image = set(dict(hash_ids_all_image - existing_hash_ids_set).keys())
- new_files_non_image = set(dict(hash_ids_all_non_image - existing_hash_ids_set).keys())
- globs_image_types = [x for x in globs_image_types if x in new_files_image]
- globs_non_image_types = [x for x in globs_non_image_types if x in new_files_non_image]
-
- # could use generator, but messes up metadata handling in recursive case
- if caption_loader and not isinstance(caption_loader, (bool, str)) and \
- caption_loader.device != 'cpu' or \
- get_device() == 'cuda':
- # to avoid deadlocks, presume was preloaded and so can't fork due to cuda context
- n_jobs_image = 1
- else:
- n_jobs_image = n_jobs
-
- return_file = True # local choice
- is_url = url is not None
- is_txt = text is not None
- kwargs = dict(verbose=verbose, fail_any_exception=fail_any_exception,
- return_file=return_file,
- chunk=chunk, chunk_size=chunk_size,
- n_jobs=n_jobs,
- is_url=is_url,
- is_txt=is_txt,
- enable_captions=enable_captions,
- captions_model=captions_model,
- caption_loader=caption_loader,
- enable_ocr=enable_ocr,
- enable_pdf_ocr=enable_pdf_ocr,
- )
-
- if n_jobs != 1 and len(globs_non_image_types) > 1:
- # avoid nesting, e.g. upload 1 zip and then inside many files
- # harder to handle if upload many zips with many files, inner parallel one will be disabled by joblib
- documents = ProgressParallel(n_jobs=n_jobs, verbose=10 if verbose else 0, backend='multiprocessing')(
- delayed(path_to_doc1)(file, **kwargs) for file in globs_non_image_types
- )
- else:
- documents = [path_to_doc1(file, **kwargs) for file in tqdm(globs_non_image_types)]
-
- # do images separately since can't fork after cuda in parent, so can't be parallel
- if n_jobs_image != 1 and len(globs_image_types) > 1:
- # avoid nesting, e.g. upload 1 zip and then inside many files
- # harder to handle if upload many zips with many files, inner parallel one will be disabled by joblib
- image_documents = ProgressParallel(n_jobs=n_jobs, verbose=10 if verbose else 0, backend='multiprocessing')(
- delayed(path_to_doc1)(file, **kwargs) for file in globs_image_types
- )
- else:
- image_documents = [path_to_doc1(file, **kwargs) for file in tqdm(globs_image_types)]
-
- # add image docs in
- documents += image_documents
-
- if return_file:
- # then documents really are files
- files = documents.copy()
- documents = []
- for fil in files:
- with open(fil, 'rb') as f:
- documents.extend(pickle.load(f))
- # remove temp pickle
- remove(fil)
- else:
- documents = reduce(concat, documents)
- return documents
-
-
-def prep_langchain(persist_directory,
- load_db_if_exists,
- db_type, use_openai_embedding, langchain_mode, langchain_mode_paths,
- hf_embedding_model, n_jobs=-1, kwargs_make_db={}):
- """
- do prep first time, involving downloads
- # FIXME: Add github caching then add here
- :return:
- """
- assert langchain_mode not in ['MyData'], "Should not prep scratch data"
-
- db_dir_exists = os.path.isdir(persist_directory)
- user_path = langchain_mode_paths.get(langchain_mode)
-
- if db_dir_exists and user_path is None:
- print("Prep: persist_directory=%s exists, using" % persist_directory, flush=True)
- db = get_existing_db(None, persist_directory, load_db_if_exists, db_type, use_openai_embedding, langchain_mode,
- hf_embedding_model)
- else:
- if db_dir_exists and user_path is not None:
- print("Prep: persist_directory=%s exists, user_path=%s passed, adding any changed or new documents" % (
- persist_directory, user_path), flush=True)
- elif not db_dir_exists:
- print("Prep: persist_directory=%s does not exist, regenerating" % persist_directory, flush=True)
- db = None
- if langchain_mode in ['All', 'DriverlessAI docs']:
- # FIXME: Could also just use dai_docs.pickle directly and upload that
- get_dai_docs(from_hf=True)
-
- if langchain_mode in ['All', 'wiki']:
- get_wiki_sources(first_para=kwargs_make_db['first_para'], text_limit=kwargs_make_db['text_limit'])
-
- langchain_kwargs = kwargs_make_db.copy()
- langchain_kwargs.update(locals())
- db, num_new_sources, new_sources_metadata = make_db(**langchain_kwargs)
-
- return db
-
-
-import posthog
-
-posthog.disabled = True
-
-
-class FakeConsumer(object):
- def __init__(self, *args, **kwargs):
- pass
-
- def run(self):
- pass
-
- def pause(self):
- pass
-
- def upload(self):
- pass
-
- def next(self):
- pass
-
- def request(self, batch):
- pass
-
-
-posthog.Consumer = FakeConsumer
-
-
-def check_update_chroma_embedding(db, use_openai_embedding, hf_embedding_model, langchain_mode):
- changed_db = False
- if load_embed(db) != (use_openai_embedding, hf_embedding_model):
- print("Detected new embedding, updating db: %s" % langchain_mode, flush=True)
- # handle embedding changes
- db_get = get_documents(db)
- sources = [Document(page_content=result[0], metadata=result[1] or {})
- for result in zip(db_get['documents'], db_get['metadatas'])]
- # delete index, has to be redone
- persist_directory = db._persist_directory
- shutil.move(persist_directory, persist_directory + "_" + str(uuid.uuid4()) + ".bak")
- db_type = 'chroma'
- load_db_if_exists = False
- db = get_db(sources, use_openai_embedding=use_openai_embedding, db_type=db_type,
- persist_directory=persist_directory, load_db_if_exists=load_db_if_exists,
- langchain_mode=langchain_mode,
- collection_name=None,
- hf_embedding_model=hf_embedding_model)
- if False:
- # below doesn't work if db already in memory, so have to switch to new db as above
- # upsert does new embedding, but if index already in memory, complains about size mismatch etc.
- client_collection = db._client.get_collection(name=db._collection.name,
- embedding_function=db._collection._embedding_function)
- client_collection.upsert(ids=db_get['ids'], metadatas=db_get['metadatas'], documents=db_get['documents'])
- changed_db = True
- print("Done updating db for new embedding: %s" % langchain_mode, flush=True)
-
- return db, changed_db
-
-
-def get_existing_db(db, persist_directory, load_db_if_exists, db_type, use_openai_embedding, langchain_mode,
- hf_embedding_model, verbose=False, check_embedding=True):
- if load_db_if_exists and db_type == 'chroma' and os.path.isdir(persist_directory) and os.path.isdir(
- os.path.join(persist_directory, 'index')):
- if db is None:
- if verbose:
- print("DO Loading db: %s" % langchain_mode, flush=True)
- embedding = get_embedding(use_openai_embedding, hf_embedding_model=hf_embedding_model)
- from chromadb.config import Settings
- client_settings = Settings(anonymized_telemetry=False,
- chroma_db_impl="duckdb+parquet",
- persist_directory=persist_directory)
- db = Chroma(persist_directory=persist_directory, embedding_function=embedding,
- collection_name=langchain_mode.replace(' ', '_'),
- client_settings=client_settings)
- if verbose:
- print("DONE Loading db: %s" % langchain_mode, flush=True)
- else:
- if verbose:
- print("USING already-loaded db: %s" % langchain_mode, flush=True)
- if check_embedding:
- db_trial, changed_db = check_update_chroma_embedding(db, use_openai_embedding, hf_embedding_model,
- langchain_mode)
- if changed_db:
- db = db_trial
- # only call persist if really changed db, else takes too long for large db
- if db is not None:
- db.persist()
- clear_embedding(db)
- save_embed(db, use_openai_embedding, hf_embedding_model)
- return db
- return None
-
-
-def clear_embedding(db):
- if db is None:
- return
- # don't keep on GPU, wastes memory, push back onto CPU and only put back on GPU once again embed
- db._embedding_function.client.cpu()
- clear_torch_cache()
-
-
-def make_db(**langchain_kwargs):
- func_names = list(inspect.signature(_make_db).parameters)
- missing_kwargs = [x for x in func_names if x not in langchain_kwargs]
- defaults_db = {k: v.default for k, v in dict(inspect.signature(run_qa_db).parameters).items()}
- for k in missing_kwargs:
- if k in defaults_db:
- langchain_kwargs[k] = defaults_db[k]
- # final check for missing
- missing_kwargs = [x for x in func_names if x not in langchain_kwargs]
- assert not missing_kwargs, "Missing kwargs for make_db: %s" % missing_kwargs
- # only keep actual used
- langchain_kwargs = {k: v for k, v in langchain_kwargs.items() if k in func_names}
- return _make_db(**langchain_kwargs)
-
-
-def save_embed(db, use_openai_embedding, hf_embedding_model):
- if db is not None:
- embed_info_file = os.path.join(db._persist_directory, 'embed_info')
- with open(embed_info_file, 'wb') as f:
- pickle.dump((use_openai_embedding, hf_embedding_model), f)
- return use_openai_embedding, hf_embedding_model
-
-
-def load_embed(db):
- embed_info_file = os.path.join(db._persist_directory, 'embed_info')
- if os.path.isfile(embed_info_file):
- with open(embed_info_file, 'rb') as f:
- use_openai_embedding, hf_embedding_model = pickle.load(f)
- else:
- # migration, assume defaults
- use_openai_embedding, hf_embedding_model = False, "sentence-transformers/all-MiniLM-L6-v2"
- return use_openai_embedding, hf_embedding_model
-
-
-def get_persist_directory(langchain_mode):
- return 'db_dir_%s' % langchain_mode # single place, no special names for each case
-
-
-def _make_db(use_openai_embedding=False,
- hf_embedding_model="sentence-transformers/all-MiniLM-L6-v2",
- first_para=False, text_limit=None,
- chunk=True, chunk_size=512,
- langchain_mode=None,
- langchain_mode_paths=None,
- db_type='faiss',
- load_db_if_exists=True,
- db=None,
- n_jobs=-1,
- verbose=False):
- persist_directory = get_persist_directory(langchain_mode)
- user_path = langchain_mode_paths.get(langchain_mode)
- # see if can get persistent chroma db
- db_trial = get_existing_db(db, persist_directory, load_db_if_exists, db_type, use_openai_embedding, langchain_mode,
- hf_embedding_model, verbose=verbose)
- if db_trial is not None:
- db = db_trial
-
- sources = []
- if not db:
- if langchain_mode in ['wiki_full']:
- from read_wiki_full import get_all_documents
- small_test = None
- print("Generating new wiki", flush=True)
- sources1 = get_all_documents(small_test=small_test, n_jobs=os.cpu_count() // 2)
- print("Got new wiki", flush=True)
- if chunk:
- sources1 = chunk_sources(sources1, chunk=chunk, chunk_size=chunk_size)
- print("Chunked new wiki", flush=True)
- sources.extend(sources1)
- elif langchain_mode in ['wiki']:
- sources1 = get_wiki_sources(first_para=first_para, text_limit=text_limit)
- if chunk:
- sources1 = chunk_sources(sources1, chunk=chunk, chunk_size=chunk_size)
- sources.extend(sources1)
- elif langchain_mode in ['github h2oGPT']:
- # sources = get_github_docs("dagster-io", "dagster")
- sources1 = get_github_docs("h2oai", "h2ogpt")
- # FIXME: always chunk for now
- sources1 = chunk_sources(sources1, chunk=chunk, chunk_size=chunk_size)
- sources.extend(sources1)
- elif langchain_mode in ['DriverlessAI docs']:
- sources1 = get_dai_docs(from_hf=True)
- if chunk and False: # FIXME: DAI docs are already chunked well, should only chunk more if over limit
- sources1 = chunk_sources(sources1, chunk=chunk, chunk_size=chunk_size)
- sources.extend(sources1)
- if user_path:
- # UserData or custom, which has to be from user's disk
- if db is not None:
- # NOTE: Ignore file names for now, only go by hash ids
- # existing_files = get_existing_files(db)
- existing_files = []
- existing_hash_ids = get_existing_hash_ids(db)
- else:
- # pretend no existing files so won't filter
- existing_files = []
- existing_hash_ids = []
- # chunk internally for speed over multiple docs
- # FIXME: If first had old Hash=None and switch embeddings,
- # then re-embed, and then hit here and reload so have hash, and then re-embed.
- sources1 = path_to_docs(user_path, n_jobs=n_jobs, chunk=chunk, chunk_size=chunk_size,
- existing_files=existing_files, existing_hash_ids=existing_hash_ids)
- new_metadata_sources = set([x.metadata['source'] for x in sources1])
- if new_metadata_sources:
- print("Loaded %s new files as sources to add to %s" % (len(new_metadata_sources), langchain_mode),
- flush=True)
- if verbose:
- print("Files added: %s" % '\n'.join(new_metadata_sources), flush=True)
- sources.extend(sources1)
- print("Loaded %s sources for potentially adding to %s" % (len(sources), langchain_mode), flush=True)
-
- # see if got sources
- if not sources:
- if verbose:
- if db is not None:
- print("langchain_mode %s has no new sources, nothing to add to db" % langchain_mode, flush=True)
- else:
- print("langchain_mode %s has no sources, not making new db" % langchain_mode, flush=True)
- return db, 0, []
- if verbose:
- if db is not None:
- print("Generating db", flush=True)
- else:
- print("Adding to db", flush=True)
- if not db:
- if sources:
- db = get_db(sources, use_openai_embedding=use_openai_embedding, db_type=db_type,
- persist_directory=persist_directory, langchain_mode=langchain_mode,
- hf_embedding_model=hf_embedding_model)
- if verbose:
- print("Generated db", flush=True)
- else:
- print("Did not generate db since no sources", flush=True)
- new_sources_metadata = [x.metadata for x in sources]
- elif user_path is not None:
- print("Existing db, potentially adding %s sources from user_path=%s" % (len(sources), user_path), flush=True)
- db, num_new_sources, new_sources_metadata = add_to_db(db, sources, db_type=db_type,
- use_openai_embedding=use_openai_embedding,
- hf_embedding_model=hf_embedding_model)
- print("Existing db, added %s new sources from user_path=%s" % (num_new_sources, user_path), flush=True)
- else:
- new_sources_metadata = [x.metadata for x in sources]
-
- return db, len(new_sources_metadata), new_sources_metadata
-
-
-def get_metadatas(db):
- from langchain.vectorstores import FAISS
- if isinstance(db, FAISS):
- metadatas = [v.metadata for k, v in db.docstore._dict.items()]
- elif isinstance(db, Chroma):
- metadatas = get_documents(db)['metadatas']
- else:
- # FIXME: Hack due to https://github.com/weaviate/weaviate/issues/1947
- # seems no way to get all metadata, so need to avoid this approach for weaviate
- metadatas = [x.metadata for x in db.similarity_search("", k=10000)]
- return metadatas
-
-
-def get_documents(db):
- if hasattr(db, '_persist_directory'):
- name_path = os.path.basename(db._persist_directory)
- base_path = 'locks'
- makedirs(base_path)
- with filelock.FileLock(os.path.join(base_path, "getdb_%s.lock" % name_path)):
- # get segfaults and other errors when multiple threads access this
- return _get_documents(db)
- else:
- return _get_documents(db)
-
-
-def _get_documents(db):
- from langchain.vectorstores import FAISS
- if isinstance(db, FAISS):
- documents = [v for k, v in db.docstore._dict.items()]
- elif isinstance(db, Chroma):
- documents = db.get()
- else:
- # FIXME: Hack due to https://github.com/weaviate/weaviate/issues/1947
- # seems no way to get all metadata, so need to avoid this approach for weaviate
- documents = [x for x in db.similarity_search("", k=10000)]
- return documents
-
-
-def get_docs_and_meta(db, top_k_docs, filter_kwargs={}):
- if hasattr(db, '_persist_directory'):
- name_path = os.path.basename(db._persist_directory)
- base_path = 'locks'
- makedirs(base_path)
- with filelock.FileLock(os.path.join(base_path, "getdb_%s.lock" % name_path)):
- return _get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs)
- else:
- return _get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs)
-
-
-def _get_docs_and_meta(db, top_k_docs, filter_kwargs={}):
- from langchain.vectorstores import FAISS
- if isinstance(db, Chroma):
- db_get = db._collection.get(where=filter_kwargs.get('filter'))
- db_metadatas = db_get['metadatas']
- db_documents = db_get['documents']
- elif isinstance(db, FAISS):
- import itertools
- db_metadatas = get_metadatas(db)
- # FIXME: FAISS has no filter
- # slice dict first
- db_documents = list(dict(itertools.islice(db.docstore._dict.items(), top_k_docs)).values())
- else:
- db_metadatas = get_metadatas(db)
- db_documents = get_documents(db)
- return db_documents, db_metadatas
-
-
-def get_existing_files(db):
- metadatas = get_metadatas(db)
- metadata_sources = set([x['source'] for x in metadatas])
- return metadata_sources
-
-
-def get_existing_hash_ids(db):
- metadatas = get_metadatas(db)
- # assume consistency, that any prior hashed source was single hashed file at the time among all source chunks
- metadata_hash_ids = {x['source']: x.get('hashid') for x in metadatas}
- return metadata_hash_ids
-
-
-def run_qa_db(**kwargs):
- func_names = list(inspect.signature(_run_qa_db).parameters)
- # hard-coded defaults
- kwargs['answer_with_sources'] = True
- kwargs['show_rank'] = False
- missing_kwargs = [x for x in func_names if x not in kwargs]
- assert not missing_kwargs, "Missing kwargs for run_qa_db: %s" % missing_kwargs
- # only keep actual used
- kwargs = {k: v for k, v in kwargs.items() if k in func_names}
- try:
- return _run_qa_db(**kwargs)
- finally:
- clear_torch_cache()
-
-
-def _run_qa_db(query=None,
- iinput=None,
- context=None,
- use_openai_model=False, use_openai_embedding=False,
- first_para=False, text_limit=None, top_k_docs=4, chunk=True, chunk_size=512,
- langchain_mode_paths={},
- detect_user_path_changes_every_query=False,
- db_type='faiss',
- model_name=None, model=None, tokenizer=None, inference_server=None,
- hf_embedding_model="sentence-transformers/all-MiniLM-L6-v2",
- stream_output=False,
- prompter=None,
- prompt_type=None,
- prompt_dict=None,
- answer_with_sources=True,
- cut_distance=1.64,
- add_chat_history_to_context=True,
- sanitize_bot_response=False,
- show_rank=False,
- use_llm_if_no_docs=False,
- load_db_if_exists=False,
- db=None,
- do_sample=False,
- temperature=0.1,
- top_k=40,
- top_p=0.7,
- num_beams=1,
- max_new_tokens=256,
- min_new_tokens=1,
- early_stopping=False,
- max_time=180,
- repetition_penalty=1.0,
- num_return_sequences=1,
- langchain_mode=None,
- langchain_action=None,
- langchain_agents=None,
- document_subset=DocumentSubset.Relevant.name,
- document_choice=[DocumentChoice.ALL.value],
- n_jobs=-1,
- verbose=False,
- cli=False,
- reverse_docs=True,
- lora_weights='',
- auto_reduce_chunks=True,
- max_chunks=100,
- ):
- """
-
- :param query:
- :param use_openai_model:
- :param use_openai_embedding:
- :param first_para:
- :param text_limit:
- :param top_k_docs:
- :param chunk:
- :param chunk_size:
- :param langchain_mode_paths: dict of langchain_mode -> user path to glob recursively from
- :param db_type: 'faiss' for in-memory db or 'chroma' or 'weaviate' for persistent db
- :param model_name: model name, used to switch behaviors
- :param model: pre-initialized model, else will make new one
- :param tokenizer: pre-initialized tokenizer, else will make new one. Required not None if model is not None
- :param answer_with_sources
- :return:
- """
- assert langchain_mode_paths is not None
- if model is not None:
- assert model_name is not None # require so can make decisions
- assert query is not None
- assert prompter is not None or prompt_type is not None or model is None # if model is None, then will generate
- if prompter is not None:
- prompt_type = prompter.prompt_type
- prompt_dict = prompter.prompt_dict
- if model is not None:
- assert prompt_type is not None
- if prompt_type == PromptType.custom.name:
- assert prompt_dict is not None # should at least be {} or ''
- else:
- prompt_dict = ''
- assert len(set(gen_hyper).difference(inspect.signature(get_llm).parameters)) == 0
- # pass in context to LLM directly, since already has prompt_type structure
- # can't pass through langchain in get_chain() to LLM: https://github.com/hwchase17/langchain/issues/6638
- llm, model_name, streamer, prompt_type_out = get_llm(use_openai_model=use_openai_model, model_name=model_name,
- model=model,
- tokenizer=tokenizer,
- inference_server=inference_server,
- stream_output=stream_output,
- do_sample=do_sample,
- temperature=temperature,
- top_k=top_k,
- top_p=top_p,
- num_beams=num_beams,
- max_new_tokens=max_new_tokens,
- min_new_tokens=min_new_tokens,
- early_stopping=early_stopping,
- max_time=max_time,
- repetition_penalty=repetition_penalty,
- num_return_sequences=num_return_sequences,
- prompt_type=prompt_type,
- prompt_dict=prompt_dict,
- prompter=prompter,
- context=context if add_chat_history_to_context else '',
- iinput=iinput if add_chat_history_to_context else '',
- sanitize_bot_response=sanitize_bot_response,
- verbose=verbose,
- )
-
- use_docs_planned = False
- scores = []
- chain = None
-
- if isinstance(document_choice, str):
- # support string as well
- document_choice = [document_choice]
-
- func_names = list(inspect.signature(get_chain).parameters)
- sim_kwargs = {k: v for k, v in locals().items() if k in func_names}
- missing_kwargs = [x for x in func_names if x not in sim_kwargs]
- assert not missing_kwargs, "Missing: %s" % missing_kwargs
- docs, chain, scores, use_docs_planned, have_any_docs = get_chain(**sim_kwargs)
- if document_subset in non_query_commands:
- formatted_doc_chunks = '\n\n'.join([get_url(x) + '\n\n' + x.page_content for x in docs])
- if not formatted_doc_chunks and not use_llm_if_no_docs:
- yield "No sources", ''
- return
- # if no souces, outside gpt_langchain, LLM will be used with '' input
- yield formatted_doc_chunks, ''
- return
- if not use_llm_if_no_docs:
- if not docs and langchain_action in [LangChainAction.SUMMARIZE_MAP.value,
- LangChainAction.SUMMARIZE_ALL.value,
- LangChainAction.SUMMARIZE_REFINE.value]:
- ret = 'No relevant documents to summarize.' if have_any_docs else 'No documents to summarize.'
- extra = ''
- yield ret, extra
- return
- if not docs and langchain_mode not in [LangChainMode.DISABLED.value,
- LangChainMode.LLM.value]:
- ret = 'No relevant documents to query.' if have_any_docs else 'No documents to query.'
- extra = ''
- yield ret, extra
- return
-
- if chain is None and model_name not in non_hf_types:
- # here if no docs at all and not HF type
- # can only return if HF type
- return
-
- # context stuff similar to used in evaluate()
- import torch
- device, torch_dtype, context_class = get_device_dtype()
- with torch.no_grad():
- have_lora_weights = lora_weights not in [no_lora_str, '', None]
- context_class_cast = NullContext if device == 'cpu' or have_lora_weights else torch.autocast
- with context_class_cast(device):
- if stream_output and streamer:
- answer = None
- import queue
- bucket = queue.Queue()
- thread = EThread(target=chain, streamer=streamer, bucket=bucket)
- thread.start()
- outputs = ""
- prompt = None # FIXME
- try:
- for new_text in streamer:
- # print("new_text: %s" % new_text, flush=True)
- if bucket.qsize() > 0 or thread.exc:
- thread.join()
- outputs += new_text
- if prompter: # and False: # FIXME: pipeline can already use prompter
- output1 = prompter.get_response(outputs, prompt=prompt,
- sanitize_bot_response=sanitize_bot_response)
- yield output1, ''
- else:
- yield outputs, ''
- except BaseException:
- # if any exception, raise that exception if was from thread, first
- if thread.exc:
- raise thread.exc
- raise
- finally:
- # in case no exception and didn't join with thread yet, then join
- if not thread.exc:
- answer = thread.join()
- # in case raise StopIteration or broke queue loop in streamer, but still have exception
- if thread.exc:
- raise thread.exc
- # FIXME: answer is not string outputs from streamer. How to get actual final output?
- # answer = outputs
- else:
- answer = chain()
-
- if not use_docs_planned:
- ret = answer['output_text']
- extra = ''
- yield ret, extra
- elif answer is not None:
- ret, extra = get_sources_answer(query, answer, scores, show_rank, answer_with_sources, verbose=verbose)
- yield ret, extra
- return
-
-
-def get_chain(query=None,
- iinput=None,
- context=None, # FIXME: https://github.com/hwchase17/langchain/issues/6638
- use_openai_model=False, use_openai_embedding=False,
- first_para=False, text_limit=None, top_k_docs=4, chunk=True, chunk_size=512,
- langchain_mode_paths=None,
- detect_user_path_changes_every_query=False,
- db_type='faiss',
- model_name=None,
- inference_server='',
- hf_embedding_model="sentence-transformers/all-MiniLM-L6-v2",
- prompt_type=None,
- prompt_dict=None,
- cut_distance=1.1,
- add_chat_history_to_context=True, # FIXME: https://github.com/hwchase17/langchain/issues/6638
- load_db_if_exists=False,
- db=None,
- langchain_mode=None,
- langchain_action=None,
- langchain_agents=None,
- document_subset=DocumentSubset.Relevant.name,
- document_choice=[DocumentChoice.ALL.value],
- n_jobs=-1,
- # beyond run_db_query:
- llm=None,
- tokenizer=None,
- verbose=False,
- reverse_docs=True,
-
- # local
- auto_reduce_chunks=True,
- max_chunks=100,
- ):
- assert langchain_agents is not None # should be at least []
- # determine whether use of context out of docs is planned
- if not use_openai_model and prompt_type not in ['plain'] or model_name in non_hf_types:
- if langchain_mode in ['Disabled', 'LLM']:
- use_docs_planned = False
- else:
- use_docs_planned = True
- else:
- use_docs_planned = True
-
- # https://github.com/hwchase17/langchain/issues/1946
- # FIXME: Seems to way to get size of chroma db to limit top_k_docs to avoid
- # Chroma collection MyData contains fewer than 4 elements.
- # type logger error
- if top_k_docs == -1:
- k_db = 1000 if db_type == 'chroma' else 100
- else:
- # top_k_docs=100 works ok too
- k_db = 1000 if db_type == 'chroma' else top_k_docs
-
- # FIXME: For All just go over all dbs instead of a separate db for All
- if not detect_user_path_changes_every_query and db is not None:
- # avoid looking at user_path during similarity search db handling,
- # if already have db and not updating from user_path every query
- # but if db is None, no db yet loaded (e.g. from prep), so allow user_path to be whatever it was
- if langchain_mode_paths is None:
- langchain_mode_paths = {}
- langchain_mode_paths = langchain_mode_paths.copy()
- langchain_mode_paths[langchain_mode] = None
- db, num_new_sources, new_sources_metadata = make_db(use_openai_embedding=use_openai_embedding,
- hf_embedding_model=hf_embedding_model,
- first_para=first_para, text_limit=text_limit,
- chunk=chunk,
- chunk_size=chunk_size,
- langchain_mode=langchain_mode,
- langchain_mode_paths=langchain_mode_paths,
- db_type=db_type,
- load_db_if_exists=load_db_if_exists,
- db=db,
- n_jobs=n_jobs,
- verbose=verbose)
- have_any_docs = db is not None
- if langchain_action == LangChainAction.QUERY.value:
- if iinput:
- query = "%s\n%s" % (query, iinput)
-
- if 'falcon' in model_name:
- extra = "According to only the information in the document sources provided within the context above, "
- prefix = "Pay attention and remember information below, which will help to answer the question or imperative after the context ends."
- elif inference_server in ['openai', 'openai_chat']:
- extra = "According to (primarily) the information in the document sources provided within context above, "
- prefix = "Pay attention and remember information below, which will help to answer the question or imperative after the context ends. If the answer cannot be primarily obtained from information within the context, then respond that the answer does not appear in the context of the documents."
- else:
- extra = ""
- prefix = ""
- if langchain_mode in ['Disabled', 'LLM'] or not use_docs_planned:
- template_if_no_docs = template = """%s{context}{question}""" % prefix
- else:
- template = """%s
- \"\"\"
- {context}
- \"\"\"
- %s{question}""" % (prefix, extra)
- template_if_no_docs = """%s{context}%s{question}""" % (prefix, extra)
- elif langchain_action in [LangChainAction.SUMMARIZE_ALL.value, LangChainAction.SUMMARIZE_MAP.value]:
- none = ['', '\n', None]
- if query in none and iinput in none:
- prompt_summary = "Using only the text above, write a condensed and concise summary:\n"
- elif query not in none:
- prompt_summary = "Focusing on %s, write a condensed and concise Summary:\n" % query
- elif iinput not in None:
- prompt_summary = iinput
- else:
- prompt_summary = "Focusing on %s, %s:\n" % (query, iinput)
- # don't auto reduce
- auto_reduce_chunks = False
- if langchain_action == LangChainAction.SUMMARIZE_MAP.value:
- fstring = '{text}'
- else:
- fstring = '{input_documents}'
- template = """In order to write a concise single-paragraph or bulleted list summary, pay attention to the following text:
-\"\"\"
-%s
-\"\"\"\n%s""" % (fstring, prompt_summary)
- template_if_no_docs = "Exactly only say: There are no documents to summarize."
- elif langchain_action in [LangChainAction.SUMMARIZE_REFINE]:
- template = '' # unused
- template_if_no_docs = '' # unused
- else:
- raise RuntimeError("No such langchain_action=%s" % langchain_action)
-
- if not use_openai_model and prompt_type not in ['plain'] or model_name in non_hf_types:
- use_template = True
- else:
- use_template = False
-
- if db and use_docs_planned:
- base_path = 'locks'
- makedirs(base_path)
- if hasattr(db, '_persist_directory'):
- name_path = "sim_%s.lock" % os.path.basename(db._persist_directory)
- else:
- name_path = "sim.lock"
- lock_file = os.path.join(base_path, name_path)
-
- if not isinstance(db, Chroma):
- # only chroma supports filtering
- filter_kwargs = {}
- else:
- assert document_choice is not None, "Document choice was None"
- if len(document_choice) >= 1 and document_choice[0] == DocumentChoice.ALL.value:
- filter_kwargs = {}
- elif len(document_choice) >= 2:
- if document_choice[0] == DocumentChoice.ALL.value:
- # remove 'All'
- document_choice = document_choice[1:]
- or_filter = [{"source": {"$eq": x}} for x in document_choice]
- filter_kwargs = dict(filter={"$or": or_filter})
- elif len(document_choice) == 1:
- # degenerate UX bug in chroma
- one_filter = [{"source": {"$eq": x}} for x in document_choice][0]
- filter_kwargs = dict(filter=one_filter)
- else:
- # shouldn't reach
- filter_kwargs = {}
- if langchain_mode in [LangChainMode.LLM.value]:
- docs = []
- scores = []
- elif document_subset == DocumentSubset.TopKSources.name or query in [None, '', '\n']:
- db_documents, db_metadatas = get_docs_and_meta(db, top_k_docs, filter_kwargs=filter_kwargs)
- # similar to langchain's chroma's _results_to_docs_and_scores
- docs_with_score = [(Document(page_content=result[0], metadata=result[1] or {}), 0)
- for result in zip(db_documents, db_metadatas)]
-
- # order documents
- doc_hashes = [x.get('doc_hash', 'None') for x in db_metadatas]
- doc_chunk_ids = [x.get('chunk_id', 0) for x in db_metadatas]
- docs_with_score = [x for _, _, x in
- sorted(zip(doc_hashes, doc_chunk_ids, docs_with_score), key=lambda x: (x[0], x[1]))
- ]
-
- docs_with_score = docs_with_score[:top_k_docs]
- docs = [x[0] for x in docs_with_score]
- scores = [x[1] for x in docs_with_score]
- have_any_docs |= len(docs) > 0
- else:
- # FIXME: if langchain_action == LangChainAction.SUMMARIZE_MAP.value
- # if map_reduce, then no need to auto reduce chunks
- if top_k_docs == -1 or auto_reduce_chunks:
- # docs_with_score = db.similarity_search_with_score(query, k=k_db, **filter_kwargs)[:top_k_docs]
- top_k_docs_tokenize = 100
- with filelock.FileLock(lock_file):
- docs_with_score = db.similarity_search_with_score(query, k=k_db, **filter_kwargs)[
- :top_k_docs_tokenize]
- if hasattr(llm, 'pipeline') and hasattr(llm.pipeline, 'tokenizer'):
- # more accurate
- tokens = [len(llm.pipeline.tokenizer(x[0].page_content)['input_ids']) for x in docs_with_score]
- template_tokens = len(llm.pipeline.tokenizer(template)['input_ids'])
- elif inference_server in ['openai', 'openai_chat'] or use_openai_model or db_type in ['faiss',
- 'weaviate']:
- # use ticktoken for faiss since embedding called differently
- tokens = [llm.get_num_tokens(x[0].page_content) for x in docs_with_score]
- template_tokens = llm.get_num_tokens(template)
- elif isinstance(tokenizer, FakeTokenizer):
- tokens = [tokenizer.num_tokens_from_string(x[0].page_content) for x in docs_with_score]
- template_tokens = tokenizer.num_tokens_from_string(template)
- else:
- # in case model is not our pipeline with HF tokenizer
- tokens = [db._embedding_function.client.tokenize([x[0].page_content])['input_ids'].shape[1] for x in
- docs_with_score]
- template_tokens = db._embedding_function.client.tokenize([template])['input_ids'].shape[1]
- tokens_cumsum = np.cumsum(tokens)
- if hasattr(llm, 'pipeline') and hasattr(llm.pipeline, 'max_input_tokens'):
- max_input_tokens = llm.pipeline.max_input_tokens
- elif inference_server in ['openai']:
- max_tokens = llm.modelname_to_contextsize(model_name)
- # leave some room for 1 paragraph, even if min_new_tokens=0
- max_input_tokens = max_tokens - 256
- elif inference_server in ['openai_chat']:
- max_tokens = model_token_mapping[model_name]
- # leave some room for 1 paragraph, even if min_new_tokens=0
- max_input_tokens = max_tokens - 256
- elif isinstance(tokenizer, FakeTokenizer):
- max_input_tokens = tokenizer.model_max_length - 256
- else:
- # leave some room for 1 paragraph, even if min_new_tokens=0
- max_input_tokens = 2048 - 256
- max_input_tokens -= template_tokens
- # FIXME: Doesn't account for query, == context, or new lines between contexts
- where_res = np.where(tokens_cumsum < max_input_tokens)[0]
- if where_res.shape[0] == 0:
- # then no chunk can fit, still do first one
- top_k_docs_trial = 1
- else:
- top_k_docs_trial = 1 + where_res[-1]
- if 0 < top_k_docs_trial < max_chunks:
- # avoid craziness
- if top_k_docs == -1:
- top_k_docs = top_k_docs_trial
- else:
- top_k_docs = min(top_k_docs, top_k_docs_trial)
- if top_k_docs == -1:
- # if here, means 0 and just do best with 1 doc
- print("Unexpected large chunks and can't add to context, will add 1 anyways", flush=True)
- top_k_docs = 1
- docs_with_score = docs_with_score[:top_k_docs]
- else:
- with filelock.FileLock(lock_file):
- docs_with_score = db.similarity_search_with_score(query, k=k_db, **filter_kwargs)[:top_k_docs]
- # put most relevant chunks closest to question,
- # esp. if truncation occurs will be "oldest" or "farthest from response" text that is truncated
- # BUT: for small models, e.g. 6_9 pythia, if sees some stuff related to h2oGPT first, it can connect that and not listen to rest
- if reverse_docs:
- docs_with_score.reverse()
- # cut off so no high distance docs/sources considered
- have_any_docs |= len(docs_with_score) > 0 # before cut
- docs = [x[0] for x in docs_with_score if x[1] < cut_distance]
- scores = [x[1] for x in docs_with_score if x[1] < cut_distance]
- if len(scores) > 0 and verbose:
- print("Distance: min: %s max: %s mean: %s median: %s" %
- (scores[0], scores[-1], np.mean(scores), np.median(scores)), flush=True)
- else:
- docs = []
- scores = []
-
- if not docs and use_docs_planned and model_name not in non_hf_types:
- # if HF type and have no docs, can bail out
- return docs, None, [], False, have_any_docs
-
- if document_subset in non_query_commands:
- # no LLM use
- return docs, None, [], False, have_any_docs
-
- common_words_file = "data/NGSL_1.2_stats.csv.zip"
- if os.path.isfile(common_words_file) and langchain_mode == LangChainAction.QUERY.value:
- df = pd.read_csv("data/NGSL_1.2_stats.csv.zip")
- import string
- reduced_query = query.translate(str.maketrans(string.punctuation, ' ' * len(string.punctuation))).strip()
- reduced_query_words = reduced_query.split(' ')
- set_common = set(df['Lemma'].values.tolist())
- num_common = len([x.lower() in set_common for x in reduced_query_words])
- frac_common = num_common / len(reduced_query) if reduced_query else 0
- # FIXME: report to user bad query that uses too many common words
- if verbose:
- print("frac_common: %s" % frac_common, flush=True)
-
- if len(docs) == 0:
- # avoid context == in prompt then
- use_docs_planned = False
- template = template_if_no_docs
-
- if langchain_action == LangChainAction.QUERY.value:
- if use_template:
- # instruct-like, rather than few-shot prompt_type='plain' as default
- # but then sources confuse the model with how inserted among rest of text, so avoid
- prompt = PromptTemplate(
- # input_variables=["summaries", "question"],
- input_variables=["context", "question"],
- template=template,
- )
- chain = load_qa_chain(llm, prompt=prompt)
- else:
- # only if use_openai_model = True, unused normally except in testing
- chain = load_qa_with_sources_chain(llm)
- if not use_docs_planned:
- chain_kwargs = dict(input_documents=[], question=query)
- else:
- chain_kwargs = dict(input_documents=docs, question=query)
- target = wrapped_partial(chain, chain_kwargs)
- elif langchain_action in [LangChainAction.SUMMARIZE_MAP.value,
- LangChainAction.SUMMARIZE_REFINE,
- LangChainAction.SUMMARIZE_ALL.value]:
- from langchain.chains.summarize import load_summarize_chain
- if langchain_action == LangChainAction.SUMMARIZE_MAP.value:
- prompt = PromptTemplate(input_variables=["text"], template=template)
- chain = load_summarize_chain(llm, chain_type="map_reduce",
- map_prompt=prompt, combine_prompt=prompt, return_intermediate_steps=True)
- target = wrapped_partial(chain, {"input_documents": docs}) # , return_only_outputs=True)
- elif langchain_action == LangChainAction.SUMMARIZE_ALL.value:
- assert use_template
- prompt = PromptTemplate(input_variables=["text"], template=template)
- chain = load_summarize_chain(llm, chain_type="stuff", prompt=prompt, return_intermediate_steps=True)
- target = wrapped_partial(chain)
- elif langchain_action == LangChainAction.SUMMARIZE_REFINE.value:
- chain = load_summarize_chain(llm, chain_type="refine", return_intermediate_steps=True)
- target = wrapped_partial(chain)
- else:
- raise RuntimeError("No such langchain_action=%s" % langchain_action)
- else:
- raise RuntimeError("No such langchain_action=%s" % langchain_action)
-
- return docs, target, scores, use_docs_planned, have_any_docs
-
-
-def get_sources_answer(query, answer, scores, show_rank, answer_with_sources, verbose=False):
- if verbose:
- print("query: %s" % query, flush=True)
- print("answer: %s" % answer['output_text'], flush=True)
-
- if len(answer['input_documents']) == 0:
- extra = ''
- ret = answer['output_text'] + extra
- return ret, extra
-
- # link
- answer_sources = [(max(0.0, 1.5 - score) / 1.5, get_url(doc)) for score, doc in
- zip(scores, answer['input_documents'])]
- answer_sources_dict = defaultdict(list)
- [answer_sources_dict[url].append(score) for score, url in answer_sources]
- answers_dict = {}
- for url, scores_url in answer_sources_dict.items():
- answers_dict[url] = np.max(scores_url)
- answer_sources = [(score, url) for url, score in answers_dict.items()]
- answer_sources.sort(key=lambda x: x[0], reverse=True)
- if show_rank:
- # answer_sources = ['%d | %s' % (1 + rank, url) for rank, (score, url) in enumerate(answer_sources)]
- # sorted_sources_urls = "Sources [Rank | Link]:
" + "
".join(answer_sources)
- answer_sources = ['%s' % url for rank, (score, url) in enumerate(answer_sources)]
- sorted_sources_urls = "Ranked Sources:
" + "
".join(answer_sources)
- else:
- answer_sources = ['" + "
')
- text = '```'.join(ts)
- return text
-
-
-def go_gradio(**kwargs):
- allow_api = kwargs['allow_api']
- is_public = kwargs['is_public']
- is_hf = kwargs['is_hf']
- memory_restriction_level = kwargs['memory_restriction_level']
- n_gpus = kwargs['n_gpus']
- admin_pass = kwargs['admin_pass']
- model_states = kwargs['model_states']
- dbs = kwargs['dbs']
- db_type = kwargs['db_type']
- visible_langchain_actions = kwargs['visible_langchain_actions']
- visible_langchain_agents = kwargs['visible_langchain_agents']
- allow_upload_to_user_data = kwargs['allow_upload_to_user_data']
- allow_upload_to_my_data = kwargs['allow_upload_to_my_data']
- enable_sources_list = kwargs['enable_sources_list']
- enable_url_upload = kwargs['enable_url_upload']
- enable_text_upload = kwargs['enable_text_upload']
- use_openai_embedding = kwargs['use_openai_embedding']
- hf_embedding_model = kwargs['hf_embedding_model']
- enable_captions = kwargs['enable_captions']
- captions_model = kwargs['captions_model']
- enable_ocr = kwargs['enable_ocr']
- enable_pdf_ocr = kwargs['enable_pdf_ocr']
- caption_loader = kwargs['caption_loader']
-
- # for dynamic state per user session in gradio
- model_state0 = kwargs['model_state0']
- score_model_state0 = kwargs['score_model_state0']
- my_db_state0 = kwargs['my_db_state0']
- selection_docs_state0 = kwargs['selection_docs_state0']
- # for evaluate defaults
- langchain_modes0 = kwargs['langchain_modes']
- visible_langchain_modes0 = kwargs['visible_langchain_modes']
- langchain_mode_paths0 = kwargs['langchain_mode_paths']
-
- # easy update of kwargs needed for evaluate() etc.
- queue = True
- allow_upload = allow_upload_to_user_data or allow_upload_to_my_data
- kwargs.update(locals())
-
- # import control
- if kwargs['langchain_mode'] != 'Disabled':
- from gpt_langchain import file_types, have_arxiv
- else:
- have_arxiv = False
- file_types = []
-
- if 'mbart-' in kwargs['model_lower']:
- instruction_label_nochat = "Text to translate"
- else:
- instruction_label_nochat = "Instruction (Shift-Enter or push Submit to send message," \
- " use Enter for multiple input lines)"
-
- title = 'h2oGPT'
- description = """h2oGPT H2O LLM Studio
🤗 Models"""
- description_bottom = "If this host is busy, try
[Multi-Model](https://gpt.h2o.ai)
[Falcon 40B](https://falcon.h2o.ai)
[Vicuna 33B](https://wizardvicuna.h2o.ai)
[MPT 30B-Chat](https://mpt.h2o.ai)
[HF Spaces1](https://huggingface.co/spaces/h2oai/h2ogpt-chatbot)
[HF Spaces2](https://huggingface.co/spaces/h2oai/h2ogpt-chatbot2)
"
- if is_hf:
- description_bottom += ''''''
- task_info_md = ''
- css_code = get_css(kwargs)
-
- if kwargs['gradio_offline_level'] >= 0:
- # avoid GoogleFont that pulls from internet
- if kwargs['gradio_offline_level'] == 1:
- # front end would still have to download fonts or have cached it at some point
- base_font = 'Source Sans Pro'
- else:
- base_font = 'Helvetica'
- theme_kwargs = dict(font=(base_font, 'ui-sans-serif', 'system-ui', 'sans-serif'),
- font_mono=('IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace'))
- else:
- theme_kwargs = dict()
- if kwargs['gradio_size'] == 'xsmall':
- theme_kwargs.update(dict(spacing_size=spacing_xsm, text_size=text_xsm, radius_size=radius_xsm))
- elif kwargs['gradio_size'] in [None, 'small']:
- theme_kwargs.update(dict(spacing_size=gr.themes.sizes.spacing_sm, text_size=gr.themes.sizes.text_sm,
- radius_size=gr.themes.sizes.spacing_sm))
- elif kwargs['gradio_size'] == 'large':
- theme_kwargs.update(dict(spacing_size=gr.themes.sizes.spacing_lg, text_size=gr.themes.sizes.text_lg),
- radius_size=gr.themes.sizes.spacing_lg)
- elif kwargs['gradio_size'] == 'medium':
- theme_kwargs.update(dict(spacing_size=gr.themes.sizes.spacing_md, text_size=gr.themes.sizes.text_md,
- radius_size=gr.themes.sizes.spacing_md))
-
- theme = H2oTheme(**theme_kwargs) if kwargs['h2ocolors'] else SoftTheme(**theme_kwargs)
- demo = gr.Blocks(theme=theme, css=css_code, title="h2oGPT", analytics_enabled=False)
- callback = gr.CSVLogger()
-
- model_options0 = flatten_list(list(prompt_type_to_model_name.values())) + kwargs['extra_model_options']
- if kwargs['base_model'].strip() not in model_options0:
- model_options0 = [kwargs['base_model'].strip()] + model_options0
- lora_options = kwargs['extra_lora_options']
- if kwargs['lora_weights'].strip() not in lora_options:
- lora_options = [kwargs['lora_weights'].strip()] + lora_options
- server_options = kwargs['extra_server_options']
- if kwargs['inference_server'].strip() not in server_options:
- server_options = [kwargs['inference_server'].strip()] + server_options
- if os.getenv('OPENAI_API_KEY'):
- if 'openai_chat' not in server_options:
- server_options += ['openai_chat']
- if 'openai' not in server_options:
- server_options += ['openai']
-
- # always add in no lora case
- # add fake space so doesn't go away in gradio dropdown
- model_options0 = [no_model_str] + model_options0
- lora_options = [no_lora_str] + lora_options
- server_options = [no_server_str] + server_options
- # always add in no model case so can free memory
- # add fake space so doesn't go away in gradio dropdown
-
- # transcribe, will be detranscribed before use by evaluate()
- if not kwargs['base_model'].strip():
- kwargs['base_model'] = no_model_str
-
- if not kwargs['lora_weights'].strip():
- kwargs['lora_weights'] = no_lora_str
-
- if not kwargs['inference_server'].strip():
- kwargs['inference_server'] = no_server_str
-
- # transcribe for gradio
- kwargs['gpu_id'] = str(kwargs['gpu_id'])
-
- no_model_msg = 'h2oGPT [ !!! Please Load Model in Models Tab !!! ]'
- output_label0 = f'h2oGPT [Model: {kwargs.get("base_model")}]' if kwargs.get(
- 'base_model') else no_model_msg
- output_label0_model2 = no_model_msg
-
- def update_prompt(prompt_type1, prompt_dict1, model_state1, which_model=0):
- if not prompt_type1 or which_model != 0:
- # keep prompt_type and prompt_dict in sync if possible
- prompt_type1 = kwargs.get('prompt_type', prompt_type1)
- prompt_dict1 = kwargs.get('prompt_dict', prompt_dict1)
- # prefer model specific prompt type instead of global one
- if not prompt_type1 or which_model != 0:
- prompt_type1 = model_state1.get('prompt_type', prompt_type1)
- prompt_dict1 = model_state1.get('prompt_dict', prompt_dict1)
-
- if not prompt_dict1 or which_model != 0:
- # if still not defined, try to get
- prompt_dict1 = kwargs.get('prompt_dict', prompt_dict1)
- if not prompt_dict1 or which_model != 0:
- prompt_dict1 = model_state1.get('prompt_dict', prompt_dict1)
- return prompt_type1, prompt_dict1
-
- default_kwargs = {k: kwargs[k] for k in eval_func_param_names_defaults}
- # ensure prompt_type consistent with prep_bot(), so nochat API works same way
- default_kwargs['prompt_type'], default_kwargs['prompt_dict'] = \
- update_prompt(default_kwargs['prompt_type'], default_kwargs['prompt_dict'],
- model_state1=model_state0, which_model=0)
- for k in no_default_param_names:
- default_kwargs[k] = ''
-
- def dummy_fun(x):
- # need dummy function to block new input from being sent until output is done,
- # else gets input_list at time of submit that is old, and shows up as truncated in chatbot
- return x
-
- def allow_empty_instruction(langchain_mode1, document_subset1, langchain_action1):
- allow = False
- allow |= langchain_action1 not in LangChainAction.QUERY.value
- allow |= document_subset1 in DocumentSubset.TopKSources.name
- if langchain_mode1 in [LangChainMode.LLM.value]:
- allow = False
- return allow
-
- with demo:
- # avoid actual model/tokenizer here or anything that would be bad to deepcopy
- # https://github.com/gradio-app/gradio/issues/3558
- model_state = gr.State(
- dict(model='model', tokenizer='tokenizer', device=kwargs['device'],
- base_model=kwargs['base_model'],
- tokenizer_base_model=kwargs['tokenizer_base_model'],
- lora_weights=kwargs['lora_weights'],
- inference_server=kwargs['inference_server'],
- prompt_type=kwargs['prompt_type'],
- prompt_dict=kwargs['prompt_dict'],
- )
- )
-
- def update_langchain_mode_paths(db1s, selection_docs_state1):
- if allow_upload_to_my_data:
- selection_docs_state1['langchain_mode_paths'].update({k: None for k in db1s})
- dup = selection_docs_state1['langchain_mode_paths'].copy()
- for k, v in dup.items():
- if k not in selection_docs_state1['visible_langchain_modes']:
- selection_docs_state1['langchain_mode_paths'].pop(k)
- return selection_docs_state1
-
- # Setup some gradio states for per-user dynamic state
- model_state2 = gr.State(kwargs['model_state_none'].copy())
- model_options_state = gr.State([model_options0])
- lora_options_state = gr.State([lora_options])
- server_options_state = gr.State([server_options])
- my_db_state = gr.State(my_db_state0)
- chat_state = gr.State({})
- docs_state00 = kwargs['document_choice'] + [DocumentChoice.ALL.value]
- docs_state0 = []
- [docs_state0.append(x) for x in docs_state00 if x not in docs_state0]
- docs_state = gr.State(docs_state0)
- viewable_docs_state0 = []
- viewable_docs_state = gr.State(viewable_docs_state0)
- selection_docs_state0 = update_langchain_mode_paths(my_db_state0, selection_docs_state0)
- selection_docs_state = gr.State(selection_docs_state0)
-
- gr.Markdown(f"""
- {get_h2o_title(title, description) if kwargs['h2ocolors'] else get_simple_title(title, description)}
- """)
-
- # go button visible if
- base_wanted = kwargs['base_model'] != no_model_str and kwargs['login_mode_if_model0']
- go_btn = gr.Button(value="ENTER", visible=base_wanted, variant="primary")
-
- nas = ' '.join(['NA'] * len(kwargs['model_states']))
- res_value = "Response Score: NA" if not kwargs[
- 'model_lock'] else "Response Scores: %s" % nas
-
- if kwargs['langchain_mode'] != LangChainMode.DISABLED.value:
- extra_prompt_form = ". For summarization, no query required, just click submit"
- else:
- extra_prompt_form = ""
- if kwargs['input_lines'] > 1:
- instruction_label = "Shift-Enter to Submit, Enter for more lines%s" % extra_prompt_form
- else:
- instruction_label = "Enter to Submit, Shift-Enter for more lines%s" % extra_prompt_form
-
- def get_langchain_choices(selection_docs_state1):
- langchain_modes = selection_docs_state1['langchain_modes']
- visible_langchain_modes = selection_docs_state1['visible_langchain_modes']
-
- if is_hf:
- # don't show 'wiki' since only usually useful for internal testing at moment
- no_show_modes = ['Disabled', 'wiki']
- else:
- no_show_modes = ['Disabled']
- allowed_modes = visible_langchain_modes.copy()
- # allowed_modes = [x for x in allowed_modes if x in dbs]
- allowed_modes += ['LLM']
- if allow_upload_to_my_data and 'MyData' not in allowed_modes:
- allowed_modes += ['MyData']
- if allow_upload_to_user_data and 'UserData' not in allowed_modes:
- allowed_modes += ['UserData']
- choices = [x for x in langchain_modes if x in allowed_modes and x not in no_show_modes]
- return choices
-
- def get_df_langchain_mode_paths(selection_docs_state1):
- langchain_mode_paths = selection_docs_state1['langchain_mode_paths']
- if langchain_mode_paths:
- df = pd.DataFrame.from_dict(langchain_mode_paths.items(), orient='columns')
- df.columns = ['Collection', 'Path']
- else:
- df = pd.DataFrame(None)
- return df
-
- normal_block = gr.Row(visible=not base_wanted, equal_height=False)
- with normal_block:
- side_bar = gr.Column(elem_id="col_container", scale=1, min_width=100)
- with side_bar:
- with gr.Accordion("Chats", open=False, visible=True):
- radio_chats = gr.Radio(value=None, label="Saved Chats", show_label=False,
- visible=True, interactive=True,
- type='value')
- upload_visible = kwargs['langchain_mode'] != 'Disabled' and allow_upload
- with gr.Accordion("Upload", open=False, visible=upload_visible):
- with gr.Column():
- with gr.Row(equal_height=False):
- file_types_str = '[' + ' '.join(file_types) + ' URL ArXiv TEXT' + ']'
- fileup_output = gr.File(label=f'Upload {file_types_str}',
- show_label=False,
- file_types=file_types,
- file_count="multiple",
- scale=1,
- min_width=0,
- elem_id="warning", elem_classes="feedback")
- fileup_output_text = gr.Textbox(visible=False)
- url_visible = kwargs['langchain_mode'] != 'Disabled' and allow_upload and enable_url_upload
- url_label = 'URL/ArXiv' if have_arxiv else 'URL'
- url_text = gr.Textbox(label=url_label,
- # placeholder="Enter Submits",
- max_lines=1,
- interactive=True)
- text_visible = kwargs['langchain_mode'] != 'Disabled' and allow_upload and enable_text_upload
- user_text_text = gr.Textbox(label='Paste Text',
- # placeholder="Enter Submits",
- interactive=True,
- visible=text_visible)
- github_textbox = gr.Textbox(label="Github URL", visible=False) # FIXME WIP
- database_visible = kwargs['langchain_mode'] != 'Disabled'
- with gr.Accordion("Resources", open=False, visible=database_visible):
- langchain_choices0 = get_langchain_choices(selection_docs_state0)
- langchain_mode = gr.Radio(
- langchain_choices0,
- value=kwargs['langchain_mode'],
- label="Collections",
- show_label=True,
- visible=kwargs['langchain_mode'] != 'Disabled',
- min_width=100)
- add_chat_history_to_context = gr.Checkbox(label="Chat History",
- value=kwargs['add_chat_history_to_context'])
- document_subset = gr.Radio([x.name for x in DocumentSubset],
- label="Subset",
- value=DocumentSubset.Relevant.name,
- interactive=True,
- )
- allowed_actions = [x for x in langchain_actions if x in visible_langchain_actions]
- langchain_action = gr.Radio(
- allowed_actions,
- value=allowed_actions[0] if len(allowed_actions) > 0 else None,
- label="Action",
- visible=True)
- allowed_agents = [x for x in langchain_agents_list if x in visible_langchain_agents]
- langchain_agents = gr.Dropdown(
- langchain_agents_list,
- value=kwargs['langchain_agents'],
- label="Agents",
- multiselect=True,
- interactive=True,
- visible=False) # WIP
- col_tabs = gr.Column(elem_id="col_container", scale=10)
- with (col_tabs, gr.Tabs()):
- with gr.TabItem("Chat"):
- if kwargs['langchain_mode'] == 'Disabled':
- text_output_nochat = gr.Textbox(lines=5, label=output_label0, show_copy_button=True,
- visible=not kwargs['chat'])
- else:
- # text looks a bit worse, but HTML links work
- text_output_nochat = gr.HTML(label=output_label0, visible=not kwargs['chat'])
- with gr.Row():
- # NOCHAT
- instruction_nochat = gr.Textbox(
- lines=kwargs['input_lines'],
- label=instruction_label_nochat,
- placeholder=kwargs['placeholder_instruction'],
- visible=not kwargs['chat'],
- )
- iinput_nochat = gr.Textbox(lines=4, label="Input context for Instruction",
- placeholder=kwargs['placeholder_input'],
- visible=not kwargs['chat'])
- submit_nochat = gr.Button("Submit", size='sm', visible=not kwargs['chat'])
- flag_btn_nochat = gr.Button("Flag", size='sm', visible=not kwargs['chat'])
- score_text_nochat = gr.Textbox("Response Score: NA", show_label=False,
- visible=not kwargs['chat'])
- submit_nochat_api = gr.Button("Submit nochat API", visible=False)
- inputs_dict_str = gr.Textbox(label='API input for nochat', show_label=False, visible=False)
- text_output_nochat_api = gr.Textbox(lines=5, label='API nochat output', visible=False,
- show_copy_button=True)
-
- # CHAT
- col_chat = gr.Column(visible=kwargs['chat'])
- with col_chat:
- with gr.Row(): # elem_id='prompt-form-area'):
- with gr.Column(scale=50):
- instruction = gr.Textbox(
- lines=kwargs['input_lines'],
- label='Ask anything',
- placeholder=instruction_label,
- info=None,
- elem_id='prompt-form',
- container=True,
- )
- submit_buttons = gr.Row(equal_height=False)
- with submit_buttons:
- mw1 = 50
- mw2 = 50
- with gr.Column(min_width=mw1):
- submit = gr.Button(value='Submit', variant='primary', size='sm',
- min_width=mw1)
- stop_btn = gr.Button(value="Stop", variant='secondary', size='sm',
- min_width=mw1)
- save_chat_btn = gr.Button("Save", size='sm', min_width=mw1)
- with gr.Column(min_width=mw2):
- retry_btn = gr.Button("Redo", size='sm', min_width=mw2)
- undo = gr.Button("Undo", size='sm', min_width=mw2)
- clear_chat_btn = gr.Button(value="Clear", size='sm', min_width=mw2)
- text_output, text_output2, text_outputs = make_chatbots(output_label0, output_label0_model2,
- **kwargs)
-
- with gr.Row():
- with gr.Column(visible=kwargs['score_model']):
- score_text = gr.Textbox(res_value,
- show_label=False,
- visible=True)
- score_text2 = gr.Textbox("Response Score2: NA", show_label=False,
- visible=False and not kwargs['model_lock'])
-
- with gr.TabItem("Document Selection"):
- document_choice = gr.Dropdown(docs_state0,
- label="Select Subset of Document(s) %s" % file_types_str,
- value=[DocumentChoice.ALL.value],
- interactive=True,
- multiselect=True,
- visible=kwargs['langchain_mode'] != 'Disabled',
- )
- sources_visible = kwargs['langchain_mode'] != 'Disabled' and enable_sources_list
- with gr.Row():
- with gr.Column(scale=1):
- get_sources_btn = gr.Button(value="Update UI with Document(s) from DB", scale=0, size='sm',
- visible=sources_visible)
- show_sources_btn = gr.Button(value="Show Sources from DB", scale=0, size='sm',
- visible=sources_visible)
- refresh_sources_btn = gr.Button(value="Update DB with new/changed files on disk", scale=0,
- size='sm',
- visible=sources_visible and allow_upload_to_user_data)
- with gr.Column(scale=4):
- pass
- with gr.Row():
- with gr.Column(scale=1):
- visible_add_remove_collection = (allow_upload_to_user_data or
- allow_upload_to_my_data) and \
- kwargs['langchain_mode'] != 'Disabled'
- add_placeholder = "e.g. UserData2, user_path2 (optional)" \
- if not is_public else "e.g. MyData2"
- remove_placeholder = "e.g. UserData2" if not is_public else "e.g. MyData2"
- new_langchain_mode_text = gr.Textbox(value="", visible=visible_add_remove_collection,
- label='Add Collection',
- placeholder=add_placeholder,
- interactive=True)
- remove_langchain_mode_text = gr.Textbox(value="", visible=visible_add_remove_collection,
- label='Remove Collection',
- placeholder=remove_placeholder,
- interactive=True)
- load_langchain = gr.Button(value="Load LangChain State", scale=0, size='sm',
- visible=allow_upload_to_user_data and
- kwargs['langchain_mode'] != 'Disabled')
- with gr.Column(scale=1):
- df0 = get_df_langchain_mode_paths(selection_docs_state0)
- langchain_mode_path_text = gr.Dataframe(value=df0,
- visible=visible_add_remove_collection,
- label='LangChain Mode-Path',
- show_label=False,
- interactive=False)
- with gr.Column(scale=4):
- pass
-
- sources_row = gr.Row(visible=kwargs['langchain_mode'] != 'Disabled' and enable_sources_list,
- equal_height=False)
- with sources_row:
- with gr.Column(scale=1):
- file_source = gr.File(interactive=False,
- label="Download File w/Sources")
- with gr.Column(scale=2):
- sources_text = gr.HTML(label='Sources Added', interactive=False)
-
- doc_exception_text = gr.Textbox(value="", label='Document Exceptions',
- interactive=False,
- visible=kwargs['langchain_mode'] != 'Disabled')
- with gr.TabItem("Document Viewer"):
- with gr.Row(visible=kwargs['langchain_mode'] != 'Disabled'):
- with gr.Column(scale=2):
- get_viewable_sources_btn = gr.Button(value="Update UI with Document(s) from DB", scale=0,
- size='sm',
- visible=sources_visible)
- view_document_choice = gr.Dropdown(viewable_docs_state0,
- label="Select Single Document",
- value=None,
- interactive=True,
- multiselect=False,
- visible=True,
- )
- with gr.Column(scale=4):
- pass
- document = 'http://infolab.stanford.edu/pub/papers/google.pdf'
- doc_view = gr.HTML(visible=False)
- doc_view2 = gr.Dataframe(visible=False)
- doc_view3 = gr.JSON(visible=False)
- doc_view4 = gr.Markdown(visible=False)
-
- with gr.TabItem("Chat History"):
- with gr.Row():
- with gr.Column(scale=1):
- remove_chat_btn = gr.Button(value="Remove Selected Saved Chats", visible=True, size='sm')
- flag_btn = gr.Button("Flag Current Chat", size='sm')
- export_chats_btn = gr.Button(value="Export Chats to Download", size='sm')
- with gr.Column(scale=4):
- pass
- with gr.Row():
- chats_file = gr.File(interactive=False, label="Download Exported Chats")
- chatsup_output = gr.File(label="Upload Chat File(s)",
- file_types=['.json'],
- file_count='multiple',
- elem_id="warning", elem_classes="feedback")
- with gr.Row():
- if 'mbart-' in kwargs['model_lower']:
- src_lang = gr.Dropdown(list(languages_covered().keys()),
- value=kwargs['src_lang'],
- label="Input Language")
- tgt_lang = gr.Dropdown(list(languages_covered().keys()),
- value=kwargs['tgt_lang'],
- label="Output Language")
-
- chat_exception_text = gr.Textbox(value="", visible=True, label='Chat Exceptions',
- interactive=False)
- with gr.TabItem("Expert"):
- with gr.Row():
- with gr.Column():
- stream_output = gr.components.Checkbox(label="Stream output",
- value=kwargs['stream_output'])
- prompt_type = gr.Dropdown(prompt_types_strings,
- value=kwargs['prompt_type'], label="Prompt Type",
- visible=not kwargs['model_lock'],
- interactive=not is_public,
- )
- prompt_type2 = gr.Dropdown(prompt_types_strings,
- value=kwargs['prompt_type'], label="Prompt Type Model 2",
- visible=False and not kwargs['model_lock'],
- interactive=not is_public)
- do_sample = gr.Checkbox(label="Sample",
- info="Enable sampler, required for use of temperature, top_p, top_k",
- value=kwargs['do_sample'])
- temperature = gr.Slider(minimum=0.01, maximum=2,
- value=kwargs['temperature'],
- label="Temperature",
- info="Lower is deterministic (but may lead to repeats), Higher more creative (but may lead to hallucinations)")
- top_p = gr.Slider(minimum=1e-3, maximum=1.0 - 1e-3,
- value=kwargs['top_p'], label="Top p",
- info="Cumulative probability of tokens to sample from")
- top_k = gr.Slider(
- minimum=1, maximum=100, step=1,
- value=kwargs['top_k'], label="Top k",
- info='Num. tokens to sample from'
- )
- # FIXME: https://github.com/h2oai/h2ogpt/issues/106
- if os.getenv('TESTINGFAIL'):
- max_beams = 8 if not (memory_restriction_level or is_public) else 1
- else:
- max_beams = 1
- num_beams = gr.Slider(minimum=1, maximum=max_beams, step=1,
- value=min(max_beams, kwargs['num_beams']), label="Beams",
- info="Number of searches for optimal overall probability. "
- "Uses more GPU memory/compute",
- interactive=False)
- max_max_new_tokens = get_max_max_new_tokens(model_state0, **kwargs)
- max_new_tokens = gr.Slider(
- minimum=1, maximum=max_max_new_tokens, step=1,
- value=min(max_max_new_tokens, kwargs['max_new_tokens']), label="Max output length",
- )
- min_new_tokens = gr.Slider(
- minimum=0, maximum=max_max_new_tokens, step=1,
- value=min(max_max_new_tokens, kwargs['min_new_tokens']), label="Min output length",
- )
- max_new_tokens2 = gr.Slider(
- minimum=1, maximum=max_max_new_tokens, step=1,
- value=min(max_max_new_tokens, kwargs['max_new_tokens']), label="Max output length 2",
- visible=False and not kwargs['model_lock'],
- )
- min_new_tokens2 = gr.Slider(
- minimum=0, maximum=max_max_new_tokens, step=1,
- value=min(max_max_new_tokens, kwargs['min_new_tokens']), label="Min output length 2",
- visible=False and not kwargs['model_lock'],
- )
- early_stopping = gr.Checkbox(label="EarlyStopping", info="Stop early in beam search",
- value=kwargs['early_stopping'])
- max_time = gr.Slider(minimum=0, maximum=kwargs['max_max_time'], step=1,
- value=min(kwargs['max_max_time'],
- kwargs['max_time']), label="Max. time",
- info="Max. time to search optimal output.")
- repetition_penalty = gr.Slider(minimum=0.01, maximum=3.0,
- value=kwargs['repetition_penalty'],
- label="Repetition Penalty")
- num_return_sequences = gr.Slider(minimum=1, maximum=10, step=1,
- value=kwargs['num_return_sequences'],
- label="Number Returns", info="Must be <= num_beams",
- interactive=not is_public)
- iinput = gr.Textbox(lines=4, label="Input",
- placeholder=kwargs['placeholder_input'],
- interactive=not is_public)
- context = gr.Textbox(lines=3, label="System Pre-Context",
- info="Directly pre-appended without prompt processing",
- interactive=not is_public)
- chat = gr.components.Checkbox(label="Chat mode", value=kwargs['chat'],
- visible=False, # no longer support nochat in UI
- interactive=not is_public,
- )
- count_chat_tokens_btn = gr.Button(value="Count Chat Tokens",
- visible=not is_public and not kwargs['model_lock'],
- interactive=not is_public)
- chat_token_count = gr.Textbox(label="Chat Token Count", value=None,
- visible=not is_public and not kwargs['model_lock'],
- interactive=False)
- chunk = gr.components.Checkbox(value=kwargs['chunk'],
- label="Whether to chunk documents",
- info="For LangChain",
- visible=kwargs['langchain_mode'] != 'Disabled',
- interactive=not is_public)
- min_top_k_docs, max_top_k_docs, label_top_k_docs = get_minmax_top_k_docs(is_public)
- top_k_docs = gr.Slider(minimum=min_top_k_docs, maximum=max_top_k_docs, step=1,
- value=kwargs['top_k_docs'],
- label=label_top_k_docs,
- info="For LangChain",
- visible=kwargs['langchain_mode'] != 'Disabled',
- interactive=not is_public)
- chunk_size = gr.Number(value=kwargs['chunk_size'],
- label="Chunk size for document chunking",
- info="For LangChain (ignored if chunk=False)",
- minimum=128,
- maximum=2048,
- visible=kwargs['langchain_mode'] != 'Disabled',
- interactive=not is_public,
- precision=0)
-
- with gr.TabItem("Models"):
- model_lock_msg = gr.Textbox(lines=1, label="Model Lock Notice",
- placeholder="Started in model_lock mode, no model changes allowed.",
- visible=bool(kwargs['model_lock']), interactive=False)
- load_msg = "Load-Unload Model/LORA [unload works if did not use --base_model]" if not is_public \
- else "LOAD-UNLOAD DISABLED FOR HOSTED DEMO"
- load_msg2 = "Load-Unload Model/LORA 2 [unload works if did not use --base_model]" if not is_public \
- else "LOAD-UNLOAD DISABLED FOR HOSTED DEMO 2"
- variant_load_msg = 'primary' if not is_public else 'secondary'
- compare_checkbox = gr.components.Checkbox(label="Compare Mode",
- value=kwargs['model_lock'],
- visible=not is_public and not kwargs['model_lock'])
- with gr.Row():
- n_gpus_list = [str(x) for x in list(range(-1, n_gpus))]
- with gr.Column():
- with gr.Row():
- with gr.Column(scale=20, visible=not kwargs['model_lock']):
- model_choice = gr.Dropdown(model_options_state.value[0], label="Choose Model",
- value=kwargs['base_model'])
- lora_choice = gr.Dropdown(lora_options_state.value[0], label="Choose LORA",
- value=kwargs['lora_weights'], visible=kwargs['show_lora'])
- server_choice = gr.Dropdown(server_options_state.value[0], label="Choose Server",
- value=kwargs['inference_server'], visible=not is_public)
- with gr.Column(scale=1, visible=not kwargs['model_lock']):
- load_model_button = gr.Button(load_msg, variant=variant_load_msg, scale=0,
- size='sm', interactive=not is_public)
- model_load8bit_checkbox = gr.components.Checkbox(
- label="Load 8-bit [requires support]",
- value=kwargs['load_8bit'], interactive=not is_public)
- model_use_gpu_id_checkbox = gr.components.Checkbox(
- label="Choose Devices [If not Checked, use all GPUs]",
- value=kwargs['use_gpu_id'], interactive=not is_public)
- model_gpu = gr.Dropdown(n_gpus_list,
- label="GPU ID [-1 = all GPUs, if Choose is enabled]",
- value=kwargs['gpu_id'], interactive=not is_public)
- model_used = gr.Textbox(label="Current Model", value=kwargs['base_model'],
- interactive=False)
- lora_used = gr.Textbox(label="Current LORA", value=kwargs['lora_weights'],
- visible=kwargs['show_lora'], interactive=False)
- server_used = gr.Textbox(label="Current Server",
- value=kwargs['inference_server'],
- visible=bool(kwargs['inference_server']) and not is_public,
- interactive=False)
- prompt_dict = gr.Textbox(label="Prompt (or Custom)",
- value=pprint.pformat(kwargs['prompt_dict'], indent=4),
- interactive=not is_public, lines=4)
- col_model2 = gr.Column(visible=False)
- with col_model2:
- with gr.Row():
- with gr.Column(scale=20, visible=not kwargs['model_lock']):
- model_choice2 = gr.Dropdown(model_options_state.value[0], label="Choose Model 2",
- value=no_model_str)
- lora_choice2 = gr.Dropdown(lora_options_state.value[0], label="Choose LORA 2",
- value=no_lora_str,
- visible=kwargs['show_lora'])
- server_choice2 = gr.Dropdown(server_options_state.value[0], label="Choose Server 2",
- value=no_server_str,
- visible=not is_public)
- with gr.Column(scale=1, visible=not kwargs['model_lock']):
- load_model_button2 = gr.Button(load_msg2, variant=variant_load_msg, scale=0,
- size='sm', interactive=not is_public)
- model_load8bit_checkbox2 = gr.components.Checkbox(
- label="Load 8-bit 2 [requires support]",
- value=kwargs['load_8bit'], interactive=not is_public)
- model_use_gpu_id_checkbox2 = gr.components.Checkbox(
- label="Choose Devices 2 [If not Checked, use all GPUs]",
- value=kwargs[
- 'use_gpu_id'], interactive=not is_public)
- model_gpu2 = gr.Dropdown(n_gpus_list,
- label="GPU ID 2 [-1 = all GPUs, if choose is enabled]",
- value=kwargs['gpu_id'], interactive=not is_public)
- # no model/lora loaded ever in model2 by default
- model_used2 = gr.Textbox(label="Current Model 2", value=no_model_str,
- interactive=False)
- lora_used2 = gr.Textbox(label="Current LORA 2", value=no_lora_str,
- visible=kwargs['show_lora'], interactive=False)
- server_used2 = gr.Textbox(label="Current Server 2", value=no_server_str,
- interactive=False,
- visible=not is_public)
- prompt_dict2 = gr.Textbox(label="Prompt (or Custom) 2",
- value=pprint.pformat(kwargs['prompt_dict'], indent=4),
- interactive=not is_public, lines=4)
- with gr.Row(visible=not kwargs['model_lock']):
- with gr.Column(scale=50):
- new_model = gr.Textbox(label="New Model name/path", interactive=not is_public)
- with gr.Column(scale=50):
- new_lora = gr.Textbox(label="New LORA name/path", visible=kwargs['show_lora'],
- interactive=not is_public)
- with gr.Column(scale=50):
- new_server = gr.Textbox(label="New Server url:port", interactive=not is_public)
- with gr.Row():
- add_model_lora_server_button = gr.Button("Add new Model, Lora, Server url:port", scale=0,
- size='sm', interactive=not is_public)
- with gr.TabItem("System"):
- with gr.Row():
- with gr.Column(scale=1):
- side_bar_text = gr.Textbox('on', visible=False, interactive=False)
- submit_buttons_text = gr.Textbox('on', visible=False, interactive=False)
-
- side_bar_btn = gr.Button("Toggle SideBar", variant="secondary", size="sm")
- submit_buttons_btn = gr.Button("Toggle Submit Buttons", variant="secondary", size="sm")
- col_tabs_scale = gr.Slider(minimum=1, maximum=20, value=10, step=1, label='Window Size')
- text_outputs_height = gr.Slider(minimum=100, maximum=2000, value=kwargs['height'] or 400,
- step=50, label='Chat Height')
- dark_mode_btn = gr.Button("Dark Mode", variant="secondary", size="sm")
- with gr.Column(scale=4):
- pass
- system_visible0 = not is_public and not admin_pass
- admin_row = gr.Row()
- with admin_row:
- with gr.Column(scale=1):
- admin_pass_textbox = gr.Textbox(label="Admin Password", type='password',
- visible=not system_visible0)
- with gr.Column(scale=4):
- pass
- system_row = gr.Row(visible=system_visible0)
- with system_row:
- with gr.Column():
- with gr.Row():
- system_btn = gr.Button(value='Get System Info', size='sm')
- system_text = gr.Textbox(label='System Info', interactive=False, show_copy_button=True)
- with gr.Row():
- system_input = gr.Textbox(label='System Info Dict Password', interactive=True,
- visible=not is_public)
- system_btn2 = gr.Button(value='Get System Info Dict', visible=not is_public, size='sm')
- system_text2 = gr.Textbox(label='System Info Dict', interactive=False,
- visible=not is_public, show_copy_button=True)
- with gr.Row():
- system_btn3 = gr.Button(value='Get Hash', visible=not is_public, size='sm')
- system_text3 = gr.Textbox(label='Hash', interactive=False,
- visible=not is_public, show_copy_button=True)
-
- with gr.Row():
- zip_btn = gr.Button("Zip", size='sm')
- zip_text = gr.Textbox(label="Zip file name", interactive=False)
- file_output = gr.File(interactive=False, label="Zip file to Download")
- with gr.Row():
- s3up_btn = gr.Button("S3UP", size='sm')
- s3up_text = gr.Textbox(label='S3UP result', interactive=False)
-
- with gr.TabItem("Terms of Service"):
- description = ""
- description += """
etc. added in chat, try to remove some of that to help avoid dup entries when hit new conversation - is_same = True - # length of conversation has to be same - if len(x) != len(y): - return False - if len(x) != len(y): - return False - for stepx, stepy in zip(x, y): - if len(stepx) != len(stepy): - # something off with a conversation - return False - for stepxx, stepyy in zip(stepx, stepy): - if len(stepxx) != len(stepyy): - # something off with a conversation - return False - if len(stepxx) != 2: - # something off - return False - if len(stepyy) != 2: - # something off - return False - questionx = stepxx[0].replace('
', '').replace('
', '') if stepxx[0] is not None else None - answerx = stepxx[1].replace('', '').replace('
', '') if stepxx[1] is not None else None - - questiony = stepyy[0].replace('', '').replace('
', '') if stepyy[0] is not None else None - answery = stepyy[1].replace('', '').replace('
', '') if stepyy[1] is not None else None - - if questionx != questiony or answerx != answery: - return False - return is_same - - def save_chat(*args, chat_is_list=False): - args_list = list(args) - if not chat_is_list: - # list of chatbot histories, - # can't pass in list with list of chatbot histories and state due to gradio limits - chat_list = args_list[:-1] - else: - assert len(args_list) == 2 - chat_list = args_list[0] - # if old chat file with single chatbot, get into shape - if isinstance(chat_list, list) and len(chat_list) > 0 and isinstance(chat_list[0], list) and len( - chat_list[0]) == 2 and isinstance(chat_list[0][0], str) and isinstance(chat_list[0][1], str): - chat_list = [chat_list] - # remove None histories - chat_list_not_none = [x for x in chat_list if x and len(x) > 0 and len(x[0]) == 2 and x[0][1] is not None] - chat_list_none = [x for x in chat_list if x not in chat_list_not_none] - if len(chat_list_none) > 0 and len(chat_list_not_none) == 0: - raise ValueError("Invalid chat file") - # dict with keys of short chat names, values of list of list of chatbot histories - chat_state1 = args_list[-1] - short_chats = list(chat_state1.keys()) - if len(chat_list_not_none) > 0: - # make short_chat key from only first history, based upon question that is same anyways - chat_first = chat_list_not_none[0] - short_chat = get_short_chat(chat_first, short_chats) - if short_chat: - old_chat_lists = list(chat_state1.values()) - already_exists = any([is_chat_same(chat_list, x) for x in old_chat_lists]) - if not already_exists: - chat_state1[short_chat] = chat_list.copy() - - # reverse so newest at top - choices = list(chat_state1.keys()).copy() - choices.reverse() - - return chat_state1, gr.update(choices=choices, value=None) - - def switch_chat(chat_key, chat_state1, num_model_lock=0): - chosen_chat = chat_state1[chat_key] - # deal with possible different size of chat list vs. current list - ret_chat = [None] * (2 + num_model_lock) - for chati in range(0, 2 + num_model_lock): - ret_chat[chati % len(ret_chat)] = chosen_chat[chati % len(chosen_chat)] - return tuple(ret_chat) - - def clear_texts(*args): - return tuple([gr.Textbox.update(value='')] * len(args)) - - def clear_scores(): - return gr.Textbox.update(value=res_value), \ - gr.Textbox.update(value='Response Score: NA'), \ - gr.Textbox.update(value='Response Score: NA') - - switch_chat_fun = functools.partial(switch_chat, num_model_lock=len(text_outputs)) - radio_chats.input(switch_chat_fun, - inputs=[radio_chats, chat_state], - outputs=[text_output, text_output2] + text_outputs) \ - .then(clear_scores, outputs=[score_text, score_text2, score_text_nochat]) - - def remove_chat(chat_key, chat_state1): - if isinstance(chat_key, str): - chat_state1.pop(chat_key, None) - return gr.update(choices=list(chat_state1.keys()), value=None), chat_state1 - - remove_chat_event = remove_chat_btn.click(remove_chat, - inputs=[radio_chats, chat_state], outputs=[radio_chats, chat_state], - queue=False, api_name='remove_chat') - - def get_chats1(chat_state1): - base = 'chats' - makedirs(base, exist_ok=True) - filename = os.path.join(base, 'chats_%s.json' % str(uuid.uuid4())) - with open(filename, "wt") as f: - f.write(json.dumps(chat_state1, indent=2)) - return filename - - export_chat_event = export_chats_btn.click(get_chats1, inputs=chat_state, outputs=chats_file, queue=False, - api_name='export_chats' if allow_api else None) - - def add_chats_from_file(file, chat_state1, radio_chats1, chat_exception_text1): - if not file: - return None, chat_state1, gr.update(choices=list(chat_state1.keys()), value=None), chat_exception_text1 - if isinstance(file, str): - files = [file] - else: - files = file - if not files: - return None, chat_state1, gr.update(choices=list(chat_state1.keys()), value=None), chat_exception_text1 - chat_exception_list = [] - for file1 in files: - try: - if hasattr(file1, 'name'): - file1 = file1.name - with open(file1, "rt") as f: - new_chats = json.loads(f.read()) - for chat1_k, chat1_v in new_chats.items(): - # ignore chat1_k, regenerate and de-dup to avoid loss - chat_state1, _ = save_chat(chat1_v, chat_state1, chat_is_list=True) - except BaseException as e: - t, v, tb = sys.exc_info() - ex = ''.join(traceback.format_exception(t, v, tb)) - ex_str = "File %s exception: %s" % (file1, str(e)) - print(ex_str, flush=True) - chat_exception_list.append(ex_str) - chat_exception_text1 = '\n'.join(chat_exception_list) - return None, chat_state1, gr.update(choices=list(chat_state1.keys()), value=None), chat_exception_text1 - - # note for update_user_db_func output is ignored for db - chatup_change_event = chatsup_output.change(add_chats_from_file, - inputs=[chatsup_output, chat_state, radio_chats, - chat_exception_text], - outputs=[chatsup_output, chat_state, radio_chats, - chat_exception_text], - queue=False, - api_name='add_to_chats' if allow_api else None) - - clear_chat_event = clear_chat_btn.click(fn=clear_texts, - inputs=[text_output, text_output2] + text_outputs, - outputs=[text_output, text_output2] + text_outputs, - queue=False, api_name='clear' if allow_api else None) \ - .then(deselect_radio_chats, inputs=None, outputs=radio_chats, queue=False) \ - .then(clear_scores, outputs=[score_text, score_text2, score_text_nochat]) - - clear_event = save_chat_btn.click(save_chat, - inputs=[text_output, text_output2] + text_outputs + [chat_state], - outputs=[chat_state, radio_chats], - api_name='save_chat' if allow_api else None) - if kwargs['score_model']: - clear_event2 = clear_event.then(clear_scores, outputs=[score_text, score_text2, score_text_nochat]) - - # NOTE: clear of instruction/iinput for nochat has to come after score, - # because score for nochat consumes actual textbox, while chat consumes chat history filled by user() - no_chat_args = dict(fn=fun, - inputs=[model_state, my_db_state, selection_docs_state] + inputs_list, - outputs=text_output_nochat, - queue=queue, - ) - submit_event_nochat = submit_nochat.click(**no_chat_args, api_name='submit_nochat' if allow_api else None) \ - .then(clear_torch_cache) \ - .then(**score_args_nochat, api_name='instruction_bot_score_nochat' if allow_api else None, queue=queue) \ - .then(clear_instruct, None, instruction_nochat) \ - .then(clear_instruct, None, iinput_nochat) \ - .then(clear_torch_cache) - # copy of above with text box submission - submit_event_nochat2 = instruction_nochat.submit(**no_chat_args) \ - .then(clear_torch_cache) \ - .then(**score_args_nochat, queue=queue) \ - .then(clear_instruct, None, instruction_nochat) \ - .then(clear_instruct, None, iinput_nochat) \ - .then(clear_torch_cache) - - submit_event_nochat_api = submit_nochat_api.click(fun_with_dict_str, - inputs=[model_state, my_db_state, selection_docs_state, - inputs_dict_str], - outputs=text_output_nochat_api, - queue=True, # required for generator - api_name='submit_nochat_api' if allow_api else None) \ - .then(clear_torch_cache) - - def load_model(model_name, lora_weights, server_name, model_state_old, prompt_type_old, load_8bit, - use_gpu_id, gpu_id): - # ensure no API calls reach here - if is_public: - raise RuntimeError("Illegal access for %s" % model_name) - # ensure old model removed from GPU memory - if kwargs['debug']: - print("Pre-switch pre-del GPU memory: %s" % get_torch_allocated(), flush=True) - - model0 = model_state0['model'] - if isinstance(model_state_old['model'], str) and model0 is not None: - # best can do, move model loaded at first to CPU - model0.cpu() - - if model_state_old['model'] is not None and not isinstance(model_state_old['model'], str): - try: - model_state_old['model'].cpu() - except Exception as e: - # sometimes hit NotImplementedError: Cannot copy out of meta tensor; no data! - print("Unable to put model on CPU: %s" % str(e), flush=True) - del model_state_old['model'] - model_state_old['model'] = None - - if model_state_old['tokenizer'] is not None and not isinstance(model_state_old['tokenizer'], str): - del model_state_old['tokenizer'] - model_state_old['tokenizer'] = None - - clear_torch_cache() - if kwargs['debug']: - print("Pre-switch post-del GPU memory: %s" % get_torch_allocated(), flush=True) - - if model_name is None or model_name == no_model_str: - # no-op if no model, just free memory - # no detranscribe needed for model, never go into evaluate - lora_weights = no_lora_str - server_name = no_server_str - return [None, None, None, model_name, server_name], \ - model_name, lora_weights, server_name, prompt_type_old, \ - gr.Slider.update(maximum=256), \ - gr.Slider.update(maximum=256) - - # don't deepcopy, can contain model itself - all_kwargs1 = all_kwargs.copy() - all_kwargs1['base_model'] = model_name.strip() - all_kwargs1['load_8bit'] = load_8bit - all_kwargs1['use_gpu_id'] = use_gpu_id - all_kwargs1['gpu_id'] = int(gpu_id) # detranscribe - model_lower = model_name.strip().lower() - if model_lower in inv_prompt_type_to_model_lower: - prompt_type1 = inv_prompt_type_to_model_lower[model_lower] - else: - prompt_type1 = prompt_type_old - - # detranscribe - if lora_weights == no_lora_str: - lora_weights = '' - all_kwargs1['lora_weights'] = lora_weights.strip() - if server_name == no_server_str: - server_name = '' - all_kwargs1['inference_server'] = server_name.strip() - - model1, tokenizer1, device1 = get_model(reward_type=False, - **get_kwargs(get_model, exclude_names=['reward_type'], - **all_kwargs1)) - clear_torch_cache() - - tokenizer_base_model = model_name - prompt_dict1, error0 = get_prompt(prompt_type1, '', - chat=False, context='', reduced=False, making_context=False, - return_dict=True) - model_state_new = dict(model=model1, tokenizer=tokenizer1, device=device1, - base_model=model_name, tokenizer_base_model=tokenizer_base_model, - lora_weights=lora_weights, inference_server=server_name, - prompt_type=prompt_type1, prompt_dict=prompt_dict1, - ) - - max_max_new_tokens1 = get_max_max_new_tokens(model_state_new, **kwargs) - - if kwargs['debug']: - print("Post-switch GPU memory: %s" % get_torch_allocated(), flush=True) - return model_state_new, model_name, lora_weights, server_name, prompt_type1, \ - gr.Slider.update(maximum=max_max_new_tokens1), \ - gr.Slider.update(maximum=max_max_new_tokens1) - - def get_prompt_str(prompt_type1, prompt_dict1, which=0): - if prompt_type1 in ['', None]: - print("Got prompt_type %s: %s" % (which, prompt_type1), flush=True) - return str({}) - prompt_dict1, prompt_dict_error = get_prompt(prompt_type1, prompt_dict1, chat=False, context='', - reduced=False, making_context=False, return_dict=True) - if prompt_dict_error: - return str(prompt_dict_error) - else: - # return so user can manipulate if want and use as custom - return str(prompt_dict1) - - get_prompt_str_func1 = functools.partial(get_prompt_str, which=1) - get_prompt_str_func2 = functools.partial(get_prompt_str, which=2) - prompt_type.change(fn=get_prompt_str_func1, inputs=[prompt_type, prompt_dict], outputs=prompt_dict, queue=False) - prompt_type2.change(fn=get_prompt_str_func2, inputs=[prompt_type2, prompt_dict2], outputs=prompt_dict2, - queue=False) - - def dropdown_prompt_type_list(x): - return gr.Dropdown.update(value=x) - - def chatbot_list(x, model_used_in): - return gr.Textbox.update(label=f'h2oGPT [Model: {model_used_in}]') - - load_model_args = dict(fn=load_model, - inputs=[model_choice, lora_choice, server_choice, model_state, prompt_type, - model_load8bit_checkbox, model_use_gpu_id_checkbox, model_gpu], - outputs=[model_state, model_used, lora_used, server_used, - # if prompt_type changes, prompt_dict will change via change rule - prompt_type, max_new_tokens, min_new_tokens, - ]) - prompt_update_args = dict(fn=dropdown_prompt_type_list, inputs=prompt_type, outputs=prompt_type) - chatbot_update_args = dict(fn=chatbot_list, inputs=[text_output, model_used], outputs=text_output) - nochat_update_args = dict(fn=chatbot_list, inputs=[text_output_nochat, model_used], outputs=text_output_nochat) - load_model_event = load_model_button.click(**load_model_args, - api_name='load_model' if allow_api and is_public else None) \ - .then(**prompt_update_args) \ - .then(**chatbot_update_args) \ - .then(**nochat_update_args) \ - .then(clear_torch_cache) - - load_model_args2 = dict(fn=load_model, - inputs=[model_choice2, lora_choice2, server_choice2, model_state2, prompt_type2, - model_load8bit_checkbox2, model_use_gpu_id_checkbox2, model_gpu2], - outputs=[model_state2, model_used2, lora_used2, server_used2, - # if prompt_type2 changes, prompt_dict2 will change via change rule - prompt_type2, max_new_tokens2, min_new_tokens2 - ]) - prompt_update_args2 = dict(fn=dropdown_prompt_type_list, inputs=prompt_type2, outputs=prompt_type2) - chatbot_update_args2 = dict(fn=chatbot_list, inputs=[text_output2, model_used2], outputs=text_output2) - load_model_event2 = load_model_button2.click(**load_model_args2, - api_name='load_model2' if allow_api and is_public else None) \ - .then(**prompt_update_args2) \ - .then(**chatbot_update_args2) \ - .then(clear_torch_cache) - - def dropdown_model_lora_server_list(model_list0, model_x, - lora_list0, lora_x, - server_list0, server_x, - model_used1, lora_used1, server_used1, - model_used2, lora_used2, server_used2, - ): - model_new_state = [model_list0[0] + [model_x]] - model_new_options = [*model_new_state[0]] - x1 = model_x if model_used1 == no_model_str else model_used1 - x2 = model_x if model_used2 == no_model_str else model_used2 - ret1 = [gr.Dropdown.update(value=x1, choices=model_new_options), - gr.Dropdown.update(value=x2, choices=model_new_options), - '', model_new_state] - - lora_new_state = [lora_list0[0] + [lora_x]] - lora_new_options = [*lora_new_state[0]] - # don't switch drop-down to added lora if already have model loaded - x1 = lora_x if model_used1 == no_model_str else lora_used1 - x2 = lora_x if model_used2 == no_model_str else lora_used2 - ret2 = [gr.Dropdown.update(value=x1, choices=lora_new_options), - gr.Dropdown.update(value=x2, choices=lora_new_options), - '', lora_new_state] - - server_new_state = [server_list0[0] + [server_x]] - server_new_options = [*server_new_state[0]] - # don't switch drop-down to added server if already have model loaded - x1 = server_x if model_used1 == no_model_str else server_used1 - x2 = server_x if model_used2 == no_model_str else server_used2 - ret3 = [gr.Dropdown.update(value=x1, choices=server_new_options), - gr.Dropdown.update(value=x2, choices=server_new_options), - '', server_new_state] - - return tuple(ret1 + ret2 + ret3) - - add_model_lora_server_event = \ - add_model_lora_server_button.click(fn=dropdown_model_lora_server_list, - inputs=[model_options_state, new_model] + - [lora_options_state, new_lora] + - [server_options_state, new_server] + - [model_used, lora_used, server_used] + - [model_used2, lora_used2, server_used2], - outputs=[model_choice, model_choice2, new_model, model_options_state] + - [lora_choice, lora_choice2, new_lora, lora_options_state] + - [server_choice, server_choice2, new_server, - server_options_state], - queue=False) - - go_event = go_btn.click(lambda: gr.update(visible=False), None, go_btn, api_name="go" if allow_api else None, - queue=False) \ - .then(lambda: gr.update(visible=True), None, normal_block, queue=False) \ - .then(**load_model_args, queue=False).then(**prompt_update_args, queue=False) - - def compare_textbox_fun(x): - return gr.Textbox.update(visible=x) - - def compare_column_fun(x): - return gr.Column.update(visible=x) - - def compare_prompt_fun(x): - return gr.Dropdown.update(visible=x) - - def slider_fun(x): - return gr.Slider.update(visible=x) - - compare_checkbox.select(compare_textbox_fun, compare_checkbox, text_output2, - api_name="compare_checkbox" if allow_api else None) \ - .then(compare_column_fun, compare_checkbox, col_model2) \ - .then(compare_prompt_fun, compare_checkbox, prompt_type2) \ - .then(compare_textbox_fun, compare_checkbox, score_text2) \ - .then(slider_fun, compare_checkbox, max_new_tokens2) \ - .then(slider_fun, compare_checkbox, min_new_tokens2) - # FIXME: add score_res2 in condition, but do better - - # callback for logging flagged input/output - callback.setup(inputs_list + [text_output, text_output2] + text_outputs, "flagged_data_points") - flag_btn.click(lambda *args: callback.flag(args), inputs_list + [text_output, text_output2] + text_outputs, - None, - preprocess=False, - api_name='flag' if allow_api else None, queue=False) - flag_btn_nochat.click(lambda *args: callback.flag(args), inputs_list + [text_output_nochat], None, - preprocess=False, - api_name='flag_nochat' if allow_api else None, queue=False) - - def get_system_info(): - if is_public: - time.sleep(10) # delay to avoid spam since queue=False - return gr.Textbox.update(value=system_info_print()) - - system_event = system_btn.click(get_system_info, outputs=system_text, - api_name='system_info' if allow_api else None, queue=False) - - def get_system_info_dict(system_input1, **kwargs1): - if system_input1 != os.getenv("ADMIN_PASS", ""): - return json.dumps({}) - exclude_list = ['admin_pass', 'examples'] - sys_dict = {k: v for k, v in kwargs1.items() if - isinstance(v, (str, int, bool, float)) and k not in exclude_list} - try: - sys_dict.update(system_info()) - except Exception as e: - # protection - print("Exception: %s" % str(e), flush=True) - return json.dumps(sys_dict) - - system_kwargs = all_kwargs.copy() - system_kwargs.update(dict(command=str(' '.join(sys.argv)))) - get_system_info_dict_func = functools.partial(get_system_info_dict, **all_kwargs) - - system_dict_event = system_btn2.click(get_system_info_dict_func, - inputs=system_input, - outputs=system_text2, - api_name='system_info_dict' if allow_api else None, - queue=False, # queue to avoid spam - ) - - def get_hash(): - return kwargs['git_hash'] - - system_event = system_btn3.click(get_hash, - outputs=system_text3, - api_name='system_hash' if allow_api else None, - queue=False, - ) - - def count_chat_tokens(model_state1, chat1, prompt_type1, prompt_dict1, - memory_restriction_level1=0, - keep_sources_in_context1=False, - ): - if model_state1 and not isinstance(model_state1['tokenizer'], str): - tokenizer = model_state1['tokenizer'] - elif model_state0 and not isinstance(model_state0['tokenizer'], str): - tokenizer = model_state0['tokenizer'] - else: - tokenizer = None - if tokenizer is not None: - langchain_mode1 = 'LLM' - add_chat_history_to_context1 = True - # fake user message to mimic bot() - chat1 = copy.deepcopy(chat1) - chat1 = chat1 + [['user_message1', None]] - model_max_length1 = tokenizer.model_max_length - context1 = history_to_context(chat1, langchain_mode1, - add_chat_history_to_context1, - prompt_type1, prompt_dict1, chat1, - model_max_length1, - memory_restriction_level1, keep_sources_in_context1) - return str(tokenizer(context1, return_tensors="pt")['input_ids'].shape[1]) - else: - return "N/A" - - count_chat_tokens_func = functools.partial(count_chat_tokens, - memory_restriction_level1=memory_restriction_level, - keep_sources_in_context1=kwargs['keep_sources_in_context']) - count_tokens_event = count_chat_tokens_btn.click(fn=count_chat_tokens, - inputs=[model_state, text_output, prompt_type, prompt_dict], - outputs=chat_token_count, - api_name='count_tokens' if allow_api else None) - - # don't pass text_output, don't want to clear output, just stop it - # cancel only stops outer generation, not inner generation or non-generation - stop_btn.click(lambda: None, None, None, - cancels=submits1 + submits2 + submits3 + submits4 + - [submit_event_nochat, submit_event_nochat2] + - [eventdb1, eventdb2, eventdb3] + - [eventdb7, eventdb8, eventdb9, eventdb12] + - db_events + - [clear_event] + - [submit_event_nochat_api, submit_event_nochat] + - [load_model_event, load_model_event2] + - [count_tokens_event] - , - queue=False, api_name='stop' if allow_api else None).then(clear_torch_cache, queue=False) - - demo.load(None, None, None, _js=get_dark_js() if kwargs['dark'] else None) - - demo.queue(concurrency_count=kwargs['concurrency_count'], api_open=kwargs['api_open']) - favicon_path = "h2o-logo.svg" - if not os.path.isfile(favicon_path): - print("favicon_path=%s not found" % favicon_path, flush=True) - favicon_path = None - - scheduler = BackgroundScheduler() - scheduler.add_job(func=clear_torch_cache, trigger="interval", seconds=20) - if is_public and \ - kwargs['base_model'] not in non_hf_types: - # FIXME: disable for gptj, langchain or gpt4all modify print itself - # FIXME: and any multi-threaded/async print will enter model output! - scheduler.add_job(func=ping, trigger="interval", seconds=60) - if is_public or os.getenv('PING_GPU'): - scheduler.add_job(func=ping_gpu, trigger="interval", seconds=60 * 10) - scheduler.start() - - # import control - if kwargs['langchain_mode'] == 'Disabled' and \ - os.environ.get("TEST_LANGCHAIN_IMPORT") and \ - kwargs['base_model'] not in non_hf_types: - assert 'gpt_langchain' not in sys.modules, "Dev bug, import of langchain when should not have" - assert 'langchain' not in sys.modules, "Dev bug, import of langchain when should not have" - - demo.launch(share=kwargs['share'], server_name="0.0.0.0", show_error=True, - favicon_path=favicon_path, prevent_thread_lock=True, - auth=kwargs['auth']) - if kwargs['verbose']: - print("Started GUI", flush=True) - if kwargs['block_gradio_exit']: - demo.block_thread() - - -def get_inputs_list(inputs_dict, model_lower, model_id=1): - """ - map gradio objects in locals() to inputs for evaluate(). - :param inputs_dict: - :param model_lower: - :param model_id: Which model (1 or 2) of 2 - :return: - """ - inputs_list_names = list(inspect.signature(evaluate).parameters) - inputs_list = [] - inputs_dict_out = {} - for k in inputs_list_names: - if k == 'kwargs': - continue - if k in input_args_list + inputs_kwargs_list: - # these are added at use time for args or partial for kwargs, not taken as input - continue - if 'mbart-' not in model_lower and k in ['src_lang', 'tgt_lang']: - continue - if model_id == 2: - if k == 'prompt_type': - k = 'prompt_type2' - if k == 'prompt_used': - k = 'prompt_used2' - if k == 'max_new_tokens': - k = 'max_new_tokens2' - if k == 'min_new_tokens': - k = 'min_new_tokens2' - inputs_list.append(inputs_dict[k]) - inputs_dict_out[k] = inputs_dict[k] - return inputs_list, inputs_dict_out - - -def get_sources(db1s, langchain_mode, dbs=None, docs_state0=None): - for k in db1s: - set_userid(db1s[k]) - - if langchain_mode in ['LLM']: - source_files_added = "NA" - source_list = [] - elif langchain_mode in ['wiki_full']: - source_files_added = "Not showing wiki_full, takes about 20 seconds and makes 4MB file." \ - " Ask jon.mckinney@h2o.ai for file if required." - source_list = [] - elif langchain_mode in db1s and len(db1s[langchain_mode]) == 2 and db1s[langchain_mode][0] is not None: - db1 = db1s[langchain_mode] - from gpt_langchain import get_metadatas - metadatas = get_metadatas(db1[0]) - source_list = sorted(set([x['source'] for x in metadatas])) - source_files_added = '\n'.join(source_list) - elif langchain_mode in dbs and dbs[langchain_mode] is not None: - from gpt_langchain import get_metadatas - db1 = dbs[langchain_mode] - metadatas = get_metadatas(db1) - source_list = sorted(set([x['source'] for x in metadatas])) - source_files_added = '\n'.join(source_list) - else: - source_list = [] - source_files_added = "None" - sources_dir = "sources_dir" - makedirs(sources_dir) - sources_file = os.path.join(sources_dir, 'sources_%s_%s' % (langchain_mode, str(uuid.uuid4()))) - with open(sources_file, "wt") as f: - f.write(source_files_added) - source_list = docs_state0 + source_list - return sources_file, source_list - - -def set_userid(db1): - # can only call this after function called so for specific userr, not in gr.State() that occurs during app init - assert db1 is not None and len(db1) == 2 - if db1[1] is None: - # uuid in db is used as user ID - db1[1] = str(uuid.uuid4()) - - -def update_user_db(file, db1s, selection_docs_state1, chunk, chunk_size, langchain_mode, dbs=None, **kwargs): - kwargs.update(selection_docs_state1) - if file is None: - raise RuntimeError("Don't use change, use input") - - try: - return _update_user_db(file, db1s=db1s, chunk=chunk, chunk_size=chunk_size, - langchain_mode=langchain_mode, dbs=dbs, - **kwargs) - except BaseException as e: - print(traceback.format_exc(), flush=True) - # gradio has issues if except, so fail semi-gracefully, else would hang forever in processing textbox - ex_str = "Exception: %s" % str(e) - source_files_added = """\ - - -
- Sources:
-
- {0}
-
- {0}
-
- Exceptions:
-
-