gjohnsdss commited on
Commit
4071f4f
1 Parent(s): 3d3f0cd

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .chroma/index/id_to_uuid_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.pkl +3 -0
  2. .chroma/index/id_to_uuid_d84a1a1c-1894-449b-a69d-dade67e4200a.pkl +3 -0
  3. .chroma/index/index_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.bin +3 -0
  4. .chroma/index/index_d84a1a1c-1894-449b-a69d-dade67e4200a.bin +3 -0
  5. .chroma/index/index_metadata_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.pkl +3 -0
  6. .chroma/index/index_metadata_d84a1a1c-1894-449b-a69d-dade67e4200a.pkl +3 -0
  7. .chroma/index/uuid_to_id_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.pkl +3 -0
  8. .chroma/index/uuid_to_id_d84a1a1c-1894-449b-a69d-dade67e4200a.pkl +3 -0
  9. .ipynb_checkpoints/DSS_proto-checkpoint.ipynb +384 -0
  10. .ipynb_checkpoints/Untitled-checkpoint.ipynb +6 -0
  11. .ipynb_checkpoints/Untitled1-checkpoint.ipynb +6 -0
  12. .ipynb_checkpoints/demo_app-checkpoint.py +250 -0
  13. .ipynb_checkpoints/llama2_gradio_v0.3-checkpoint.ipynb +429 -0
  14. .ipynb_checkpoints/llama2_gradio_v0.4-checkpoint.ipynb +0 -0
  15. .ipynb_checkpoints/llama2_gradio_v0.4_backup-checkpoint.ipynb +0 -0
  16. .ipynb_checkpoints/llama2_gradio_v0.4_s3-checkpoint.ipynb +0 -0
  17. .ipynb_checkpoints/main-checkpoint.py +157 -0
  18. .virtual_documents/llama2_gradio_v0.4.ipynb +241 -0
  19. .virtual_documents/llama2_gradio_v0.4_s3.ipynb +241 -0
  20. DSS_proto.ipynb +350 -0
  21. Mission.pdf +0 -0
  22. README.md +2 -8
  23. Untitled.ipynb +107 -0
  24. Untitled1.ipynb +109 -0
  25. demo_app.py +250 -0
  26. llama2_gradio_v0.3.ipynb +386 -0
  27. llama2_gradio_v0.4.ipynb +0 -0
  28. llama2_gradio_v0.4_backup.ipynb +0 -0
  29. llama2_gradio_v0.4_s3.ipynb +347 -0
  30. main.py +157 -0
  31. spikeball.pdf +0 -0
  32. text-generation-webui/.github/FUNDING.yml +1 -0
  33. text-generation-webui/.github/ISSUE_TEMPLATE/bug_report_template.yml +53 -0
  34. text-generation-webui/.github/ISSUE_TEMPLATE/feature_request.md +16 -0
  35. text-generation-webui/.github/dependabot.yml +11 -0
  36. text-generation-webui/.github/workflows/stale.yml +22 -0
  37. text-generation-webui/.gitignore +35 -0
  38. text-generation-webui/LICENSE +661 -0
  39. text-generation-webui/README.md +362 -0
  40. text-generation-webui/api-examples/api-example-chat-stream.py +101 -0
  41. text-generation-webui/api-examples/api-example-chat.py +81 -0
  42. text-generation-webui/api-examples/api-example-model.py +176 -0
  43. text-generation-webui/api-examples/api-example-stream.py +80 -0
  44. text-generation-webui/api-examples/api-example.py +57 -0
  45. text-generation-webui/characters/Example.png +0 -0
  46. text-generation-webui/characters/Example.yaml +16 -0
  47. text-generation-webui/characters/instruction-following/Airoboros-v1.2.yaml +4 -0
  48. text-generation-webui/characters/instruction-following/Alpaca.yaml +4 -0
  49. text-generation-webui/characters/instruction-following/Bactrian.yaml +4 -0
  50. text-generation-webui/characters/instruction-following/Baize.yaml +4 -0
.chroma/index/id_to_uuid_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbf060a1a4c5b9e3495826626a3c703e9fc5937c2b1bb0aedf5ea0d5cb3a4702
3
+ size 1512
.chroma/index/id_to_uuid_d84a1a1c-1894-449b-a69d-dade67e4200a.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01e16e8dfa45adc310f8741b122289f9e84d16ef7809a5db6207f96317c5d46f
3
+ size 1610
.chroma/index/index_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:404ad5247b0ec684bead70fc2fac5b340950b3fb5a93b333b07b01fb9d5458e5
3
+ size 151520
.chroma/index/index_d84a1a1c-1894-449b-a69d-dade67e4200a.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1940be13912cbce474dee04ecf5fff9c6151ebea2c154db9797a6e8dcbd9dd22
3
+ size 161168
.chroma/index/index_metadata_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01d55c4492521f1fb0050ce2f1e224bd888fed5653202991f7b2e3173ecb9634
3
+ size 103
.chroma/index/index_metadata_d84a1a1c-1894-449b-a69d-dade67e4200a.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a7b0a042ca2d31faa68396f3c75f1a77d59b8ea0de428fbb5d22e9baf52c993
3
+ size 103
.chroma/index/uuid_to_id_90efa5f8-e52a-44c9-8a81-72ff253cd2ec.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51360f72ef2f84b5fa10383c43249227b2a93cc50ec342f20bc901deaee19b43
3
+ size 1755
.chroma/index/uuid_to_id_d84a1a1c-1894-449b-a69d-dade67e4200a.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87df2f713998dd22f81eb45922a29bf14f01c4857b673c7060396b8632935107
3
+ size 1866
.ipynb_checkpoints/DSS_proto-checkpoint.ipynb ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "fb4f9384-be8e-488a-aa51-b56b27c71213",
6
+ "metadata": {
7
+ "tags": []
8
+ },
9
+ "source": [
10
+ "## 1. Set up Sagemaker\n",
11
+ "*Explain more later...*"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "id": "ea107aa6-376e-4364-bceb-50aca9f30b74",
18
+ "metadata": {},
19
+ "outputs": [],
20
+ "source": [
21
+ "response = client.create_presigned_notebook_instance_url(\n",
22
+ " NotebookInstanceName='string',\n",
23
+ " SessionExpirationDurationInSeconds=123\n",
24
+ ")"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "execution_count": 3,
30
+ "id": "ac706b50-8413-42ef-b5a7-5906f7f5cdf5",
31
+ "metadata": {
32
+ "tags": []
33
+ },
34
+ "outputs": [
35
+ {
36
+ "name": "stdout",
37
+ "output_type": "stream",
38
+ "text": [
39
+ "arn:aws:iam::907929678403:role/service-role/AmazonSageMaker-ExecutionRole-20230621T132010\n"
40
+ ]
41
+ }
42
+ ],
43
+ "source": [
44
+ "import json\n",
45
+ "import sagemaker\n",
46
+ "from sagemaker.huggingface import get_huggingface_llm_image_uri\n",
47
+ "from sagemaker.huggingface import HuggingFaceModel\n",
48
+ "\n",
49
+ "# retrieve the llm image uri\n",
50
+ "llm_image = get_huggingface_llm_image_uri(\n",
51
+ " \"huggingface\",\n",
52
+ " version=\"0.8.2\"\n",
53
+ ")\n",
54
+ "\n",
55
+ "# Define Model and Endpoint configuration parameter\n",
56
+ "role = sagemaker.get_execution_role()\n",
57
+ "print(role)\n",
58
+ "endpoint_name = \"falcon-40b-instruct-demo2\"\n",
59
+ "aws_region = \"us-east-1\"\n",
60
+ "hf_model_id = \"tiiuae/falcon-40b-instruct\" # model id from huggingface.co/models\n",
61
+ "instance_type = \"ml.g5.12xlarge\" # instance type to use for deployment\n",
62
+ "number_of_gpu = 4 # number of gpus to use for inference and tensor parallelism\n",
63
+ "health_check_timeout = 600 # Increase the timeout for the health check to 5 minutes for downloading the model\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "execution_count": 4,
69
+ "id": "2ce504d1-0bc3-43ce-bb39-b925a59718cc",
70
+ "metadata": {
71
+ "tags": []
72
+ },
73
+ "outputs": [],
74
+ "source": [
75
+ "# create HuggingFaceModel with the image uri\n",
76
+ "llm_model = HuggingFaceModel(\n",
77
+ " role=role,\n",
78
+ " image_uri=llm_image,\n",
79
+ " env={\n",
80
+ " 'HF_MODEL_ID': hf_model_id,\n",
81
+ " # 'HF_MODEL_QUANTIZE': \"bitsandbytes\", # comment in to quantize\n",
82
+ " 'SM_NUM_GPUS': json.dumps(number_of_gpu),\n",
83
+ " 'MAX_INPUT_LENGTH': json.dumps(1024), # Max length of input text\n",
84
+ " 'MAX_TOTAL_TOKENS': json.dumps(2048), # Max length of the generation (including input text)\n",
85
+ " }\n",
86
+ ")"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": 5,
92
+ "id": "00664be7-3d08-4c68-9048-ba1e602c44c2",
93
+ "metadata": {
94
+ "tags": []
95
+ },
96
+ "outputs": [
97
+ {
98
+ "ename": "ClientError",
99
+ "evalue": "An error occurred (ValidationException) when calling the CreateEndpoint operation: Cannot create already existing endpoint \"arn:aws:sagemaker:us-east-1:907929678403:endpoint/falcon-40b-instruct-demo\".",
100
+ "output_type": "error",
101
+ "traceback": [
102
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
103
+ "\u001b[0;31mClientError\u001b[0m Traceback (most recent call last)",
104
+ "Cell \u001b[0;32mIn[5], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m llm2 \u001b[38;5;241m=\u001b[39m \u001b[43mllm_model\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdeploy\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2\u001b[0m \u001b[43m \u001b[49m\u001b[43minitial_instance_count\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3\u001b[0m \u001b[43m \u001b[49m\u001b[43minstance_type\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minstance_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mhealth_check_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m)\u001b[49m\n",
105
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/huggingface/model.py:311\u001b[0m, in \u001b[0;36mHuggingFaceModel.deploy\u001b[0;34m(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, async_inference_config, serverless_inference_config, volume_size, model_data_download_timeout, container_startup_health_check_timeout, inference_recommendation_id, explainer_config, **kwargs)\u001b[0m\n\u001b[1;32m 305\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mimage_uri \u001b[38;5;129;01mand\u001b[39;00m instance_type \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m instance_type\u001b[38;5;241m.\u001b[39mstartswith(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mml.inf\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[1;32m 306\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mimage_uri \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mserving_image_uri(\n\u001b[1;32m 307\u001b[0m region_name\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session\u001b[38;5;241m.\u001b[39mboto_session\u001b[38;5;241m.\u001b[39mregion_name,\n\u001b[1;32m 308\u001b[0m instance_type\u001b[38;5;241m=\u001b[39minstance_type,\n\u001b[1;32m 309\u001b[0m )\n\u001b[0;32m--> 311\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mHuggingFaceModel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdeploy\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 312\u001b[0m \u001b[43m \u001b[49m\u001b[43minitial_instance_count\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 313\u001b[0m \u001b[43m \u001b[49m\u001b[43minstance_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 314\u001b[0m \u001b[43m \u001b[49m\u001b[43mserializer\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 315\u001b[0m \u001b[43m \u001b[49m\u001b[43mdeserializer\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 316\u001b[0m \u001b[43m \u001b[49m\u001b[43maccelerator_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 317\u001b[0m \u001b[43m \u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 318\u001b[0m \u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 319\u001b[0m \u001b[43m \u001b[49m\u001b[43mkms_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 320\u001b[0m \u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 321\u001b[0m \u001b[43m \u001b[49m\u001b[43mdata_capture_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 322\u001b[0m \u001b[43m \u001b[49m\u001b[43masync_inference_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 323\u001b[0m \u001b[43m \u001b[49m\u001b[43mserverless_inference_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 324\u001b[0m \u001b[43m \u001b[49m\u001b[43mvolume_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mvolume_size\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 325\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel_data_download_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel_data_download_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 326\u001b[0m \u001b[43m \u001b[49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 327\u001b[0m \u001b[43m \u001b[49m\u001b[43minference_recommendation_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minference_recommendation_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 328\u001b[0m \u001b[43m \u001b[49m\u001b[43mexplainer_config\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mexplainer_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 329\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
106
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/model.py:1347\u001b[0m, in \u001b[0;36mModel.deploy\u001b[0;34m(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, async_inference_config, serverless_inference_config, volume_size, model_data_download_timeout, container_startup_health_check_timeout, inference_recommendation_id, explainer_config, **kwargs)\u001b[0m\n\u001b[1;32m 1344\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_explainer_enabled:\n\u001b[1;32m 1345\u001b[0m explainer_config_dict \u001b[38;5;241m=\u001b[39m explainer_config\u001b[38;5;241m.\u001b[39m_to_request_dict()\n\u001b[0;32m-> 1347\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_session\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mendpoint_from_production_variants\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1348\u001b[0m \u001b[43m \u001b[49m\u001b[43mname\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1349\u001b[0m \u001b[43m \u001b[49m\u001b[43mproduction_variants\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m[\u001b[49m\u001b[43mproduction_variant\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1350\u001b[0m \u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1351\u001b[0m \u001b[43m \u001b[49m\u001b[43mkms_key\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mkms_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1352\u001b[0m \u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mwait\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1353\u001b[0m \u001b[43m \u001b[49m\u001b[43mdata_capture_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdata_capture_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1354\u001b[0m \u001b[43m \u001b[49m\u001b[43mexplainer_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mexplainer_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1355\u001b[0m \u001b[43m \u001b[49m\u001b[43masync_inference_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43masync_inference_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1356\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1358\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpredictor_cls:\n\u001b[1;32m 1359\u001b[0m predictor \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpredictor_cls(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mendpoint_name, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session)\n",
107
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/session.py:4641\u001b[0m, in \u001b[0;36mSession.endpoint_from_production_variants\u001b[0;34m(self, name, production_variants, tags, kms_key, wait, data_capture_config_dict, async_inference_config_dict, explainer_config_dict)\u001b[0m\n\u001b[1;32m 4638\u001b[0m LOGGER\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCreating endpoint-config with name \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, name)\n\u001b[1;32m 4639\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_client\u001b[38;5;241m.\u001b[39mcreate_endpoint_config(\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mconfig_options)\n\u001b[0;32m-> 4641\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate_endpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mwait\u001b[49m\u001b[43m)\u001b[49m\n",
108
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/session.py:4030\u001b[0m, in \u001b[0;36mSession.create_endpoint\u001b[0;34m(self, endpoint_name, config_name, tags, wait)\u001b[0m\n\u001b[1;32m 4027\u001b[0m tags \u001b[38;5;241m=\u001b[39m tags \u001b[38;5;129;01mor\u001b[39;00m []\n\u001b[1;32m 4028\u001b[0m tags \u001b[38;5;241m=\u001b[39m _append_project_tags(tags)\n\u001b[0;32m-> 4030\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_client\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate_endpoint\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4031\u001b[0m \u001b[43m \u001b[49m\u001b[43mEndpointName\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mEndpointConfigName\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mconfig_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mTags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\n\u001b[1;32m 4032\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 4033\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m wait:\n\u001b[1;32m 4034\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mwait_for_endpoint(endpoint_name)\n",
109
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:530\u001b[0m, in \u001b[0;36mClientCreator._create_api_method.<locals>._api_call\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 526\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 527\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpy_operation_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m() only accepts keyword arguments.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 528\u001b[0m )\n\u001b[1;32m 529\u001b[0m \u001b[38;5;66;03m# The \"self\" in this scope is referring to the BaseClient.\u001b[39;00m\n\u001b[0;32m--> 530\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_make_api_call\u001b[49m\u001b[43m(\u001b[49m\u001b[43moperation_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
110
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:964\u001b[0m, in \u001b[0;36mBaseClient._make_api_call\u001b[0;34m(self, operation_name, api_params)\u001b[0m\n\u001b[1;32m 962\u001b[0m error_code \u001b[38;5;241m=\u001b[39m parsed_response\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError\u001b[39m\u001b[38;5;124m\"\u001b[39m, {})\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCode\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 963\u001b[0m error_class \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mexceptions\u001b[38;5;241m.\u001b[39mfrom_code(error_code)\n\u001b[0;32m--> 964\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m error_class(parsed_response, operation_name)\n\u001b[1;32m 965\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 966\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m parsed_response\n",
111
+ "\u001b[0;31mClientError\u001b[0m: An error occurred (ValidationException) when calling the CreateEndpoint operation: Cannot create already existing endpoint \"arn:aws:sagemaker:us-east-1:907929678403:endpoint/falcon-40b-instruct-demo\"."
112
+ ]
113
+ }
114
+ ],
115
+ "source": [
116
+ "llm2 = llm_model.deploy(\n",
117
+ " initial_instance_count=1,\n",
118
+ " instance_type=instance_type,\n",
119
+ " container_startup_health_check_timeout=health_check_timeout,\n",
120
+ " endpoint_name=endpoint_name\n",
121
+ ")"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": 9,
127
+ "id": "50f556f8-06b4-450e-9db3-9bc9c979e8ab",
128
+ "metadata": {
129
+ "tags": []
130
+ },
131
+ "outputs": [
132
+ {
133
+ "ename": "ClientError",
134
+ "evalue": "An error occurred (ValidationException) when calling the DeleteEndpointConfig operation: Could not find endpoint configuration \"arn:aws:sagemaker:us-east-1:907929678403:endpoint-config/falcon-40b-instruct-demo\".",
135
+ "output_type": "error",
136
+ "traceback": [
137
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
138
+ "\u001b[0;31mClientError\u001b[0m Traceback (most recent call last)",
139
+ "Cell \u001b[0;32mIn[9], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mllm2\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdelete_endpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
140
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/base_predictor.py:339\u001b[0m, in \u001b[0;36mPredictor.delete_endpoint\u001b[0;34m(self, delete_endpoint_config)\u001b[0m\n\u001b[1;32m 327\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Delete the Amazon SageMaker endpoint backing this predictor.\u001b[39;00m\n\u001b[1;32m 328\u001b[0m \n\u001b[1;32m 329\u001b[0m \u001b[38;5;124;03mThis also delete the endpoint configuration attached to it if\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 336\u001b[0m \u001b[38;5;124;03m be deleted. If False, only endpoint will be deleted.\u001b[39;00m\n\u001b[1;32m 337\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 338\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m delete_endpoint_config:\n\u001b[0;32m--> 339\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_delete_endpoint_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 341\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session\u001b[38;5;241m.\u001b[39mdelete_endpoint(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mendpoint_name)\n",
141
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/base_predictor.py:324\u001b[0m, in \u001b[0;36mPredictor._delete_endpoint_config\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 322\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Delete the Amazon SageMaker endpoint configuration\"\"\"\u001b[39;00m\n\u001b[1;32m 323\u001b[0m current_endpoint_config_name \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_get_endpoint_config_name()\n\u001b[0;32m--> 324\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_session\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdelete_endpoint_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcurrent_endpoint_config_name\u001b[49m\u001b[43m)\u001b[49m\n",
142
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/session.py:4086\u001b[0m, in \u001b[0;36mSession.delete_endpoint_config\u001b[0;34m(self, endpoint_config_name)\u001b[0m\n\u001b[1;32m 4079\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Delete an Amazon SageMaker endpoint configuration.\u001b[39;00m\n\u001b[1;32m 4080\u001b[0m \n\u001b[1;32m 4081\u001b[0m \u001b[38;5;124;03mArgs:\u001b[39;00m\n\u001b[1;32m 4082\u001b[0m \u001b[38;5;124;03m endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to\u001b[39;00m\n\u001b[1;32m 4083\u001b[0m \u001b[38;5;124;03m delete.\u001b[39;00m\n\u001b[1;32m 4084\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 4085\u001b[0m LOGGER\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mDeleting endpoint configuration with name: \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, endpoint_config_name)\n\u001b[0;32m-> 4086\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_client\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdelete_endpoint_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mEndpointConfigName\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_config_name\u001b[49m\u001b[43m)\u001b[49m\n",
143
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:530\u001b[0m, in \u001b[0;36mClientCreator._create_api_method.<locals>._api_call\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 526\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 527\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpy_operation_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m() only accepts keyword arguments.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 528\u001b[0m )\n\u001b[1;32m 529\u001b[0m \u001b[38;5;66;03m# The \"self\" in this scope is referring to the BaseClient.\u001b[39;00m\n\u001b[0;32m--> 530\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_make_api_call\u001b[49m\u001b[43m(\u001b[49m\u001b[43moperation_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
144
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:964\u001b[0m, in \u001b[0;36mBaseClient._make_api_call\u001b[0;34m(self, operation_name, api_params)\u001b[0m\n\u001b[1;32m 962\u001b[0m error_code \u001b[38;5;241m=\u001b[39m parsed_response\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError\u001b[39m\u001b[38;5;124m\"\u001b[39m, {})\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCode\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 963\u001b[0m error_class \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mexceptions\u001b[38;5;241m.\u001b[39mfrom_code(error_code)\n\u001b[0;32m--> 964\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m error_class(parsed_response, operation_name)\n\u001b[1;32m 965\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 966\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m parsed_response\n",
145
+ "\u001b[0;31mClientError\u001b[0m: An error occurred (ValidationException) when calling the DeleteEndpointConfig operation: Could not find endpoint configuration \"arn:aws:sagemaker:us-east-1:907929678403:endpoint-config/falcon-40b-instruct-demo\"."
146
+ ]
147
+ }
148
+ ],
149
+ "source": [
150
+ "llm2.delete_endpoint()"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": null,
156
+ "id": "c341f368-a9e7-441c-886e-0576c3f2f432",
157
+ "metadata": {
158
+ "tags": []
159
+ },
160
+ "outputs": [],
161
+ "source": [
162
+ "\n",
163
+ "from langchain.chains.question_answering import load_qa_chain\n",
164
+ "from langchain.memory import ConversationBufferMemory\n",
165
+ "from langchain import PromptTemplate\n",
166
+ "from typing import Dict\n",
167
+ "\n",
168
+ "class ContentHandler(LLMContentHandler):\n",
169
+ " content_type = \"application/json\"\n",
170
+ " accepts = \"application/json\"\n",
171
+ " len_prompt = 0\n",
172
+ "\n",
173
+ " def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:\n",
174
+ " self.len_prompt = len(prompt)\n",
175
+ " input_str = json.dumps(\n",
176
+ " {\"inputs\": prompt,\n",
177
+ " \"parameters\": {\n",
178
+ " \"do_sample\": True,\n",
179
+ " \"top_p\": 0.9,\n",
180
+ " \"temperature\": 0.8,\n",
181
+ " \"max_new_tokens\": 1024,\n",
182
+ " \"repetition_penalty\": 1.03,\n",
183
+ " \"stop\": [\"\\n\\n\", \"Human:\", \"<|endoftext|>\", \"</s>\"]\n",
184
+ " }})\n",
185
+ " return input_str.encode('utf-8')\n",
186
+ "\n",
187
+ " def transform_output(self, output: bytes) -> str:\n",
188
+ " response_json = output.read()\n",
189
+ " res = json.loads(response_json)\n",
190
+ " ans = res[0]['generated_text'][self.len_prompt:]\n",
191
+ " ans = ans[:ans.rfind(\"Human\")].strip()\n",
192
+ " return ans\n",
193
+ "\n",
194
+ "\n",
195
+ "content_handler = ContentHandler()\n",
196
+ "\n",
197
+ "\n",
198
+ "prompt = PromptTemplate(\n",
199
+ " input_variables=[\"history\", \"context\", \"new_message\"],\n",
200
+ " template=\"\"\"\n",
201
+ "The following is a given context and history of a conversation between a human and a helpful AI assistant. \n",
202
+ "The AI assistant answers the human's messages with full, informational responses by inferring on the information given in the context, but does not extrapolate or hallucinate any facts that are not given.\n",
203
+ "When answering questions with unclear answers, the AI assistant qualifies its responses as such.\n",
204
+ "The AI assistant pretends it is also human and that the context is objectively true and well-known and therefore avoids mentioning the context as a source.\n",
205
+ "\n",
206
+ "Context: {context}\n",
207
+ "\n",
208
+ "{history}\n",
209
+ "Human: {new_message}\n",
210
+ "AI:\"\"\")\n",
211
+ "\n",
212
+ "def load_chain():\n",
213
+ " llm = SagemakerEndpoint(\n",
214
+ " endpoint_name=endpoint_name,\n",
215
+ " region_name=aws_region,\n",
216
+ " content_handler=content_handler\n",
217
+ " )\n",
218
+ " chain = load_qa_chain(llm=llm, chain_type=\"stuff\", verbose=True, memory=ConversationBufferMemory(memory_key=\"history\", input_key=\"new_message\"), prompt=prompt)\n",
219
+ " return chain\n",
220
+ "\n",
221
+ "\n",
222
+ "dachain = load_chain()"
223
+ ]
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "execution_count": null,
228
+ "id": "b0a557a0-ca6d-45db-97b4-f89317a5e500",
229
+ "metadata": {
230
+ "tags": []
231
+ },
232
+ "outputs": [],
233
+ "source": [
234
+ "query = \"What is Becton?\"\n",
235
+ "dachain({\"input_documents\": docsearch.similarity_search(query, k=3), \"new_message\": query}, return_only_outputs=True)['output_text'].strip()"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "markdown",
240
+ "id": "c4ac2fca-820b-412d-9e90-47848e046236",
241
+ "metadata": {},
242
+ "source": [
243
+ "## Load DSS Website Data into ChromaDB\n",
244
+ "`urls` object defines what URLs are to be considered in the context database."
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": null,
250
+ "id": "c596a7a6-cca1-46c5-a914-e8b5ce9eba17",
251
+ "metadata": {
252
+ "tags": []
253
+ },
254
+ "outputs": [],
255
+ "source": [
256
+ "from langchain.document_loaders import UnstructuredURLLoader\n",
257
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
258
+ "from langchain.vectorstores import Chroma\n",
259
+ "from langchain.embeddings import HuggingFaceInstructEmbeddings\n",
260
+ "\n",
261
+ "# define URL sources\n",
262
+ "urls = [\n",
263
+ " 'https://www.dssinc.com/blog/2022/6/21/suicide-prevention-manager-enabling-the-veterans-affairs-to-achieve-high-reliability-in-suicide-risk-identification',\n",
264
+ " 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development', \n",
265
+ " 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',\n",
266
+ " 'https://www.dssinc.com/blog/2023/5/24/supporting-the-vas-high-reliability-organization-journey-through-suicide-prevention',\n",
267
+ " 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',\n",
268
+ " 'https://www.dssinc.com/blog/2022/9/21/dss-inc-chosen-for-phase-two-of-mission-daybreak-vas-suicide-prevention-challenge',\n",
269
+ " 'https://www.dssinc.com/blog/2022/9/19/crescenz-va-medical-center-cmcvamc-deploys-the-dss-iconic-data-patient-case-manager-pcm-solution',\n",
270
+ " 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization']\n",
271
+ "\n",
272
+ "# load and split\n",
273
+ "loaders = UnstructuredURLLoader(urls=urls)\n",
274
+ "data = loaders.load()\n",
275
+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
276
+ "texts = text_splitter.split_documents(data)\n",
277
+ "print(\"Sources split into the following number of \\\"texts\\\":\", len(texts))\n",
278
+ "\n",
279
+ "# load embedding model\n",
280
+ "print(\"Loading embedding model...\")\n",
281
+ "embeddings = HuggingFaceInstructEmbeddings(model_name=\"hkunlp/instructor-xl\")\n",
282
+ "\n",
283
+ "docsearch = Chroma.from_texts([t.page_content for t in texts], embeddings)"
284
+ ]
285
+ },
286
+ {
287
+ "cell_type": "code",
288
+ "execution_count": null,
289
+ "id": "6fe72b28-0d34-47c5-82f5-7318576e4ec8",
290
+ "metadata": {},
291
+ "outputs": [],
292
+ "source": [
293
+ "print(\"Getting AI response... @ \", datetime.datetime.now().strftime(\"%H:%M:%S\"))\n",
294
+ "print(chain({\"input_documents\": docsearch.similarity_search(query, k=3), \"new_message\": query}, return_only_outputs=True)['output_text'].strip())"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "execution_count": 8,
300
+ "id": "f9c38a37-9aa0-4584-8b06-cee2932d14cf",
301
+ "metadata": {
302
+ "tags": []
303
+ },
304
+ "outputs": [
305
+ {
306
+ "ename": "ClientError",
307
+ "evalue": "An error occurred (ValidationException) when calling the DeleteEndpointConfig operation: Could not find endpoint configuration \"arn:aws:sagemaker:us-east-1:907929678403:endpoint-config/falcon-40b-instruct-demo\".",
308
+ "output_type": "error",
309
+ "traceback": [
310
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
311
+ "\u001b[0;31mClientError\u001b[0m Traceback (most recent call last)",
312
+ "Cell \u001b[0;32mIn[8], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mllm2\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdelete_endpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
313
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/base_predictor.py:339\u001b[0m, in \u001b[0;36mPredictor.delete_endpoint\u001b[0;34m(self, delete_endpoint_config)\u001b[0m\n\u001b[1;32m 327\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Delete the Amazon SageMaker endpoint backing this predictor.\u001b[39;00m\n\u001b[1;32m 328\u001b[0m \n\u001b[1;32m 329\u001b[0m \u001b[38;5;124;03mThis also delete the endpoint configuration attached to it if\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 336\u001b[0m \u001b[38;5;124;03m be deleted. If False, only endpoint will be deleted.\u001b[39;00m\n\u001b[1;32m 337\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 338\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m delete_endpoint_config:\n\u001b[0;32m--> 339\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_delete_endpoint_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 341\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session\u001b[38;5;241m.\u001b[39mdelete_endpoint(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mendpoint_name)\n",
314
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/base_predictor.py:324\u001b[0m, in \u001b[0;36mPredictor._delete_endpoint_config\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 322\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Delete the Amazon SageMaker endpoint configuration\"\"\"\u001b[39;00m\n\u001b[1;32m 323\u001b[0m current_endpoint_config_name \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_get_endpoint_config_name()\n\u001b[0;32m--> 324\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_session\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdelete_endpoint_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcurrent_endpoint_config_name\u001b[49m\u001b[43m)\u001b[49m\n",
315
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/session.py:4086\u001b[0m, in \u001b[0;36mSession.delete_endpoint_config\u001b[0;34m(self, endpoint_config_name)\u001b[0m\n\u001b[1;32m 4079\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Delete an Amazon SageMaker endpoint configuration.\u001b[39;00m\n\u001b[1;32m 4080\u001b[0m \n\u001b[1;32m 4081\u001b[0m \u001b[38;5;124;03mArgs:\u001b[39;00m\n\u001b[1;32m 4082\u001b[0m \u001b[38;5;124;03m endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to\u001b[39;00m\n\u001b[1;32m 4083\u001b[0m \u001b[38;5;124;03m delete.\u001b[39;00m\n\u001b[1;32m 4084\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m 4085\u001b[0m LOGGER\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mDeleting endpoint configuration with name: \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, endpoint_config_name)\n\u001b[0;32m-> 4086\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_client\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdelete_endpoint_config\u001b[49m\u001b[43m(\u001b[49m\u001b[43mEndpointConfigName\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_config_name\u001b[49m\u001b[43m)\u001b[49m\n",
316
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:530\u001b[0m, in \u001b[0;36mClientCreator._create_api_method.<locals>._api_call\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 526\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 527\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpy_operation_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m() only accepts keyword arguments.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 528\u001b[0m )\n\u001b[1;32m 529\u001b[0m \u001b[38;5;66;03m# The \"self\" in this scope is referring to the BaseClient.\u001b[39;00m\n\u001b[0;32m--> 530\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_make_api_call\u001b[49m\u001b[43m(\u001b[49m\u001b[43moperation_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
317
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:964\u001b[0m, in \u001b[0;36mBaseClient._make_api_call\u001b[0;34m(self, operation_name, api_params)\u001b[0m\n\u001b[1;32m 962\u001b[0m error_code \u001b[38;5;241m=\u001b[39m parsed_response\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError\u001b[39m\u001b[38;5;124m\"\u001b[39m, {})\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCode\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 963\u001b[0m error_class \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mexceptions\u001b[38;5;241m.\u001b[39mfrom_code(error_code)\n\u001b[0;32m--> 964\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m error_class(parsed_response, operation_name)\n\u001b[1;32m 965\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 966\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m parsed_response\n",
318
+ "\u001b[0;31mClientError\u001b[0m: An error occurred (ValidationException) when calling the DeleteEndpointConfig operation: Could not find endpoint configuration \"arn:aws:sagemaker:us-east-1:907929678403:endpoint-config/falcon-40b-instruct-demo\"."
319
+ ]
320
+ }
321
+ ],
322
+ "source": [
323
+ "\n",
324
+ "llm2.delete_endpoint()"
325
+ ]
326
+ },
327
+ {
328
+ "cell_type": "code",
329
+ "execution_count": null,
330
+ "id": "881f2cb5-41c5-4fd2-b942-d3c289dda758",
331
+ "metadata": {},
332
+ "outputs": [],
333
+ "source": []
334
+ },
335
+ {
336
+ "cell_type": "code",
337
+ "execution_count": 6,
338
+ "id": "202caf50-c00a-4555-8150-4fc7a779aa0a",
339
+ "metadata": {
340
+ "tags": []
341
+ },
342
+ "outputs": [],
343
+ "source": [
344
+ "from sagemaker.predictor import Predictor\n",
345
+ "\n",
346
+ "llm2 = Predictor(endpoint_name)"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": null,
352
+ "id": "31f54a95-0324-4deb-be0e-89c453004f6c",
353
+ "metadata": {
354
+ "tags": []
355
+ },
356
+ "outputs": [],
357
+ "source": [
358
+ "dom = \"d-bipui5yzbvlc\"\n",
359
+ "print(f'https://{dom}.studio.{aws_region}.sagemaker.aws/studiolab/default/jupyter/proxy/6006/')"
360
+ ]
361
+ }
362
+ ],
363
+ "metadata": {
364
+ "kernelspec": {
365
+ "display_name": "conda_pytorch_p310",
366
+ "language": "python",
367
+ "name": "conda_pytorch_p310"
368
+ },
369
+ "language_info": {
370
+ "codemirror_mode": {
371
+ "name": "ipython",
372
+ "version": 3
373
+ },
374
+ "file_extension": ".py",
375
+ "mimetype": "text/x-python",
376
+ "name": "python",
377
+ "nbconvert_exporter": "python",
378
+ "pygments_lexer": "ipython3",
379
+ "version": "3.10.10"
380
+ }
381
+ },
382
+ "nbformat": 4,
383
+ "nbformat_minor": 5
384
+ }
.ipynb_checkpoints/Untitled-checkpoint.ipynb ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [],
3
+ "metadata": {},
4
+ "nbformat": 4,
5
+ "nbformat_minor": 5
6
+ }
.ipynb_checkpoints/Untitled1-checkpoint.ipynb ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [],
3
+ "metadata": {},
4
+ "nbformat": 4,
5
+ "nbformat_minor": 5
6
+ }
.ipynb_checkpoints/demo_app-checkpoint.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import boto3
2
+ import sagemaker
3
+ from sagemaker.predictor import Predictor
4
+ from sagemaker.serializers import JSONSerializer
5
+ from sagemaker.deserializers import JSONDeserializer
6
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
7
+ from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader, S3FileLoader
8
+ from langchain.docstore.document import Document
9
+ from langchain.document_loaders.csv_loader import CSVLoader
10
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
11
+ from langchain.vectorstores import Chroma
12
+ import json
13
+ import gradio as gr
14
+
15
+ def loadCleanDocsearch(embeddings):
16
+ print("Getting fresh docsearch...")
17
+
18
+ # define URL sources with some stock articles from public DSS website
19
+ urls = [
20
+ 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',
21
+ 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',
22
+ 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',
23
+ 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'
24
+ ]
25
+
26
+ # load and split
27
+ loaders = UnstructuredURLLoader(urls=urls)
28
+ data = loaders.load()
29
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
30
+ texts = text_splitter.split_documents(data)
31
+ print("Sources split into the following number of \"texts\":", len(texts))
32
+
33
+ # get object
34
+ docsearch = Chroma.from_texts([t.page_content for t in texts],
35
+ metadatas=[{"src": "DSS"} for t in texts],
36
+ embedding=embeddings)
37
+ print("Done getting fresh docsearch.")
38
+
39
+ return docsearch
40
+
41
+ def resetDocsearch():
42
+ global docsearch
43
+
44
+ foreignIDs = docsearch.get(where= {"src":"foreign"})['ids']
45
+
46
+ if foreignIDs != []:
47
+ docsearch.delete(ids=foreignIDs)
48
+
49
+ clearStuff()
50
+
51
+
52
+ def addURLsource(url):
53
+ print("Adding new source...")
54
+
55
+ global docsearch
56
+
57
+ # load and split
58
+ loaders = UnstructuredURLLoader(urls=[url])
59
+ data = loaders.load()
60
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
61
+ texts = text_splitter.split_documents(data)
62
+ print("New source split into the following number of \"texts\":", len(texts))
63
+
64
+ # add new sources
65
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
66
+
67
+ # restart convo, as the old messages confuse the AI
68
+ clearStuff()
69
+
70
+ print("Done adding new source.")
71
+
72
+ return None, None
73
+
74
+ # def addCSVsource(url):
75
+ # print("Adding new source...")
76
+
77
+ # global docsearch
78
+
79
+ # # load and split
80
+ # loaders = CSVLoader(urls=[url])
81
+ # data = loaders.load()
82
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
83
+ # texts = text_splitter.split_documents(data)
84
+ # print("New source split into the following number of \"texts\":", len(texts))
85
+
86
+ # # add new sources
87
+ # docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
88
+
89
+ # # restart convo, as the old messages confuse the AI
90
+ # clearStuff()
91
+
92
+ # print("Done adding new source.")
93
+
94
+ # return None, None
95
+
96
+ def addPDFsource(url):
97
+ print("Adding new source...")
98
+
99
+ global docsearch
100
+
101
+ # load and split
102
+ try: # assuming it is local
103
+ data = UnstructuredPDFLoader(url).load()
104
+ except: # not local, try S3
105
+ if '://' in url:
106
+ scheme, path = url.split('://', 1)
107
+ bucket, key = path.split('/', 1)
108
+
109
+ else:
110
+ raise ValueError('Invalid S3 URI')
111
+
112
+ data = S3FileLoader("strategicinnovation", "testingPDFload/bitcoin.pdf").load()
113
+
114
+
115
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
116
+ texts = text_splitter.split_documents(data)
117
+ print("New source split into the following number of \"texts\":", len(texts))
118
+
119
+ # add new sources
120
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
121
+
122
+ # restart convo, as the old messages confuse the AI
123
+ clearStuff()
124
+
125
+ print("Done adding new source.")
126
+
127
+ return None, None
128
+
129
+ def msgs2chatbot(msgs):
130
+ # the gradio chatbot object is used to display the conversation
131
+ # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message
132
+ chatbot = []
133
+
134
+ for msg in msgs:
135
+ if msg['role'] == 'user':
136
+ chatbot.append([msg['content'], ""])
137
+ elif msg['role'] == 'assistant':
138
+ chatbot[-1][1] = msg['content']
139
+
140
+ return chatbot
141
+
142
+ def getPrediction(newMsg):
143
+ global msgs
144
+ global docsearch
145
+ global predictor
146
+
147
+ # add new message to msgs object
148
+ msgs.append({"role":"user", "content": newMsg})
149
+
150
+ # edit system message to include the correct context
151
+ msgs[0] = {"role": "system",
152
+ "content": f"""
153
+ You are a helpful AI assistant.
154
+ Use your knowledge to answer the user's question if they asked a question.
155
+ If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.
156
+ DO NOT use phrases like "Based on the information provided" or other similar phrases.
157
+ Refer to the information provided below as "your knowledge".
158
+ State all answers as if they are ground truth, DO NOT mention where you got the information.
159
+
160
+ YOUR KNOWLEDGE: {" ".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}"""}
161
+
162
+ # get response from endpoint
163
+
164
+ responseObject = predictor.predict({"inputs": [msgs],
165
+ "parameters": {"max_new_tokens": 750, "top_p": 0.9, "temperature": 0.5}},
166
+ initial_args={'CustomAttributes': "accept_eula=true"})
167
+ # responseObject = predictor.predict(payload, custom_attributes="accept_eula=true")
168
+
169
+
170
+ responseMsg = responseObject[0]['generation']['content'].strip()
171
+
172
+ # add response to msgs object
173
+ msgs.append({"role":"assistant", "content": responseMsg})
174
+
175
+ # print msgs object for debugging
176
+ print(msgs)
177
+
178
+ # convert msgs to chatbot object to be displayed
179
+ chatbot = msgs2chatbot(msgs)
180
+
181
+ return chatbot, ""
182
+
183
+ def clearStuff():
184
+ global msgs
185
+ msgs = [{}]
186
+ return None
187
+
188
+ # Create a SageMaker client
189
+ sagemaker_client = boto3.client('sagemaker')
190
+ sagemaker_session = sagemaker.Session()
191
+
192
+ # Create a predictor object
193
+ predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',
194
+ sagemaker_session=sagemaker_session,
195
+ serializer=JSONSerializer(),
196
+ deserializer=JSONDeserializer())
197
+
198
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
199
+
200
+ # Create a docsearch object
201
+ docsearch = loadCleanDocsearch(embeddings)
202
+
203
+ # Create messages list with system message
204
+ msgs = [{}]
205
+
206
+ with gr.Blocks() as demo:
207
+ gr.HTML("<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />")
208
+ gr.Markdown("## DSS LLM Demo: Chat with Llama 2")
209
+
210
+ with gr.Column():
211
+ chatbot = gr.Chatbot()
212
+
213
+ with gr.Row():
214
+ with gr.Column():
215
+ newMsg = gr.Textbox(label="New Message Box", placeholder="New Message", show_label=False)
216
+ with gr.Column():
217
+ with gr.Row():
218
+ submit = gr.Button("Submit")
219
+ clear = gr.Button("Clear")
220
+ with gr.Row():
221
+ with gr.Column():
222
+ newSRC = gr.Textbox(label="New source link/path Box", placeholder="New source link/path", show_label=False)
223
+ with gr.Column():
224
+ with gr.Row():
225
+ addURL = gr.Button("Add URL Source")
226
+ addPDF = gr.Button("Add PDF Source")
227
+ #uploadFile = gr.UploadButton(file_types=[".pdf",".csv",".doc"])
228
+ reset = gr.Button("Reset Sources")
229
+
230
+ submit.click(getPrediction, [newMsg], [chatbot, newMsg])
231
+ clear.click(clearStuff, None, chatbot, queue=False)
232
+
233
+ addURL.click(addURLsource, newSRC, [newSRC, chatbot])
234
+ addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])
235
+ #uploadFile.click(getOut, uploadFile, None)
236
+ reset.click(resetDocsearch, None, chatbot)
237
+
238
+ gr.Markdown("""*Note:*
239
+
240
+ To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.
241
+
242
+ To add a PDF source, place either (1) the relative filepath to the current directory or (2) the full S3 URI in the bottom textbox and click the 'Add PDF Source' button.
243
+
244
+ The database for contextualization includes 8 public DSS website articles upon initialization.
245
+
246
+ When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)""")
247
+
248
+
249
+ demo.queue()
250
+ demo.launch(share=True)
.ipynb_checkpoints/llama2_gradio_v0.3-checkpoint.ipynb ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "0cd0e718-beac-4442-ac45-fffb26698d33",
6
+ "metadata": {
7
+ "tags": []
8
+ },
9
+ "source": [
10
+ "# Install packages, need to write a requirement later\n",
11
+ "!pip install instructorembedding sentence-transformers gradio langchain unstructured chromadb pdf2image pdfminer pdfminer.six"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": 2,
17
+ "id": "4d086ed6-eb66-4ded-b701-dac062e19521",
18
+ "metadata": {
19
+ "tags": []
20
+ },
21
+ "outputs": [],
22
+ "source": [
23
+ "import boto3\n",
24
+ "import sagemaker\n",
25
+ "from sagemaker.predictor import Predictor\n",
26
+ "from sagemaker.serializers import JSONSerializer\n",
27
+ "from sagemaker.deserializers import JSONDeserializer\n",
28
+ "from langchain.embeddings import HuggingFaceInstructEmbeddings\n",
29
+ "from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader\n",
30
+ "from langchain.document_loaders.csv_loader import CSVLoader\n",
31
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
32
+ "from langchain.vectorstores import Chroma\n",
33
+ "import json\n",
34
+ "import gradio as gr"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": 6,
40
+ "id": "a2d81908-6026-47b6-bd0d-ade2771eacdd",
41
+ "metadata": {
42
+ "tags": []
43
+ },
44
+ "outputs": [],
45
+ "source": [
46
+ "def loadCleanDocsearch(embeddings):\n",
47
+ " print(\"Getting fresh docsearch...\")\n",
48
+ "\n",
49
+ " # define URL sources\n",
50
+ " urls = [\n",
51
+ " 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',\n",
52
+ " 'https://www.dssinc.com/blog/2022/6/21/suicide-prevention-manager-enabling-the-veterans-affairs-to-achieve-high-reliability-in-suicide-risk-identification',\n",
53
+ " 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',\n",
54
+ " 'https://www.dssinc.com/blog/2023/5/24/supporting-the-vas-high-reliability-organization-journey-through-suicide-prevention',\n",
55
+ " 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',\n",
56
+ " 'https://www.dssinc.com/blog/2022/9/19/crescenz-va-medical-center-cmcvamc-deploys-the-dss-iconic-data-patient-case-manager-pcm-solution',\n",
57
+ " 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'\n",
58
+ " ]\n",
59
+ "\n",
60
+ " # load and split\n",
61
+ " loaders = UnstructuredURLLoader(urls=urls)\n",
62
+ " data = loaders.load()\n",
63
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)\n",
64
+ " texts = text_splitter.split_documents(data)\n",
65
+ " print(\"Sources split into the following number of \\\"texts\\\":\", len(texts))\n",
66
+ "\n",
67
+ " # get object\n",
68
+ " docsearch = Chroma.from_texts([t.page_content for t in texts],\n",
69
+ " metadatas=[{\"src\": \"DSS\"} for t in texts],\n",
70
+ " embedding=embeddings)\n",
71
+ " print(\"Done getting fresh docsearch.\")\n",
72
+ "\n",
73
+ " return docsearch\n",
74
+ "\n",
75
+ "def resetDocsearch():\n",
76
+ " global docsearch\n",
77
+ "\n",
78
+ " foreignIDs = docsearch.get(where= {\"src\":\"foreign\"})['ids']\n",
79
+ "\n",
80
+ " if foreignIDs != []:\n",
81
+ " docsearch.delete(ids=foreignIDs)\n",
82
+ " \n",
83
+ " clearStuff()\n",
84
+ " msgs[0] = {\"role\": \"system\",\n",
85
+ " \"content\": f\"\"\"\n",
86
+ " You are a helpful AI assistant.\n",
87
+ " Use your knowledge to answer the user's question if they asked a question.\n",
88
+ " If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\n",
89
+ " DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \n",
90
+ " Refer to the information provided below as \"your knowledge\". \n",
91
+ " State all answers as if they are ground truth, DO NOT mention where you got the information.\n",
92
+ "\n",
93
+ " YOUR KNOWLEDGE: {\" \".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}\"\"\"}\n",
94
+ " \n",
95
+ "def addURLsource(url):\n",
96
+ " print(\"Adding new source...\")\n",
97
+ " \n",
98
+ " global docsearch\n",
99
+ "\n",
100
+ " # load and split\n",
101
+ " loaders = UnstructuredURLLoader(urls=[url])\n",
102
+ " data = loaders.load()\n",
103
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
104
+ " texts = text_splitter.split_documents(data)\n",
105
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
106
+ "\n",
107
+ " # add new sources\n",
108
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
109
+ " \n",
110
+ " # restart convo, as the old messages confuse the AI\n",
111
+ " clearStuff()\n",
112
+ "\n",
113
+ " print(\"Done adding new source.\")\n",
114
+ " \n",
115
+ " return None, None\n",
116
+ "\n",
117
+ "def addCSVsource(url):\n",
118
+ " print(\"Adding new source...\")\n",
119
+ " \n",
120
+ " global docsearch\n",
121
+ "\n",
122
+ " # load and split\n",
123
+ " loaders = CSVLoader(urls=[url])\n",
124
+ " data = loaders.load()\n",
125
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
126
+ " texts = text_splitter.split_documents(data)\n",
127
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
128
+ "\n",
129
+ " # add new sources\n",
130
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
131
+ " \n",
132
+ " # restart convo, as the old messages confuse the AI\n",
133
+ " clearStuff()\n",
134
+ "\n",
135
+ " print(\"Done adding new source.\")\n",
136
+ " \n",
137
+ " return None, None\n",
138
+ "\n",
139
+ "def addPDFsource(url):\n",
140
+ " print(\"Adding new source...\")\n",
141
+ "\n",
142
+ " global docsearch\n",
143
+ " \n",
144
+ " # load and split\n",
145
+ " loaders = UnstructuredPDFLoader(url)\n",
146
+ " data = loaders.load()\n",
147
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
148
+ " texts = text_splitter.split_documents(data)\n",
149
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
150
+ "\n",
151
+ " # add new sources\n",
152
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
153
+ " \n",
154
+ " # restart convo, as the old messages confuse the AI\n",
155
+ " clearStuff()\n",
156
+ "\n",
157
+ " print(\"Done adding new source.\")\n",
158
+ " \n",
159
+ " return None, None\n",
160
+ "\n",
161
+ "def msgs2chatbot(msgs):\n",
162
+ " # the gradio chatbot object is used to display the conversation\n",
163
+ " # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message\n",
164
+ " chatbot = []\n",
165
+ " \n",
166
+ " for msg in msgs:\n",
167
+ " if msg['role'] == 'user':\n",
168
+ " chatbot.append([msg['content'], \"\"])\n",
169
+ " elif msg['role'] == 'assistant':\n",
170
+ " chatbot[-1][1] = msg['content']\n",
171
+ "\n",
172
+ " return chatbot\n",
173
+ "\n",
174
+ "def getPrediction(newMsg):\n",
175
+ " global msgs\n",
176
+ " global docsearch\n",
177
+ " global predictor\n",
178
+ " \n",
179
+ " # add new message to msgs object\n",
180
+ " msgs.append({\"role\":\"user\", \"content\": newMsg})\n",
181
+ "\n",
182
+ " # edit system message to include the correct context\n",
183
+ " msgs[0] = {\"role\": \"system\",\n",
184
+ " \"content\": f\"\"\"\n",
185
+ " You are a helpful AI assistant.\n",
186
+ " Use your knowledge to answer the user's question if they asked a question.\n",
187
+ " If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\n",
188
+ " DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \n",
189
+ " Refer to the information provided below as \"your knowledge\". \n",
190
+ " State all answers as if they are ground truth, DO NOT mention where you got the information.\n",
191
+ " \n",
192
+ " YOUR KNOWLEDGE: {\" \".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}\"\"\"}\n",
193
+ "\n",
194
+ " # get response from endpoint\n",
195
+ "\n",
196
+ " responseObject = predictor.predict({\"inputs\": [msgs],\n",
197
+ " \"parameters\": {\"max_new_tokens\": 750, \"top_p\": 0.9, \"temperature\": 0.5}},\n",
198
+ " initial_args={'CustomAttributes': \"accept_eula=true\"})\n",
199
+ "# responseObject = predictor.predict(payload, custom_attributes=\"accept_eula=true\")\n",
200
+ "\n",
201
+ " \n",
202
+ " responseMsg = responseObject[0]['generation']['content'].strip()\n",
203
+ "\n",
204
+ " # add response to msgs object\n",
205
+ " msgs.append({\"role\":\"assistant\", \"content\": responseMsg})\n",
206
+ " \n",
207
+ " # print msgs object for debugging\n",
208
+ " print(msgs)\n",
209
+ " \n",
210
+ " # convert msgs to chatbot object to be displayed\n",
211
+ " chatbot = msgs2chatbot(msgs)\n",
212
+ "\n",
213
+ " return chatbot, \"\"\n",
214
+ "\n",
215
+ "def clearStuff():\n",
216
+ " global msgs\n",
217
+ " msgs = [{}]\n",
218
+ " return None"
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "execution_count": 7,
224
+ "id": "c56c588d-1bca-448f-bba9-96f61e5bab33",
225
+ "metadata": {
226
+ "tags": []
227
+ },
228
+ "outputs": [
229
+ {
230
+ "name": "stdout",
231
+ "output_type": "stream",
232
+ "text": [
233
+ "load INSTRUCTOR_Transformer\n",
234
+ "max_seq_length 512\n",
235
+ "Getting fresh docsearch...\n",
236
+ "Sources split into the following number of \"texts\": 36\n",
237
+ "Done getting fresh docsearch.\n"
238
+ ]
239
+ }
240
+ ],
241
+ "source": [
242
+ "# Create a SageMaker client\n",
243
+ "sagemaker_client = boto3.client('sagemaker')\n",
244
+ "sagemaker_session = sagemaker.Session()\n",
245
+ "\n",
246
+ "# Create a predictor object\n",
247
+ "predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',\n",
248
+ " sagemaker_session=sagemaker_session,\n",
249
+ " serializer=JSONSerializer(),\n",
250
+ " deserializer=JSONDeserializer())\n",
251
+ "\n",
252
+ "embeddings = HuggingFaceInstructEmbeddings(model_name=\"hkunlp/instructor-xl\")\n",
253
+ "\n",
254
+ "# Create a docsearch object\n",
255
+ "docsearch = loadCleanDocsearch(embeddings)\n",
256
+ "\n",
257
+ "# Create messages list with system message\n",
258
+ "msgs = [{}]"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": 8,
264
+ "id": "0572e3b3-2805-4db5-9d23-dac40842c58c",
265
+ "metadata": {
266
+ "tags": []
267
+ },
268
+ "outputs": [
269
+ {
270
+ "name": "stdout",
271
+ "output_type": "stream",
272
+ "text": [
273
+ "Running on local URL: http://127.0.0.1:7861\n",
274
+ "Running on public URL: https://19e4016261d7378e5b.gradio.live\n",
275
+ "\n",
276
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
277
+ ]
278
+ },
279
+ {
280
+ "data": {
281
+ "text/html": [
282
+ "<div><iframe src=\"https://19e4016261d7378e5b.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
283
+ ],
284
+ "text/plain": [
285
+ "<IPython.core.display.HTML object>"
286
+ ]
287
+ },
288
+ "metadata": {},
289
+ "output_type": "display_data"
290
+ },
291
+ {
292
+ "data": {
293
+ "text/plain": []
294
+ },
295
+ "execution_count": 8,
296
+ "metadata": {},
297
+ "output_type": "execute_result"
298
+ },
299
+ {
300
+ "name": "stdout",
301
+ "output_type": "stream",
302
+ "text": [
303
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: Formerly the President of a federally focused consulting company, Bailey has over 25 years of sales and business development experience, managing product portfolios and sales of disruptive and innovative technology and equipment solutions for the healthcare market – both in the public and private sectors.\\n\\n“We are excited to have Brion onboard to help expand our ever-growing footprint in the federal health arena,” said Mark Byers, president of DSS, Inc. “He brings a deep level of sales and business development expertise in supporting cutting-edge and disruptive healthcare innovations.” Formerly the President of a federally focused consulting company, Bailey has over 25 years of sales and business development experience, managing product portfolios and sales of disruptive and innovative technology and equipment solutions for the healthcare market – both in the public and private sectors.\\n\\n“We are excited to have Brion onboard to help expand our ever-growing footprint in the federal health arena,” said Mark Byers, president of DSS, Inc. “He brings a deep level of sales and business development expertise in supporting cutting-edge and disruptive healthcare innovations.” As VP of Strategic Accounts for the U.S. Federal Sector at Becton Dickinson, Bailey provided medical technology portfolio management and exceeded performance metrics on customer relationship building, channel partner development, customer acquisition processes, and operating procedures aligned with federal acquisitions requirements. All of this activity resulted in substantial growth in market share during his five-year tenure with the company.\\n\\nBailey has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University. He resides in Central Florida with his wife and son.\\n\\nFor more information on DSS, Inc.’s Federal Health IT solutions, please click here. As VP of Strategic Accounts for the U.S. Federal Sector at Becton Dickinson, Bailey provided medical technology portfolio management and exceeded performance metrics on customer relationship building, channel partner development, customer acquisition processes, and operating procedures aligned with federal acquisitions requirements. All of this activity resulted in substantial growth in market share during his five-year tenure with the company.\\n\\nBailey has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University. He resides in Central Florida with his wife and son.\\n\\nFor more information on DSS, Inc.’s Federal Health IT solutions, please click here. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies.'}, {'role': 'user', 'content': 'who is brion bailey'}, {'role': 'assistant', 'content': 'Based on the information provided, Brion Bailey is the Director of Business Development for the Federal Health division of Document Storage Systems, Inc. (DSS, Inc.). He has over 25 years of sales and business development experience, specifically in supporting disruptive healthcare innovations. Prior to joining DSS, Inc., Bailey was the President of a federally focused consulting company, where he managed product portfolios and sales of innovative technology and equipment solutions for the healthcare market. He has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University.'}]\n",
304
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen DSS Federal Health\\n\\nTwitter\\n\\nLinkedIn0\\n\\n0 Likes\\n\\nPrevious\\n DSS, Inc. Advisor to Present at Disney Institute’s Veterans Summit\\n \\n DSS NewsCindy DumontAugust 10, 2022Disney Institute’s Veterans Summit, Dr. Barbara Van Dahlen, Veterans in the Workplace, Heroes Work Here initiative, suicide prevention for Veterans, The Inclusive Approach to Care, General Mike Linnington Ret., CEO of the Wounded Warrior Project, Mark Elliot, Give an Hour, Veterans, Veterans mental health\\n\\nNext\\n Contracting Officers: Celebrating the Unsung Heroes at the VA\\n \\n Customer ServiceCindy DumontJuly 27, 2022Contracting Officers, VA, Department of Veterans Affairs, Procurement, federal health IT solutions, DSS, Health IT'}, {'role': 'user', 'content': 'who is brion bailey'}, {'role': 'assistant', 'content': 'Based on the information provided, Brion Bailey is the Director of Business Development for the Federal Health division of Document Storage Systems, Inc. (DSS, Inc.). He has over 25 years of sales and business development experience, specifically in supporting disruptive healthcare innovations. Prior to joining DSS, Inc., Bailey was the President of a federally focused consulting company, where he managed product portfolios and sales of innovative technology and equipment solutions for the healthcare market. He has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University.'}, {'role': 'user', 'content': 'did dss join mission daybreak?'}, {'role': 'assistant', 'content': 'Based on the information provided, there is no mention of DSS joining Mission Daybreak.'}]\n",
305
+ "Adding new source...\n",
306
+ "New source split into the following number of \"texts\": 5\n",
307
+ "Done adding new source.\n"
308
+ ]
309
+ },
310
+ {
311
+ "name": "stderr",
312
+ "output_type": "stream",
313
+ "text": [
314
+ "Traceback (most recent call last):\n",
315
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/routes.py\", line 488, in run_predict\n",
316
+ " output = await app.get_blocks().process_api(\n",
317
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/blocks.py\", line 1431, in process_api\n",
318
+ " result = await self.call_function(\n",
319
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/blocks.py\", line 1109, in call_function\n",
320
+ " prediction = await anyio.to_thread.run_sync(\n",
321
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/anyio/to_thread.py\", line 31, in run_sync\n",
322
+ " return await get_asynclib().run_sync_in_worker_thread(\n",
323
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 937, in run_sync_in_worker_thread\n",
324
+ " return await future\n",
325
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 867, in run\n",
326
+ " result = context.run(func, *args)\n",
327
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/utils.py\", line 706, in wrapper\n",
328
+ " response = f(*args, **kwargs)\n",
329
+ " File \"/tmp/ipykernel_9156/3825752108.py\", line 39, in resetDocsearch\n",
330
+ " msgs = msgs[0]\n",
331
+ "UnboundLocalError: local variable 'msgs' referenced before assignment\n",
332
+ "Traceback (most recent call last):\n",
333
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/routes.py\", line 488, in run_predict\n",
334
+ " output = await app.get_blocks().process_api(\n",
335
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/blocks.py\", line 1431, in process_api\n",
336
+ " result = await self.call_function(\n",
337
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/blocks.py\", line 1109, in call_function\n",
338
+ " prediction = await anyio.to_thread.run_sync(\n",
339
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/anyio/to_thread.py\", line 31, in run_sync\n",
340
+ " return await get_asynclib().run_sync_in_worker_thread(\n",
341
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 937, in run_sync_in_worker_thread\n",
342
+ " return await future\n",
343
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 867, in run\n",
344
+ " result = context.run(func, *args)\n",
345
+ " File \"/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/gradio/utils.py\", line 706, in wrapper\n",
346
+ " response = f(*args, **kwargs)\n",
347
+ " File \"/tmp/ipykernel_9156/3825752108.py\", line 39, in resetDocsearch\n",
348
+ " msgs = msgs[0]\n",
349
+ "UnboundLocalError: local variable 'msgs' referenced before assignment\n"
350
+ ]
351
+ }
352
+ ],
353
+ "source": [
354
+ "with gr.Blocks() as demo:\n",
355
+ " gr.HTML(\"<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />\")\n",
356
+ " gr.Markdown(\"## DSS LLM Demo: Chat with Llama 2\")\n",
357
+ "\n",
358
+ " with gr.Column():\n",
359
+ " chatbot = gr.Chatbot()\n",
360
+ " \n",
361
+ " with gr.Row():\n",
362
+ " with gr.Column():\n",
363
+ " newMsg = gr.Textbox(label=\"New Message Box\", placeholder=\"New Message\", show_label=False)\n",
364
+ " with gr.Column():\n",
365
+ " with gr.Row():\n",
366
+ " submit = gr.Button(\"Submit\")\n",
367
+ " clear = gr.Button(\"Clear\")\n",
368
+ " with gr.Row():\n",
369
+ " with gr.Column():\n",
370
+ " newSRC = gr.Textbox(label=\"New source link/path Box\", placeholder=\"New source link/path\", show_label=False)\n",
371
+ " with gr.Column():\n",
372
+ " with gr.Row():\n",
373
+ " addURL = gr.Button(\"Add URL Source\")\n",
374
+ " addPDF = gr.Button(\"Add PDF Source\")\n",
375
+ " reset = gr.Button(\"Reset Sources\")\n",
376
+ "\n",
377
+ " submit.click(getPrediction, [newMsg], [chatbot, newMsg])\n",
378
+ " clear.click(clearStuff, None, chatbot, queue=False)\n",
379
+ " \n",
380
+ " addURL.click(addURLsource, newSRC, [newSRC, chatbot])\n",
381
+ " addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])\n",
382
+ " reset.click(resetDocsearch, None, chatbot)\n",
383
+ "\n",
384
+ " gr.Markdown(\"\"\"*Note: \n",
385
+ " \n",
386
+ " To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.\n",
387
+ " \n",
388
+ " To add a PDF source, place a relative file path in the bottom textbox and click the 'Add PDF Source' button.\n",
389
+ " \n",
390
+ " The database for contextualization includes 8 public DSS website articles upon initialization.\n",
391
+ " \n",
392
+ " When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)*\"\"\")\n",
393
+ "\n",
394
+ "\n",
395
+ "demo.queue()\n",
396
+ "demo.launch(share=True)"
397
+ ]
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "execution_count": null,
402
+ "id": "e200839d-9f90-4651-8212-decc75d1e3e3",
403
+ "metadata": {},
404
+ "outputs": [],
405
+ "source": []
406
+ }
407
+ ],
408
+ "metadata": {
409
+ "kernelspec": {
410
+ "display_name": "conda_pytorch_p310",
411
+ "language": "python",
412
+ "name": "conda_pytorch_p310"
413
+ },
414
+ "language_info": {
415
+ "codemirror_mode": {
416
+ "name": "ipython",
417
+ "version": 3
418
+ },
419
+ "file_extension": ".py",
420
+ "mimetype": "text/x-python",
421
+ "name": "python",
422
+ "nbconvert_exporter": "python",
423
+ "pygments_lexer": "ipython3",
424
+ "version": "3.10.10"
425
+ }
426
+ },
427
+ "nbformat": 4,
428
+ "nbformat_minor": 5
429
+ }
.ipynb_checkpoints/llama2_gradio_v0.4-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
.ipynb_checkpoints/llama2_gradio_v0.4_backup-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
.ipynb_checkpoints/llama2_gradio_v0.4_s3-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
.ipynb_checkpoints/main-checkpoint.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sagemaker
2
+ import streamlit as st
3
+ from streamlit_chat import message
4
+ from langchain.llms.sagemaker_endpoint import LLMContentHandler, SagemakerEndpoint
5
+ from langchain.document_loaders import UnstructuredURLLoader
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain.vectorstores import Chroma
8
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
9
+ from langchain import PromptTemplate
10
+ from langchain.chains.question_answering import load_qa_chain
11
+ from langchain.memory import ConversationBufferMemory
12
+ from typing import Dict
13
+ import json
14
+ import chromadb
15
+ import datetime
16
+
17
+ endpoint_name = "falcon-40b-instruct-gates3"
18
+ aws_region = "us-east-1"
19
+ class ContentHandler(LLMContentHandler):
20
+ content_type = "application/json"
21
+ accepts = "application/json"
22
+ len_prompt = 0
23
+
24
+ def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:
25
+ self.len_prompt = len(prompt)
26
+ input_str = json.dumps(
27
+ {"inputs": prompt,
28
+ "parameters": {
29
+ "do_sample": True,
30
+ "top_p": 0.9,
31
+ "temperature": 0.8,
32
+ "max_new_tokens": 1024,
33
+ "repetition_penalty": 1.03,
34
+ "stop": ["\n\n", "Human:", "<|endoftext|>", "</s>"]
35
+ }})
36
+ return input_str.encode('utf-8')
37
+
38
+ def transform_output(self, output: bytes) -> str:
39
+ response_json = output.read()
40
+ res = json.loads(response_json)
41
+ ans = res[0]['generated_text'][self.len_prompt:]
42
+ ans = ans[:ans.rfind("Human")].strip()
43
+ return ans
44
+
45
+
46
+ @st.cache_resource
47
+ def getDocsearchOnce():
48
+ print("Getting docsearch...")
49
+
50
+ # define URL sources
51
+ urls = [
52
+ 'https://www.dssinc.com/blog/2022/6/21/suicide-prevention-manager-enabling-the-veterans-affairs-to-achieve-high-reliability-in-suicide-risk-identification',
53
+ 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',
54
+ 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',
55
+ 'https://www.dssinc.com/blog/2023/5/24/supporting-the-vas-high-reliability-organization-journey-through-suicide-prevention',
56
+ 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',
57
+ 'https://www.dssinc.com/blog/2022/9/21/dss-inc-chosen-for-phase-two-of-mission-daybreak-vas-suicide-prevention-challenge',
58
+ 'https://www.dssinc.com/blog/2022/9/19/crescenz-va-medical-center-cmcvamc-deploys-the-dss-iconic-data-patient-case-manager-pcm-solution',
59
+ 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization']
60
+
61
+ # load and split
62
+ loaders = UnstructuredURLLoader(urls=urls)
63
+ data = loaders.load()
64
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
65
+ texts = text_splitter.split_documents(data) # do not want to reassign (must stay consistent with pinecone embeddings)
66
+ print("Sources split into the following number of \"texts\":", len(texts))
67
+
68
+ # load embedding model
69
+ print("Loading embedding model...")
70
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
71
+
72
+ docsearch = Chroma.from_texts([t.page_content for t in texts], embeddings)
73
+
74
+ return docsearch
75
+
76
+
77
+ @st.cache_resource
78
+ def getChainOnce():
79
+ print("Getting chain...")
80
+
81
+ content_handler = ContentHandler()
82
+
83
+ # get langchain-wrapped Predictor Endpoint Object
84
+ llm = SagemakerEndpoint(
85
+ endpoint_name=endpoint_name,
86
+ region_name=aws_region,
87
+ content_handler=content_handler
88
+ )
89
+
90
+ # configure the prompt object
91
+ prompt = PromptTemplate(
92
+ input_variables=["history", "context", "new_message"],
93
+ template="""
94
+ The following is a given context and history of a conversation between a human and a helpful AI assistant.
95
+ The AI assistant answers the human's messages with full, informational responses by inferring on the information given in the context, but does not extrapolate any facts that are not given.
96
+ When answering questions with uncertain answers, the AI assistant qualifies responses as such.
97
+ The AI assistant pretends it is also human and that the context is objectively true and therefore avoids mentioning the context as a source.
98
+
99
+ Context: {context}
100
+
101
+ {history}
102
+ Human: {new_message}
103
+ AI:"""
104
+ )
105
+ return load_qa_chain(llm=llm, chain_type="stuff", verbose=True, memory=ConversationBufferMemory(memory_key="history", input_key="new_message"), prompt=prompt)
106
+
107
+
108
+ def getAIresponse(chain, docsearch, query):
109
+ print("Getting AI response... @ ", datetime.datetime.now().strftime("%H:%M:%S"))
110
+ return chain({"input_documents": docsearch.similarity_search(query, k=3), "new_message": query}, return_only_outputs=True)['output_text'].strip()
111
+
112
+
113
+ st.title("DSS Prototype LLM 💬")
114
+
115
+ # THREE VARIABLES NEED TO BE PERSISTENT:
116
+
117
+ # 1. Conversational Chain
118
+ if "chain" not in st.session_state:
119
+ st.session_state["chain"] = getChainOnce()
120
+
121
+ # 2. docsearch object
122
+ if "docsearch" not in st.session_state:
123
+ st.session_state["docsearch"] = getDocsearchOnce()
124
+
125
+ # 3. messages for UI
126
+ if "messages" not in st.session_state:
127
+ st.session_state["messages"] = []
128
+
129
+
130
+ # DRAW THE ACTUAL UI AND IMPLEMENT FUNCTIONALITY
131
+ # (some formatting is handled by streamlit chat)
132
+
133
+ # draw input box
134
+ with st.form("chat_input", clear_on_submit=True):
135
+ a, b = st.columns([4, 1])
136
+ user_input = a.text_input(
137
+ label="Your message:",
138
+ placeholder="What would you like to say?",
139
+ label_visibility="collapsed",
140
+ )
141
+ b.form_submit_button("Send", use_container_width=True)
142
+
143
+ # handle input
144
+ if user_input:
145
+ st.session_state.messages.append({"role":"user", "content": user_input})
146
+ respText = getAIresponse(st.session_state.chain, st.session_state.docsearch, user_input)
147
+ print(respText)
148
+ st.session_state.messages.append({"role":"assistant", "content": respText})
149
+
150
+ # draw messages
151
+ for k, msg in enumerate(st.session_state.messages):
152
+ message(msg["content"], is_user=msg["role"] == "user", key=k)
153
+
154
+
155
+
156
+
157
+
.virtual_documents/llama2_gradio_v0.4.ipynb ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import boto3
2
+ import sagemaker
3
+ from sagemaker.predictor import Predictor
4
+ from sagemaker.serializers import JSONSerializer
5
+ from sagemaker.deserializers import JSONDeserializer
6
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
7
+ from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader
8
+ from langchain.document_loaders.csv_loader import CSVLoader
9
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
10
+ from langchain.vectorstores import Chroma
11
+ import json
12
+ import gradio as gr
13
+
14
+
15
+ def loadCleanDocsearch(embeddings):
16
+ print("Getting fresh docsearch...")
17
+
18
+ # define URL sources
19
+ urls = [
20
+ 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',
21
+ 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',
22
+ 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',
23
+ 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'
24
+ ]
25
+
26
+ # load and split
27
+ loaders = UnstructuredURLLoader(urls=urls)
28
+ data = loaders.load()
29
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
30
+ texts = text_splitter.split_documents(data)
31
+ print("Sources split into the following number of \"texts\":", len(texts))
32
+
33
+ # get object
34
+ docsearch = Chroma.from_texts([t.page_content for t in texts],
35
+ metadatas=[{"src": "DSS"} for t in texts],
36
+ embedding=embeddings)
37
+ print("Done getting fresh docsearch.")
38
+
39
+ return docsearch
40
+
41
+ def resetDocsearch():
42
+ global docsearch
43
+
44
+ foreignIDs = docsearch.get(where= {"src":"foreign"})['ids']
45
+
46
+ if foreignIDs != []:
47
+ docsearch.delete(ids=foreignIDs)
48
+
49
+ clearStuff()
50
+
51
+ def addURLsource(url):
52
+ print("Adding new source...")
53
+
54
+ global docsearch
55
+
56
+ # load and split
57
+ loaders = UnstructuredURLLoader(urls=[url])
58
+ data = loaders.load()
59
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
60
+ texts = text_splitter.split_documents(data)
61
+ print("New source split into the following number of \"texts\":", len(texts))
62
+
63
+ # add new sources
64
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
65
+
66
+ # restart convo, as the old messages confuse the AI
67
+ clearStuff()
68
+
69
+ print("Done adding new source.")
70
+
71
+ return None, None
72
+
73
+ def addCSVsource(url):
74
+ print("Adding new source...")
75
+
76
+ global docsearch
77
+
78
+ # load and split
79
+ loaders = CSVLoader(urls=[url])
80
+ data = loaders.load()
81
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
82
+ texts = text_splitter.split_documents(data)
83
+ print("New source split into the following number of \"texts\":", len(texts))
84
+
85
+ # add new sources
86
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
87
+
88
+ # restart convo, as the old messages confuse the AI
89
+ clearStuff()
90
+
91
+ print("Done adding new source.")
92
+
93
+ return None, None
94
+
95
+ def addPDFsource(url):
96
+ print("Adding new source...")
97
+
98
+ global docsearch
99
+
100
+ # load and split
101
+ loaders = UnstructuredPDFLoader(url)
102
+ data = loaders.load()
103
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
104
+ texts = text_splitter.split_documents(data)
105
+ print("New source split into the following number of \"texts\":", len(texts))
106
+
107
+ # add new sources
108
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
109
+
110
+ # restart convo, as the old messages confuse the AI
111
+ clearStuff()
112
+
113
+ print("Done adding new source.")
114
+
115
+ return None, None
116
+
117
+ def msgs2chatbot(msgs):
118
+ # the gradio chatbot object is used to display the conversation
119
+ # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message
120
+ chatbot = []
121
+
122
+ for msg in msgs:
123
+ if msg['role'] == 'user':
124
+ chatbot.append([msg['content'], ""])
125
+ elif msg['role'] == 'assistant':
126
+ chatbot[-1][1] = msg['content']
127
+
128
+ return chatbot
129
+
130
+ def getPrediction(newMsg):
131
+ global msgs
132
+ global docsearch
133
+ global predictor
134
+
135
+ # add new message to msgs object
136
+ msgs.append({"role":"user", "content": newMsg})
137
+
138
+ # edit system message to include the correct context
139
+ msgs[0] = {"role": "system",
140
+ "content": f"""
141
+ You are a helpful AI assistant.
142
+ Use your knowledge to answer the user's question if they asked a question.
143
+ If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.
144
+ DO NOT use phrases like "Based on the information provided" or other similar phrases.
145
+ Refer to the information provided below as "your knowledge".
146
+ State all answers as if they are ground truth, DO NOT mention where you got the information.
147
+
148
+ YOUR KNOWLEDGE: {" ".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}"""}
149
+
150
+ # get response from endpoint
151
+
152
+ responseObject = predictor.predict({"inputs": [msgs],
153
+ "parameters": {"max_new_tokens": 750, "top_p": 0.9, "temperature": 0.5}},
154
+ initial_args={'CustomAttributes': "accept_eula=true"})
155
+ # responseObject = predictor.predict(payload, custom_attributes="accept_eula=true")
156
+
157
+
158
+ responseMsg = responseObject[0]['generation']['content'].strip()
159
+
160
+ # add response to msgs object
161
+ msgs.append({"role":"assistant", "content": responseMsg})
162
+
163
+ # print msgs object for debugging
164
+ print(msgs)
165
+
166
+ # convert msgs to chatbot object to be displayed
167
+ chatbot = msgs2chatbot(msgs)
168
+
169
+ return chatbot, ""
170
+
171
+ def clearStuff():
172
+ global msgs
173
+ msgs = [{}]
174
+ return None
175
+
176
+
177
+ # Create a SageMaker client
178
+ sagemaker_client = boto3.client('sagemaker')
179
+ sagemaker_session = sagemaker.Session()
180
+
181
+ # Create a predictor object
182
+ predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',
183
+ sagemaker_session=sagemaker_session,
184
+ serializer=JSONSerializer(),
185
+ deserializer=JSONDeserializer())
186
+
187
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
188
+
189
+ # Create a docsearch object
190
+ docsearch = loadCleanDocsearch(embeddings)
191
+
192
+ # Create messages list with system message
193
+ msgs = [{}]
194
+
195
+
196
+ with gr.Blocks() as demo:
197
+ gr.HTML("<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />")
198
+ gr.Markdown("## DSS LLM Demo: Chat with Llama 2")
199
+
200
+ with gr.Column():
201
+ chatbot = gr.Chatbot()
202
+
203
+ with gr.Row():
204
+ with gr.Column():
205
+ newMsg = gr.Textbox(label="New Message Box", placeholder="New Message", show_label=False)
206
+ with gr.Column():
207
+ with gr.Row():
208
+ submit = gr.Button("Submit")
209
+ clear = gr.Button("Clear")
210
+ with gr.Row():
211
+ with gr.Column():
212
+ newSRC = gr.Textbox(label="New source link/path Box", placeholder="New source link/path", show_label=False)
213
+ with gr.Column():
214
+ with gr.Row():
215
+ addURL = gr.Button("Add URL Source")
216
+ addPDF = gr.Button("Add PDF Source")
217
+ reset = gr.Button("Reset Sources")
218
+
219
+ submit.click(getPrediction, [newMsg], [chatbot, newMsg])
220
+ clear.click(clearStuff, None, chatbot, queue=False)
221
+
222
+ addURL.click(addURLsource, newSRC, [newSRC, chatbot])
223
+ addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])
224
+ reset.click(resetDocsearch, None, chatbot)
225
+
226
+ gr.Markdown("""*Note:
227
+
228
+ To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.
229
+
230
+ To add a PDF source, place a relative file path in the bottom textbox and click the 'Add PDF Source' button.
231
+
232
+ The database for contextualization includes 8 public DSS website articles upon initialization.
233
+
234
+ When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)*""")
235
+
236
+
237
+ demo.queue()
238
+ demo.launch(share=True)
239
+
240
+
241
+
.virtual_documents/llama2_gradio_v0.4_s3.ipynb ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import boto3
2
+ import sagemaker
3
+ from sagemaker.predictor import Predictor
4
+ from sagemaker.serializers import JSONSerializer
5
+ from sagemaker.deserializers import JSONDeserializer
6
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
7
+ from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader
8
+ from langchain.document_loaders.csv_loader import CSVLoader
9
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
10
+ from langchain.vectorstores import Chroma
11
+ import json
12
+ import gradio as gr
13
+
14
+
15
+ def loadCleanDocsearch(embeddings):
16
+ print("Getting fresh docsearch...")
17
+
18
+ # define URL sources with some stock articles from public DSS w
19
+ urls = [
20
+ 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',
21
+ 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',
22
+ 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',
23
+ 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'
24
+ ]
25
+
26
+ # load and split
27
+ loaders = UnstructuredURLLoader(urls=urls)
28
+ data = loaders.load()
29
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
30
+ texts = text_splitter.split_documents(data)
31
+ print("Sources split into the following number of \"texts\":", len(texts))
32
+
33
+ # get object
34
+ docsearch = Chroma.from_texts([t.page_content for t in texts],
35
+ metadatas=[{"src": "DSS"} for t in texts],
36
+ embedding=embeddings)
37
+ print("Done getting fresh docsearch.")
38
+
39
+ return docsearch
40
+
41
+ def resetDocsearch():
42
+ global docsearch
43
+
44
+ foreignIDs = docsearch.get(where= {"src":"foreign"})['ids']
45
+
46
+ if foreignIDs != []:
47
+ docsearch.delete(ids=foreignIDs)
48
+
49
+ clearStuff()
50
+
51
+ def addURLsource(url):
52
+ print("Adding new source...")
53
+
54
+ global docsearch
55
+
56
+ # load and split
57
+ loaders = UnstructuredURLLoader(urls=[url])
58
+ data = loaders.load()
59
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
60
+ texts = text_splitter.split_documents(data)
61
+ print("New source split into the following number of \"texts\":", len(texts))
62
+
63
+ # add new sources
64
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
65
+
66
+ # restart convo, as the old messages confuse the AI
67
+ clearStuff()
68
+
69
+ print("Done adding new source.")
70
+
71
+ return None, None
72
+
73
+ def addCSVsource(url):
74
+ print("Adding new source...")
75
+
76
+ global docsearch
77
+
78
+ # load and split
79
+ loaders = CSVLoader(urls=[url])
80
+ data = loaders.load()
81
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
82
+ texts = text_splitter.split_documents(data)
83
+ print("New source split into the following number of \"texts\":", len(texts))
84
+
85
+ # add new sources
86
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
87
+
88
+ # restart convo, as the old messages confuse the AI
89
+ clearStuff()
90
+
91
+ print("Done adding new source.")
92
+
93
+ return None, None
94
+
95
+ def addPDFsource(url):
96
+ print("Adding new source...")
97
+
98
+ global docsearch
99
+
100
+ # load and split
101
+ loaders = UnstructuredPDFLoader(url)
102
+ data = loaders.load()
103
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
104
+ texts = text_splitter.split_documents(data)
105
+ print("New source split into the following number of \"texts\":", len(texts))
106
+
107
+ # add new sources
108
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
109
+
110
+ # restart convo, as the old messages confuse the AI
111
+ clearStuff()
112
+
113
+ print("Done adding new source.")
114
+
115
+ return None, None
116
+
117
+ def msgs2chatbot(msgs):
118
+ # the gradio chatbot object is used to display the conversation
119
+ # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message
120
+ chatbot = []
121
+
122
+ for msg in msgs:
123
+ if msg['role'] == 'user':
124
+ chatbot.append([msg['content'], ""])
125
+ elif msg['role'] == 'assistant':
126
+ chatbot[-1][1] = msg['content']
127
+
128
+ return chatbot
129
+
130
+ def getPrediction(newMsg):
131
+ global msgs
132
+ global docsearch
133
+ global predictor
134
+
135
+ # add new message to msgs object
136
+ msgs.append({"role":"user", "content": newMsg})
137
+
138
+ # edit system message to include the correct context
139
+ msgs[0] = {"role": "system",
140
+ "content": f"""
141
+ You are a helpful AI assistant.
142
+ Use your knowledge to answer the user's question if they asked a question.
143
+ If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.
144
+ DO NOT use phrases like "Based on the information provided" or other similar phrases.
145
+ Refer to the information provided below as "your knowledge".
146
+ State all answers as if they are ground truth, DO NOT mention where you got the information.
147
+
148
+ YOUR KNOWLEDGE: {" ".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}"""}
149
+
150
+ # get response from endpoint
151
+
152
+ responseObject = predictor.predict({"inputs": [msgs],
153
+ "parameters": {"max_new_tokens": 750, "top_p": 0.9, "temperature": 0.5}},
154
+ initial_args={'CustomAttributes': "accept_eula=true"})
155
+ # responseObject = predictor.predict(payload, custom_attributes="accept_eula=true")
156
+
157
+
158
+ responseMsg = responseObject[0]['generation']['content'].strip()
159
+
160
+ # add response to msgs object
161
+ msgs.append({"role":"assistant", "content": responseMsg})
162
+
163
+ # print msgs object for debugging
164
+ print(msgs)
165
+
166
+ # convert msgs to chatbot object to be displayed
167
+ chatbot = msgs2chatbot(msgs)
168
+
169
+ return chatbot, ""
170
+
171
+ def clearStuff():
172
+ global msgs
173
+ msgs = [{}]
174
+ return None
175
+
176
+
177
+ # Create a SageMaker client
178
+ sagemaker_client = boto3.client('sagemaker')
179
+ sagemaker_session = sagemaker.Session()
180
+
181
+ # Create a predictor object
182
+ predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',
183
+ sagemaker_session=sagemaker_session,
184
+ serializer=JSONSerializer(),
185
+ deserializer=JSONDeserializer())
186
+
187
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
188
+
189
+ # Create a docsearch object
190
+ docsearch = loadCleanDocsearch(embeddings)
191
+
192
+ # Create messages list with system message
193
+ msgs = [{}]
194
+
195
+
196
+ with gr.Blocks() as demo:
197
+ gr.HTML("<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />")
198
+ gr.Markdown("## DSS LLM Demo: Chat with Llama 2")
199
+
200
+ with gr.Column():
201
+ chatbot = gr.Chatbot()
202
+
203
+ with gr.Row():
204
+ with gr.Column():
205
+ newMsg = gr.Textbox(label="New Message Box", placeholder="New Message", show_label=False)
206
+ with gr.Column():
207
+ with gr.Row():
208
+ submit = gr.Button("Submit")
209
+ clear = gr.Button("Clear")
210
+ with gr.Row():
211
+ with gr.Column():
212
+ newSRC = gr.Textbox(label="New source link/path Box", placeholder="New source link/path", show_label=False)
213
+ with gr.Column():
214
+ with gr.Row():
215
+ addURL = gr.Button("Add URL Source")
216
+ addPDF = gr.Button("Add PDF Source")
217
+ reset = gr.Button("Reset Sources")
218
+
219
+ submit.click(getPrediction, [newMsg], [chatbot, newMsg])
220
+ clear.click(clearStuff, None, chatbot, queue=False)
221
+
222
+ addURL.click(addURLsource, newSRC, [newSRC, chatbot])
223
+ addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])
224
+ reset.click(resetDocsearch, None, chatbot)
225
+
226
+ gr.Markdown("""*Note:
227
+
228
+ To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.
229
+
230
+ To add a PDF source, place a relative file path in the bottom textbox and click the 'Add PDF Source' button.
231
+
232
+ The database for contextualization includes 8 public DSS website articles upon initialization.
233
+
234
+ When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)*""")
235
+
236
+
237
+ demo.queue()
238
+ demo.launch(share=True)
239
+
240
+
241
+
DSS_proto.ipynb ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "fb4f9384-be8e-488a-aa51-b56b27c71213",
6
+ "metadata": {
7
+ "tags": []
8
+ },
9
+ "source": [
10
+ "## 1. Set up Sagemaker\n",
11
+ "*Explain more later...*"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "id": "ea107aa6-376e-4364-bceb-50aca9f30b74",
18
+ "metadata": {},
19
+ "outputs": [],
20
+ "source": [
21
+ "response = client.create_presigned_notebook_instance_url(\n",
22
+ " NotebookInstanceName='string',\n",
23
+ " SessionExpirationDurationInSeconds=123\n",
24
+ ")"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "execution_count": 4,
30
+ "id": "ac706b50-8413-42ef-b5a7-5906f7f5cdf5",
31
+ "metadata": {
32
+ "tags": []
33
+ },
34
+ "outputs": [
35
+ {
36
+ "name": "stdout",
37
+ "output_type": "stream",
38
+ "text": [
39
+ "arn:aws:iam::907929678403:role/service-role/AmazonSageMaker-ExecutionRole-20230621T132010\n"
40
+ ]
41
+ }
42
+ ],
43
+ "source": [
44
+ "import json\n",
45
+ "import sagemaker\n",
46
+ "from sagemaker.huggingface import get_huggingface_llm_image_uri\n",
47
+ "from sagemaker.huggingface import HuggingFaceModel\n",
48
+ "\n",
49
+ "# retrieve the llm image uri\n",
50
+ "llm_image = get_huggingface_llm_image_uri(\n",
51
+ " \"huggingface\",\n",
52
+ " version=\"0.8.2\"\n",
53
+ ")\n",
54
+ "\n",
55
+ "# Define Model and Endpoint configuration parameter\n",
56
+ "role = sagemaker.get_execution_role()\n",
57
+ "print(role)\n",
58
+ "endpoint_name = \"falcon-40b-instruct-demo\"\n",
59
+ "aws_region = \"us-east-1\"\n",
60
+ "hf_model_id = \"tiiuae/falcon-40b-instruct\" # model id from huggingface.co/models\n",
61
+ "instance_type = \"ml.g5.12xlarge\" # instance type to use for deployment\n",
62
+ "number_of_gpu = 4 # number of gpus to use for inference and tensor parallelism\n",
63
+ "health_check_timeout = 600 # Increase the timeout for the health check to 5 minutes for downloading the model\n"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "execution_count": 5,
69
+ "id": "2ce504d1-0bc3-43ce-bb39-b925a59718cc",
70
+ "metadata": {
71
+ "tags": []
72
+ },
73
+ "outputs": [],
74
+ "source": [
75
+ "# create HuggingFaceModel with the image uri\n",
76
+ "llm_model = HuggingFaceModel(\n",
77
+ " role=role,\n",
78
+ " image_uri=llm_image,\n",
79
+ " env={\n",
80
+ " 'HF_MODEL_ID': hf_model_id,\n",
81
+ " # 'HF_MODEL_QUANTIZE': \"bitsandbytes\", # comment in to quantize\n",
82
+ " 'SM_NUM_GPUS': json.dumps(number_of_gpu),\n",
83
+ " 'MAX_INPUT_LENGTH': json.dumps(1024), # Max length of input text\n",
84
+ " 'MAX_TOTAL_TOKENS': json.dumps(2048), # Max length of the generation (including input text)\n",
85
+ " }\n",
86
+ ")"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": 6,
92
+ "id": "00664be7-3d08-4c68-9048-ba1e602c44c2",
93
+ "metadata": {
94
+ "tags": []
95
+ },
96
+ "outputs": [
97
+ {
98
+ "ename": "ResourceLimitExceeded",
99
+ "evalue": "An error occurred (ResourceLimitExceeded) when calling the CreateEndpoint operation: The account-level service limit 'ml.g5.12xlarge for endpoint usage' is 2 Instances, with current utilization of 2 Instances and a request delta of 1 Instances. Please use AWS Service Quotas to request an increase for this quota. If AWS Service Quotas is not available, contact AWS support to request an increase for this quota.",
100
+ "output_type": "error",
101
+ "traceback": [
102
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
103
+ "\u001b[0;31mResourceLimitExceeded\u001b[0m Traceback (most recent call last)",
104
+ "Cell \u001b[0;32mIn[6], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m llm \u001b[38;5;241m=\u001b[39m \u001b[43mllm_model\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdeploy\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2\u001b[0m \u001b[43m \u001b[49m\u001b[43minitial_instance_count\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3\u001b[0m \u001b[43m \u001b[49m\u001b[43minstance_type\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minstance_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mhealth_check_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m)\u001b[49m\n",
105
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/huggingface/model.py:311\u001b[0m, in \u001b[0;36mHuggingFaceModel.deploy\u001b[0;34m(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, async_inference_config, serverless_inference_config, volume_size, model_data_download_timeout, container_startup_health_check_timeout, inference_recommendation_id, explainer_config, **kwargs)\u001b[0m\n\u001b[1;32m 305\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mimage_uri \u001b[38;5;129;01mand\u001b[39;00m instance_type \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m instance_type\u001b[38;5;241m.\u001b[39mstartswith(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mml.inf\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[1;32m 306\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mimage_uri \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mserving_image_uri(\n\u001b[1;32m 307\u001b[0m region_name\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session\u001b[38;5;241m.\u001b[39mboto_session\u001b[38;5;241m.\u001b[39mregion_name,\n\u001b[1;32m 308\u001b[0m instance_type\u001b[38;5;241m=\u001b[39minstance_type,\n\u001b[1;32m 309\u001b[0m )\n\u001b[0;32m--> 311\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mHuggingFaceModel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdeploy\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 312\u001b[0m \u001b[43m \u001b[49m\u001b[43minitial_instance_count\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 313\u001b[0m \u001b[43m \u001b[49m\u001b[43minstance_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 314\u001b[0m \u001b[43m \u001b[49m\u001b[43mserializer\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 315\u001b[0m \u001b[43m \u001b[49m\u001b[43mdeserializer\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 316\u001b[0m \u001b[43m \u001b[49m\u001b[43maccelerator_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 317\u001b[0m \u001b[43m \u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 318\u001b[0m \u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 319\u001b[0m \u001b[43m \u001b[49m\u001b[43mkms_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 320\u001b[0m \u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 321\u001b[0m \u001b[43m \u001b[49m\u001b[43mdata_capture_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 322\u001b[0m \u001b[43m \u001b[49m\u001b[43masync_inference_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 323\u001b[0m \u001b[43m \u001b[49m\u001b[43mserverless_inference_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 324\u001b[0m \u001b[43m \u001b[49m\u001b[43mvolume_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mvolume_size\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 325\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel_data_download_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel_data_download_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 326\u001b[0m \u001b[43m \u001b[49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 327\u001b[0m \u001b[43m \u001b[49m\u001b[43minference_recommendation_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minference_recommendation_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 328\u001b[0m \u001b[43m \u001b[49m\u001b[43mexplainer_config\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mexplainer_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 329\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
106
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/model.py:1347\u001b[0m, in \u001b[0;36mModel.deploy\u001b[0;34m(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, async_inference_config, serverless_inference_config, volume_size, model_data_download_timeout, container_startup_health_check_timeout, inference_recommendation_id, explainer_config, **kwargs)\u001b[0m\n\u001b[1;32m 1344\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_explainer_enabled:\n\u001b[1;32m 1345\u001b[0m explainer_config_dict \u001b[38;5;241m=\u001b[39m explainer_config\u001b[38;5;241m.\u001b[39m_to_request_dict()\n\u001b[0;32m-> 1347\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_session\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mendpoint_from_production_variants\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1348\u001b[0m \u001b[43m \u001b[49m\u001b[43mname\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1349\u001b[0m \u001b[43m \u001b[49m\u001b[43mproduction_variants\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m[\u001b[49m\u001b[43mproduction_variant\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1350\u001b[0m \u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1351\u001b[0m \u001b[43m \u001b[49m\u001b[43mkms_key\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mkms_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1352\u001b[0m \u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mwait\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1353\u001b[0m \u001b[43m \u001b[49m\u001b[43mdata_capture_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdata_capture_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1354\u001b[0m \u001b[43m \u001b[49m\u001b[43mexplainer_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mexplainer_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1355\u001b[0m \u001b[43m \u001b[49m\u001b[43masync_inference_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43masync_inference_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1356\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1358\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpredictor_cls:\n\u001b[1;32m 1359\u001b[0m predictor \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpredictor_cls(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mendpoint_name, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session)\n",
107
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/session.py:4641\u001b[0m, in \u001b[0;36mSession.endpoint_from_production_variants\u001b[0;34m(self, name, production_variants, tags, kms_key, wait, data_capture_config_dict, async_inference_config_dict, explainer_config_dict)\u001b[0m\n\u001b[1;32m 4638\u001b[0m LOGGER\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCreating endpoint-config with name \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, name)\n\u001b[1;32m 4639\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_client\u001b[38;5;241m.\u001b[39mcreate_endpoint_config(\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mconfig_options)\n\u001b[0;32m-> 4641\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate_endpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mwait\u001b[49m\u001b[43m)\u001b[49m\n",
108
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/sagemaker/session.py:4030\u001b[0m, in \u001b[0;36mSession.create_endpoint\u001b[0;34m(self, endpoint_name, config_name, tags, wait)\u001b[0m\n\u001b[1;32m 4027\u001b[0m tags \u001b[38;5;241m=\u001b[39m tags \u001b[38;5;129;01mor\u001b[39;00m []\n\u001b[1;32m 4028\u001b[0m tags \u001b[38;5;241m=\u001b[39m _append_project_tags(tags)\n\u001b[0;32m-> 4030\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_client\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate_endpoint\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4031\u001b[0m \u001b[43m \u001b[49m\u001b[43mEndpointName\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mEndpointConfigName\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mconfig_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mTags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\n\u001b[1;32m 4032\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 4033\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m wait:\n\u001b[1;32m 4034\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mwait_for_endpoint(endpoint_name)\n",
109
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:530\u001b[0m, in \u001b[0;36mClientCreator._create_api_method.<locals>._api_call\u001b[0;34m(self, *args, **kwargs)\u001b[0m\n\u001b[1;32m 526\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\n\u001b[1;32m 527\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpy_operation_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m() only accepts keyword arguments.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 528\u001b[0m )\n\u001b[1;32m 529\u001b[0m \u001b[38;5;66;03m# The \"self\" in this scope is referring to the BaseClient.\u001b[39;00m\n\u001b[0;32m--> 530\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_make_api_call\u001b[49m\u001b[43m(\u001b[49m\u001b[43moperation_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
110
+ "File \u001b[0;32m~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/botocore/client.py:964\u001b[0m, in \u001b[0;36mBaseClient._make_api_call\u001b[0;34m(self, operation_name, api_params)\u001b[0m\n\u001b[1;32m 962\u001b[0m error_code \u001b[38;5;241m=\u001b[39m parsed_response\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError\u001b[39m\u001b[38;5;124m\"\u001b[39m, {})\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCode\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 963\u001b[0m error_class \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mexceptions\u001b[38;5;241m.\u001b[39mfrom_code(error_code)\n\u001b[0;32m--> 964\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m error_class(parsed_response, operation_name)\n\u001b[1;32m 965\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 966\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m parsed_response\n",
111
+ "\u001b[0;31mResourceLimitExceeded\u001b[0m: An error occurred (ResourceLimitExceeded) when calling the CreateEndpoint operation: The account-level service limit 'ml.g5.12xlarge for endpoint usage' is 2 Instances, with current utilization of 2 Instances and a request delta of 1 Instances. Please use AWS Service Quotas to request an increase for this quota. If AWS Service Quotas is not available, contact AWS support to request an increase for this quota."
112
+ ]
113
+ }
114
+ ],
115
+ "source": [
116
+ "llm = llm_model.deploy(\n",
117
+ " initial_instance_count=1,\n",
118
+ " instance_type=instance_type,\n",
119
+ " container_startup_health_check_timeout=health_check_timeout,\n",
120
+ " endpoint_name=endpoint_name\n",
121
+ ")"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "50f556f8-06b4-450e-9db3-9bc9c979e8ab",
128
+ "metadata": {
129
+ "tags": []
130
+ },
131
+ "outputs": [],
132
+ "source": [
133
+ "llm2.delete_endpoint()"
134
+ ]
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "execution_count": null,
139
+ "id": "c341f368-a9e7-441c-886e-0576c3f2f432",
140
+ "metadata": {
141
+ "tags": []
142
+ },
143
+ "outputs": [],
144
+ "source": [
145
+ "\n",
146
+ "from langchain.chains.question_answering import load_qa_chain\n",
147
+ "from langchain.memory import ConversationBufferMemory\n",
148
+ "from langchain import PromptTemplate\n",
149
+ "from typing import Dict\n",
150
+ "\n",
151
+ "class ContentHandler(LLMContentHandler):\n",
152
+ " content_type = \"application/json\"\n",
153
+ " accepts = \"application/json\"\n",
154
+ " len_prompt = 0\n",
155
+ "\n",
156
+ " def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:\n",
157
+ " self.len_prompt = len(prompt)\n",
158
+ " input_str = json.dumps(\n",
159
+ " {\"inputs\": prompt,\n",
160
+ " \"parameters\": {\n",
161
+ " \"do_sample\": True,\n",
162
+ " \"top_p\": 0.9,\n",
163
+ " \"temperature\": 0.8,\n",
164
+ " \"max_new_tokens\": 1024,\n",
165
+ " \"repetition_penalty\": 1.03,\n",
166
+ " \"stop\": [\"\\n\\n\", \"Human:\", \"<|endoftext|>\", \"</s>\"]\n",
167
+ " }})\n",
168
+ " return input_str.encode('utf-8')\n",
169
+ "\n",
170
+ " def transform_output(self, output: bytes) -> str:\n",
171
+ " response_json = output.read()\n",
172
+ " res = json.loads(response_json)\n",
173
+ " ans = res[0]['generated_text'][self.len_prompt:]\n",
174
+ " ans = ans[:ans.rfind(\"Human\")].strip()\n",
175
+ " return ans\n",
176
+ "\n",
177
+ "\n",
178
+ "content_handler = ContentHandler()\n",
179
+ "\n",
180
+ "\n",
181
+ "prompt = PromptTemplate(\n",
182
+ " input_variables=[\"history\", \"context\", \"new_message\"],\n",
183
+ " template=\"\"\"\n",
184
+ "The following is a given context and history of a conversation between a human and a helpful AI assistant. \n",
185
+ "The AI assistant answers the human's messages with full, informational responses by inferring on the information given in the context, but does not extrapolate or hallucinate any facts that are not given.\n",
186
+ "When answering questions with unclear answers, the AI assistant qualifies its responses as such.\n",
187
+ "The AI assistant pretends it is also human and that the context is objectively true and well-known and therefore avoids mentioning the context as a source.\n",
188
+ "\n",
189
+ "Context: {context}\n",
190
+ "\n",
191
+ "{history}\n",
192
+ "Human: {new_message}\n",
193
+ "AI:\"\"\")\n",
194
+ "\n",
195
+ "def load_chain():\n",
196
+ " llm = SagemakerEndpoint(\n",
197
+ " endpoint_name=endpoint_name,\n",
198
+ " region_name=aws_region,\n",
199
+ " content_handler=content_handler\n",
200
+ " )\n",
201
+ " chain = load_qa_chain(llm=llm, chain_type=\"stuff\", verbose=True, memory=ConversationBufferMemory(memory_key=\"history\", input_key=\"new_message\"), prompt=prompt)\n",
202
+ " return chain\n",
203
+ "\n",
204
+ "\n",
205
+ "dachain = load_chain()"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": null,
211
+ "id": "b0a557a0-ca6d-45db-97b4-f89317a5e500",
212
+ "metadata": {
213
+ "tags": []
214
+ },
215
+ "outputs": [],
216
+ "source": [
217
+ "query = \"What is Becton?\"\n",
218
+ "dachain({\"input_documents\": docsearch.similarity_search(query, k=3), \"new_message\": query}, return_only_outputs=True)['output_text'].strip()"
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "markdown",
223
+ "id": "c4ac2fca-820b-412d-9e90-47848e046236",
224
+ "metadata": {},
225
+ "source": [
226
+ "## Load DSS Website Data into ChromaDB\n",
227
+ "`urls` object defines what URLs are to be considered in the context database."
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": null,
233
+ "id": "c596a7a6-cca1-46c5-a914-e8b5ce9eba17",
234
+ "metadata": {
235
+ "tags": []
236
+ },
237
+ "outputs": [],
238
+ "source": [
239
+ "from langchain.document_loaders import UnstructuredURLLoader\n",
240
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
241
+ "from langchain.vectorstores import Chroma\n",
242
+ "from langchain.embeddings import HuggingFaceInstructEmbeddings\n",
243
+ "\n",
244
+ "# define URL sources\n",
245
+ "urls = [\n",
246
+ " 'https://www.dssinc.com/blog/2022/6/21/suicide-prevention-manager-enabling-the-veterans-affairs-to-achieve-high-reliability-in-suicide-risk-identification',\n",
247
+ " 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development', \n",
248
+ " 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',\n",
249
+ " 'https://www.dssinc.com/blog/2023/5/24/supporting-the-vas-high-reliability-organization-journey-through-suicide-prevention',\n",
250
+ " 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',\n",
251
+ " 'https://www.dssinc.com/blog/2022/9/21/dss-inc-chosen-for-phase-two-of-mission-daybreak-vas-suicide-prevention-challenge',\n",
252
+ " 'https://www.dssinc.com/blog/2022/9/19/crescenz-va-medical-center-cmcvamc-deploys-the-dss-iconic-data-patient-case-manager-pcm-solution',\n",
253
+ " 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization']\n",
254
+ "\n",
255
+ "# load and split\n",
256
+ "loaders = UnstructuredURLLoader(urls=urls)\n",
257
+ "data = loaders.load()\n",
258
+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
259
+ "texts = text_splitter.split_documents(data)\n",
260
+ "print(\"Sources split into the following number of \\\"texts\\\":\", len(texts))\n",
261
+ "\n",
262
+ "# load embedding model\n",
263
+ "print(\"Loading embedding model...\")\n",
264
+ "embeddings = HuggingFaceInstructEmbeddings(model_name=\"hkunlp/instructor-xl\")\n",
265
+ "\n",
266
+ "docsearch = Chroma.from_texts([t.page_content for t in texts], embeddings)"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": null,
272
+ "id": "6fe72b28-0d34-47c5-82f5-7318576e4ec8",
273
+ "metadata": {},
274
+ "outputs": [],
275
+ "source": [
276
+ "print(\"Getting AI response... @ \", datetime.datetime.now().strftime(\"%H:%M:%S\"))\n",
277
+ "print(chain({\"input_documents\": docsearch.similarity_search(query, k=3), \"new_message\": query}, return_only_outputs=True)['output_text'].strip())"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "execution_count": null,
283
+ "id": "f9c38a37-9aa0-4584-8b06-cee2932d14cf",
284
+ "metadata": {
285
+ "tags": []
286
+ },
287
+ "outputs": [],
288
+ "source": [
289
+ "\n",
290
+ "llm2.delete_endpoint()"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "code",
295
+ "execution_count": null,
296
+ "id": "881f2cb5-41c5-4fd2-b942-d3c289dda758",
297
+ "metadata": {},
298
+ "outputs": [],
299
+ "source": []
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "execution_count": null,
304
+ "id": "202caf50-c00a-4555-8150-4fc7a779aa0a",
305
+ "metadata": {
306
+ "tags": []
307
+ },
308
+ "outputs": [],
309
+ "source": [
310
+ "from sagemaker.predictor import Predictor\n",
311
+ "\n",
312
+ "llm2 = Predictor(endpoint_name)"
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "execution_count": null,
318
+ "id": "31f54a95-0324-4deb-be0e-89c453004f6c",
319
+ "metadata": {
320
+ "tags": []
321
+ },
322
+ "outputs": [],
323
+ "source": [
324
+ "dom = \"d-bipui5yzbvlc\"\n",
325
+ "print(f'https://{dom}.studio.{aws_region}.sagemaker.aws/studiolab/default/jupyter/proxy/6006/')"
326
+ ]
327
+ }
328
+ ],
329
+ "metadata": {
330
+ "kernelspec": {
331
+ "display_name": "conda_pytorch_p310",
332
+ "language": "python",
333
+ "name": "conda_pytorch_p310"
334
+ },
335
+ "language_info": {
336
+ "codemirror_mode": {
337
+ "name": "ipython",
338
+ "version": 3
339
+ },
340
+ "file_extension": ".py",
341
+ "mimetype": "text/x-python",
342
+ "name": "python",
343
+ "nbconvert_exporter": "python",
344
+ "pygments_lexer": "ipython3",
345
+ "version": "3.10.10"
346
+ }
347
+ },
348
+ "nbformat": 4,
349
+ "nbformat_minor": 5
350
+ }
Mission.pdf ADDED
Binary file (356 kB). View file
 
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Llm
3
- emoji: 📈
4
- colorFrom: indigo
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 3.40.1
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: llm
3
+ app_file: demo_app.py
 
 
4
  sdk: gradio
5
  sdk_version: 3.40.1
 
 
6
  ---
 
 
Untitled.ipynb ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 5,
6
+ "id": "d08fefa9-5733-47d7-80e1-9535b7102e90",
7
+ "metadata": {
8
+ "tags": []
9
+ },
10
+ "outputs": [
11
+ {
12
+ "name": "stdout",
13
+ "output_type": "stream",
14
+ "text": [
15
+ "------------------------------------------------*"
16
+ ]
17
+ },
18
+ {
19
+ "ename": "UnexpectedStatusException",
20
+ "evalue": "Error hosting endpoint huggingface-pytorch-tgi-inference-2023-08-07-22-35-09-932: Failed. Reason: The primary container for production variant AllTraffic did not pass the ping health check. Please check CloudWatch logs for this endpoint..",
21
+ "output_type": "error",
22
+ "traceback": [
23
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
24
+ "\u001b[0;31mUnexpectedStatusException\u001b[0m Traceback (most recent call last)",
25
+ "Cell \u001b[0;32mIn[5], line 29\u001b[0m\n\u001b[1;32m 22\u001b[0m huggingface_model \u001b[38;5;241m=\u001b[39m HuggingFaceModel(\n\u001b[1;32m 23\u001b[0m image_uri\u001b[38;5;241m=\u001b[39mget_huggingface_llm_image_uri(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhuggingface\u001b[39m\u001b[38;5;124m\"\u001b[39m,version\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m0.8.2\u001b[39m\u001b[38;5;124m\"\u001b[39m),\n\u001b[1;32m 24\u001b[0m env\u001b[38;5;241m=\u001b[39mhub,\n\u001b[1;32m 25\u001b[0m role\u001b[38;5;241m=\u001b[39mrole, \n\u001b[1;32m 26\u001b[0m )\n\u001b[1;32m 28\u001b[0m \u001b[38;5;66;03m# deploy model to SageMaker Inference\u001b[39;00m\n\u001b[0;32m---> 29\u001b[0m predictor \u001b[38;5;241m=\u001b[39m \u001b[43mhuggingface_model\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdeploy\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 30\u001b[0m \u001b[43m \u001b[49m\u001b[43minitial_instance_count\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 31\u001b[0m \u001b[43m \u001b[49m\u001b[43minstance_type\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mml.g5.4xlarge\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 32\u001b[0m \u001b[43m \u001b[49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m1200\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 33\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n",
26
+ "File \u001b[0;32m~/anaconda3/envs/python3/lib/python3.10/site-packages/sagemaker/huggingface/model.py:313\u001b[0m, in \u001b[0;36mHuggingFaceModel.deploy\u001b[0;34m(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, async_inference_config, serverless_inference_config, volume_size, model_data_download_timeout, container_startup_health_check_timeout, inference_recommendation_id, explainer_config, **kwargs)\u001b[0m\n\u001b[1;32m 306\u001b[0m inference_tool \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mneuron\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m instance_type\u001b[38;5;241m.\u001b[39mstartswith(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mml.inf1\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mneuronx\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 307\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mimage_uri \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mserving_image_uri(\n\u001b[1;32m 308\u001b[0m region_name\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session\u001b[38;5;241m.\u001b[39mboto_session\u001b[38;5;241m.\u001b[39mregion_name,\n\u001b[1;32m 309\u001b[0m instance_type\u001b[38;5;241m=\u001b[39minstance_type,\n\u001b[1;32m 310\u001b[0m inference_tool\u001b[38;5;241m=\u001b[39minference_tool,\n\u001b[1;32m 311\u001b[0m )\n\u001b[0;32m--> 313\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mHuggingFaceModel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdeploy\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 314\u001b[0m \u001b[43m \u001b[49m\u001b[43minitial_instance_count\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 315\u001b[0m \u001b[43m \u001b[49m\u001b[43minstance_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 316\u001b[0m \u001b[43m \u001b[49m\u001b[43mserializer\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 317\u001b[0m \u001b[43m \u001b[49m\u001b[43mdeserializer\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 318\u001b[0m \u001b[43m \u001b[49m\u001b[43maccelerator_type\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 319\u001b[0m \u001b[43m \u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 320\u001b[0m \u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 321\u001b[0m \u001b[43m \u001b[49m\u001b[43mkms_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 322\u001b[0m \u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 323\u001b[0m \u001b[43m \u001b[49m\u001b[43mdata_capture_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 324\u001b[0m \u001b[43m \u001b[49m\u001b[43masync_inference_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 325\u001b[0m \u001b[43m \u001b[49m\u001b[43mserverless_inference_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 326\u001b[0m \u001b[43m \u001b[49m\u001b[43mvolume_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mvolume_size\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 327\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel_data_download_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel_data_download_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 328\u001b[0m \u001b[43m \u001b[49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcontainer_startup_health_check_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 329\u001b[0m \u001b[43m \u001b[49m\u001b[43minference_recommendation_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minference_recommendation_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 330\u001b[0m \u001b[43m \u001b[49m\u001b[43mexplainer_config\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mexplainer_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 331\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
27
+ "File \u001b[0;32m~/anaconda3/envs/python3/lib/python3.10/site-packages/sagemaker/model.py:1406\u001b[0m, in \u001b[0;36mModel.deploy\u001b[0;34m(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, async_inference_config, serverless_inference_config, volume_size, model_data_download_timeout, container_startup_health_check_timeout, inference_recommendation_id, explainer_config, **kwargs)\u001b[0m\n\u001b[1;32m 1403\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_explainer_enabled:\n\u001b[1;32m 1404\u001b[0m explainer_config_dict \u001b[38;5;241m=\u001b[39m explainer_config\u001b[38;5;241m.\u001b[39m_to_request_dict()\n\u001b[0;32m-> 1406\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msagemaker_session\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mendpoint_from_production_variants\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 1407\u001b[0m \u001b[43m \u001b[49m\u001b[43mname\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mendpoint_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1408\u001b[0m \u001b[43m \u001b[49m\u001b[43mproduction_variants\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m[\u001b[49m\u001b[43mproduction_variant\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1409\u001b[0m \u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtags\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1410\u001b[0m \u001b[43m \u001b[49m\u001b[43mkms_key\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mkms_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1411\u001b[0m \u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mwait\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1412\u001b[0m \u001b[43m \u001b[49m\u001b[43mdata_capture_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdata_capture_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1413\u001b[0m \u001b[43m \u001b[49m\u001b[43mexplainer_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mexplainer_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1414\u001b[0m \u001b[43m \u001b[49m\u001b[43masync_inference_config_dict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43masync_inference_config_dict\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 1415\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1417\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpredictor_cls:\n\u001b[1;32m 1418\u001b[0m predictor \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpredictor_cls(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mendpoint_name, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_session)\n",
28
+ "File \u001b[0;32m~/anaconda3/envs/python3/lib/python3.10/site-packages/sagemaker/session.py:4686\u001b[0m, in \u001b[0;36mSession.endpoint_from_production_variants\u001b[0;34m(self, name, production_variants, tags, kms_key, wait, data_capture_config_dict, async_inference_config_dict, explainer_config_dict)\u001b[0m\n\u001b[1;32m 4683\u001b[0m LOGGER\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCreating endpoint-config with name \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, name)\n\u001b[1;32m 4684\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_client\u001b[38;5;241m.\u001b[39mcreate_endpoint_config(\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mconfig_options)\n\u001b[0;32m-> 4686\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate_endpoint\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4687\u001b[0m \u001b[43m \u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtags\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mendpoint_tags\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mwait\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mwait\u001b[49m\n\u001b[1;32m 4688\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
29
+ "File \u001b[0;32m~/anaconda3/envs/python3/lib/python3.10/site-packages/sagemaker/session.py:4066\u001b[0m, in \u001b[0;36mSession.create_endpoint\u001b[0;34m(self, endpoint_name, config_name, tags, wait)\u001b[0m\n\u001b[1;32m 4062\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msagemaker_client\u001b[38;5;241m.\u001b[39mcreate_endpoint(\n\u001b[1;32m 4063\u001b[0m EndpointName\u001b[38;5;241m=\u001b[39mendpoint_name, EndpointConfigName\u001b[38;5;241m=\u001b[39mconfig_name, Tags\u001b[38;5;241m=\u001b[39mtags\n\u001b[1;32m 4064\u001b[0m )\n\u001b[1;32m 4065\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m wait:\n\u001b[0;32m-> 4066\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mwait_for_endpoint\u001b[49m\u001b[43m(\u001b[49m\u001b[43mendpoint_name\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 4067\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m endpoint_name\n",
30
+ "File \u001b[0;32m~/anaconda3/envs/python3/lib/python3.10/site-packages/sagemaker/session.py:4418\u001b[0m, in \u001b[0;36mSession.wait_for_endpoint\u001b[0;34m(self, endpoint, poll)\u001b[0m\n\u001b[1;32m 4412\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCapacityError\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mstr\u001b[39m(reason):\n\u001b[1;32m 4413\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m exceptions\u001b[38;5;241m.\u001b[39mCapacityError(\n\u001b[1;32m 4414\u001b[0m message\u001b[38;5;241m=\u001b[39mmessage,\n\u001b[1;32m 4415\u001b[0m allowed_statuses\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInService\u001b[39m\u001b[38;5;124m\"\u001b[39m],\n\u001b[1;32m 4416\u001b[0m actual_status\u001b[38;5;241m=\u001b[39mstatus,\n\u001b[1;32m 4417\u001b[0m )\n\u001b[0;32m-> 4418\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m exceptions\u001b[38;5;241m.\u001b[39mUnexpectedStatusException(\n\u001b[1;32m 4419\u001b[0m message\u001b[38;5;241m=\u001b[39mmessage,\n\u001b[1;32m 4420\u001b[0m allowed_statuses\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInService\u001b[39m\u001b[38;5;124m\"\u001b[39m],\n\u001b[1;32m 4421\u001b[0m actual_status\u001b[38;5;241m=\u001b[39mstatus,\n\u001b[1;32m 4422\u001b[0m )\n\u001b[1;32m 4423\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m desc\n",
31
+ "\u001b[0;31mUnexpectedStatusException\u001b[0m: Error hosting endpoint huggingface-pytorch-tgi-inference-2023-08-07-22-35-09-932: Failed. Reason: The primary container for production variant AllTraffic did not pass the ping health check. Please check CloudWatch logs for this endpoint.."
32
+ ]
33
+ }
34
+ ],
35
+ "source": [
36
+ "import json\n",
37
+ "import sagemaker\n",
38
+ "import boto3\n",
39
+ "from sagemaker.huggingface import HuggingFaceModel, get_huggingface_llm_image_uri\n",
40
+ "\n",
41
+ "try:\n",
42
+ " role = sagemaker.get_execution_role()\n",
43
+ "except ValueError:\n",
44
+ " iam = boto3.client('iam')\n",
45
+ " role = iam.get_role(RoleName='sagemaker_execution_role')['Role']['Arn']\n",
46
+ "\n",
47
+ "# Hub Model configuration. https://huggingface.co/models\n",
48
+ "hub = {\n",
49
+ " 'HF_MODEL_ID':'meta-llama/Llama-2-13b-chat-hf',\n",
50
+ " 'SM_NUM_GPUS': json.dumps(1),\n",
51
+ " 'HUGGING_FACE_HUB_TOKEN': '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'\n",
52
+ "}\n",
53
+ "\n",
54
+ "assert hub['HUGGING_FACE_HUB_TOKEN'] != '<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>', \"You have to provide a token.\"\n",
55
+ "\n",
56
+ "# create Hugging Face Model Class\n",
57
+ "huggingface_model = HuggingFaceModel(\n",
58
+ " image_uri=get_huggingface_llm_image_uri(\"huggingface\",version=\"0.8.2\"),\n",
59
+ " env=hub,\n",
60
+ " role=role, \n",
61
+ ")\n",
62
+ "\n",
63
+ "# deploy model to SageMaker Inference\n",
64
+ "predictor = huggingface_model.deploy(\n",
65
+ " initial_instance_count=1,\n",
66
+ " instance_type=\"ml.g5.4xlarge\",\n",
67
+ " container_startup_health_check_timeout=1200,\n",
68
+ " )\n",
69
+ " "
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "execution_count": null,
75
+ "id": "8e35b51f-6195-415a-a52f-3ac6d744bd01",
76
+ "metadata": {},
77
+ "outputs": [],
78
+ "source": [
79
+ "# send request\n",
80
+ "predictor.predict({\n",
81
+ " \"inputs\": \"My name is Julien and I like to\",\n",
82
+ "})"
83
+ ]
84
+ }
85
+ ],
86
+ "metadata": {
87
+ "kernelspec": {
88
+ "display_name": "conda_python3",
89
+ "language": "python",
90
+ "name": "conda_python3"
91
+ },
92
+ "language_info": {
93
+ "codemirror_mode": {
94
+ "name": "ipython",
95
+ "version": 3
96
+ },
97
+ "file_extension": ".py",
98
+ "mimetype": "text/x-python",
99
+ "name": "python",
100
+ "nbconvert_exporter": "python",
101
+ "pygments_lexer": "ipython3",
102
+ "version": "3.10.10"
103
+ }
104
+ },
105
+ "nbformat": 4,
106
+ "nbformat_minor": 5
107
+ }
Untitled1.ipynb ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 9,
6
+ "id": "7c544f15-74a0-4ef5-886a-cb62a756d7e5",
7
+ "metadata": {
8
+ "tags": []
9
+ },
10
+ "outputs": [
11
+ {
12
+ "ename": "SyntaxError",
13
+ "evalue": "invalid syntax (1681792056.py, line 2)",
14
+ "output_type": "error",
15
+ "traceback": [
16
+ "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_14850/1681792056.py\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m yum install aria2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
17
+ ]
18
+ }
19
+ ],
20
+ "source": [
21
+ "%cd /home/ec2-user/SageMaker\n",
22
+ "yum install aria2"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": 10,
28
+ "id": "d4caaebe-c5e7-422e-a1da-585166c6d67c",
29
+ "metadata": {
30
+ "tags": []
31
+ },
32
+ "outputs": [
33
+ {
34
+ "name": "stdout",
35
+ "output_type": "stream",
36
+ "text": [
37
+ "fatal: destination path 'text-generation-webui' already exists and is not an empty directory.\n",
38
+ "[Errno 2] No such file or directory: '/content/text-generation-webui'\n",
39
+ "/home/ec2-user/SageMaker\n",
40
+ "\u001b[31mERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'\u001b[0m\u001b[31m\n",
41
+ "\u001b[0m/bin/sh: aria2c: command not found\n",
42
+ "/bin/sh: aria2c: command not found\n",
43
+ "/bin/sh: aria2c: command not found\n",
44
+ "/bin/sh: aria2c: command not found\n",
45
+ "/bin/sh: aria2c: command not found\n",
46
+ "/bin/sh: aria2c: command not found\n",
47
+ "/bin/sh: aria2c: command not found\n",
48
+ "/bin/sh: aria2c: command not found\n",
49
+ "/bin/sh: aria2c: command not found\n",
50
+ "/home/ec2-user/SageMaker/text-generation-webui\n",
51
+ "Traceback (most recent call last):\n",
52
+ " File \"server.py\", line 12, in <module>\n",
53
+ " import gradio as gr\n",
54
+ "ModuleNotFoundError: No module named 'gradio'\n"
55
+ ]
56
+ }
57
+ ],
58
+ "source": [
59
+ "\n",
60
+ "\n",
61
+ "!git clone -b v1.8 https://github.com/camenduru/text-generation-webui\n",
62
+ "%cd /content/text-generation-webui\n",
63
+ "!pip install -r requirements.txt\n",
64
+ "\n",
65
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/resolve/main/model-00001-of-00003.safetensors -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o model-00001-of-00003.safetensors\n",
66
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/resolve/main/model-00002-of-00003.safetensors -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o model-00002-of-00003.safetensors\n",
67
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/resolve/main/model-00003-of-00003.safetensors -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o model-00003-of-00003.safetensors\n",
68
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/raw/main/model.safetensors.index.json -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o model.safetensors.index.json\n",
69
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/raw/main/special_tokens_map.json -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o special_tokens_map.json\n",
70
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/resolve/main/tokenizer.model -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o tokenizer.model\n",
71
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/raw/main/tokenizer_config.json -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o tokenizer_config.json\n",
72
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/raw/main/config.json -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o config.json\n",
73
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M https://huggingface.co/4bit/Llama-2-13b-chat-hf/raw/main/generation_config.json -d /content/text-generation-webui/models/Llama-2-13b-chat-hf -o generation_config.json\n",
74
+ "\n",
75
+ "%cd /home/ec2-user/SageMaker/text-generation-webui\n",
76
+ "!python server.py --share --chat --load-in-8bit --model /content/text-generation-webui/models/Llama-2-13b-chat-hf"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "execution_count": null,
82
+ "id": "65156833-73d0-474c-86db-876024f37dc9",
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": []
86
+ }
87
+ ],
88
+ "metadata": {
89
+ "kernelspec": {
90
+ "display_name": "conda_mxnet_p38",
91
+ "language": "python",
92
+ "name": "conda_mxnet_p38"
93
+ },
94
+ "language_info": {
95
+ "codemirror_mode": {
96
+ "name": "ipython",
97
+ "version": 3
98
+ },
99
+ "file_extension": ".py",
100
+ "mimetype": "text/x-python",
101
+ "name": "python",
102
+ "nbconvert_exporter": "python",
103
+ "pygments_lexer": "ipython3",
104
+ "version": "3.8.16"
105
+ }
106
+ },
107
+ "nbformat": 4,
108
+ "nbformat_minor": 5
109
+ }
demo_app.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import boto3
2
+ import sagemaker
3
+ from sagemaker.predictor import Predictor
4
+ from sagemaker.serializers import JSONSerializer
5
+ from sagemaker.deserializers import JSONDeserializer
6
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
7
+ from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader, S3FileLoader
8
+ from langchain.docstore.document import Document
9
+ from langchain.document_loaders.csv_loader import CSVLoader
10
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
11
+ from langchain.vectorstores import Chroma
12
+ import json
13
+ import gradio as gr
14
+
15
+ def loadCleanDocsearch(embeddings):
16
+ print("Getting fresh docsearch...")
17
+
18
+ # define URL sources with some stock articles from public DSS website
19
+ urls = [
20
+ 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',
21
+ 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',
22
+ 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',
23
+ 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'
24
+ ]
25
+
26
+ # load and split
27
+ loaders = UnstructuredURLLoader(urls=urls)
28
+ data = loaders.load()
29
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
30
+ texts = text_splitter.split_documents(data)
31
+ print("Sources split into the following number of \"texts\":", len(texts))
32
+
33
+ # get object
34
+ docsearch = Chroma.from_texts([t.page_content for t in texts],
35
+ metadatas=[{"src": "DSS"} for t in texts],
36
+ embedding=embeddings)
37
+ print("Done getting fresh docsearch.")
38
+
39
+ return docsearch
40
+
41
+ def resetDocsearch():
42
+ global docsearch
43
+
44
+ foreignIDs = docsearch.get(where= {"src":"foreign"})['ids']
45
+
46
+ if foreignIDs != []:
47
+ docsearch.delete(ids=foreignIDs)
48
+
49
+ clearStuff()
50
+
51
+
52
+ def addURLsource(url):
53
+ print("Adding new source...")
54
+
55
+ global docsearch
56
+
57
+ # load and split
58
+ loaders = UnstructuredURLLoader(urls=[url])
59
+ data = loaders.load()
60
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
61
+ texts = text_splitter.split_documents(data)
62
+ print("New source split into the following number of \"texts\":", len(texts))
63
+
64
+ # add new sources
65
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
66
+
67
+ # restart convo, as the old messages confuse the AI
68
+ clearStuff()
69
+
70
+ print("Done adding new source.")
71
+
72
+ return None, None
73
+
74
+ # def addCSVsource(url):
75
+ # print("Adding new source...")
76
+
77
+ # global docsearch
78
+
79
+ # # load and split
80
+ # loaders = CSVLoader(urls=[url])
81
+ # data = loaders.load()
82
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
83
+ # texts = text_splitter.split_documents(data)
84
+ # print("New source split into the following number of \"texts\":", len(texts))
85
+
86
+ # # add new sources
87
+ # docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
88
+
89
+ # # restart convo, as the old messages confuse the AI
90
+ # clearStuff()
91
+
92
+ # print("Done adding new source.")
93
+
94
+ # return None, None
95
+
96
+ def addPDFsource(url):
97
+ print("Adding new source...")
98
+
99
+ global docsearch
100
+
101
+ # load and split
102
+ try: # assuming it is local
103
+ data = UnstructuredPDFLoader(url).load()
104
+ except: # not local, try S3
105
+ if '://' in url:
106
+ scheme, path = url.split('://', 1)
107
+ bucket, key = path.split('/', 1)
108
+
109
+ else:
110
+ raise ValueError('Invalid S3 URI')
111
+
112
+ data = S3FileLoader("strategicinnovation", "testingPDFload/bitcoin.pdf").load()
113
+
114
+
115
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
116
+ texts = text_splitter.split_documents(data)
117
+ print("New source split into the following number of \"texts\":", len(texts))
118
+
119
+ # add new sources
120
+ docsearch.add_texts([t.page_content for t in texts], metadatas=[{"src": "foreign"} for t in texts])
121
+
122
+ # restart convo, as the old messages confuse the AI
123
+ clearStuff()
124
+
125
+ print("Done adding new source.")
126
+
127
+ return None, None
128
+
129
+ def msgs2chatbot(msgs):
130
+ # the gradio chatbot object is used to display the conversation
131
+ # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message
132
+ chatbot = []
133
+
134
+ for msg in msgs:
135
+ if msg['role'] == 'user':
136
+ chatbot.append([msg['content'], ""])
137
+ elif msg['role'] == 'assistant':
138
+ chatbot[-1][1] = msg['content']
139
+
140
+ return chatbot
141
+
142
+ def getPrediction(newMsg):
143
+ global msgs
144
+ global docsearch
145
+ global predictor
146
+
147
+ # add new message to msgs object
148
+ msgs.append({"role":"user", "content": newMsg})
149
+
150
+ # edit system message to include the correct context
151
+ msgs[0] = {"role": "system",
152
+ "content": f"""
153
+ You are a helpful AI assistant.
154
+ Use your knowledge to answer the user's question if they asked a question.
155
+ If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.
156
+ DO NOT use phrases like "Based on the information provided" or other similar phrases.
157
+ Refer to the information provided below as "your knowledge".
158
+ State all answers as if they are ground truth, DO NOT mention where you got the information.
159
+
160
+ YOUR KNOWLEDGE: {" ".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}"""}
161
+
162
+ # get response from endpoint
163
+
164
+ responseObject = predictor.predict({"inputs": [msgs],
165
+ "parameters": {"max_new_tokens": 750, "top_p": 0.9, "temperature": 0.5}},
166
+ initial_args={'CustomAttributes': "accept_eula=true"})
167
+ # responseObject = predictor.predict(payload, custom_attributes="accept_eula=true")
168
+
169
+
170
+ responseMsg = responseObject[0]['generation']['content'].strip()
171
+
172
+ # add response to msgs object
173
+ msgs.append({"role":"assistant", "content": responseMsg})
174
+
175
+ # print msgs object for debugging
176
+ print(msgs)
177
+
178
+ # convert msgs to chatbot object to be displayed
179
+ chatbot = msgs2chatbot(msgs)
180
+
181
+ return chatbot, ""
182
+
183
+ def clearStuff():
184
+ global msgs
185
+ msgs = [{}]
186
+ return None
187
+
188
+ # Create a SageMaker client
189
+ sagemaker_client = boto3.client('sagemaker')
190
+ sagemaker_session = sagemaker.Session()
191
+
192
+ # Create a predictor object
193
+ predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',
194
+ sagemaker_session=sagemaker_session,
195
+ serializer=JSONSerializer(),
196
+ deserializer=JSONDeserializer())
197
+
198
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
199
+
200
+ # Create a docsearch object
201
+ docsearch = loadCleanDocsearch(embeddings)
202
+
203
+ # Create messages list with system message
204
+ msgs = [{}]
205
+
206
+ with gr.Blocks() as demo:
207
+ gr.HTML("<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />")
208
+ gr.Markdown("## DSS LLM Demo: Chat with Llama 2")
209
+
210
+ with gr.Column():
211
+ chatbot = gr.Chatbot()
212
+
213
+ with gr.Row():
214
+ with gr.Column():
215
+ newMsg = gr.Textbox(label="New Message Box", placeholder="New Message", show_label=False)
216
+ with gr.Column():
217
+ with gr.Row():
218
+ submit = gr.Button("Submit")
219
+ clear = gr.Button("Clear")
220
+ with gr.Row():
221
+ with gr.Column():
222
+ newSRC = gr.Textbox(label="New source link/path Box", placeholder="New source link/path", show_label=False)
223
+ with gr.Column():
224
+ with gr.Row():
225
+ addURL = gr.Button("Add URL Source")
226
+ addPDF = gr.Button("Add PDF Source")
227
+ #uploadFile = gr.UploadButton(file_types=[".pdf",".csv",".doc"])
228
+ reset = gr.Button("Reset Sources")
229
+
230
+ submit.click(getPrediction, [newMsg], [chatbot, newMsg])
231
+ clear.click(clearStuff, None, chatbot, queue=False)
232
+
233
+ addURL.click(addURLsource, newSRC, [newSRC, chatbot])
234
+ addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])
235
+ #uploadFile.click(getOut, uploadFile, None)
236
+ reset.click(resetDocsearch, None, chatbot)
237
+
238
+ gr.Markdown("""*Note:*
239
+
240
+ To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.
241
+
242
+ To add a PDF source, place either (1) the relative filepath to the current directory or (2) the full S3 URI in the bottom textbox and click the 'Add PDF Source' button.
243
+
244
+ The database for contextualization includes 8 public DSS website articles upon initialization.
245
+
246
+ When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)""")
247
+
248
+
249
+ demo.queue()
250
+ demo.launch(share=True)
llama2_gradio_v0.3.ipynb ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "0cd0e718-beac-4442-ac45-fffb26698d33",
6
+ "metadata": {
7
+ "tags": []
8
+ },
9
+ "source": [
10
+ "# Install packages, need to write a requirement later\n",
11
+ "!pip install instructorembedding sentence-transformers gradio langchain unstructured chromadb pdf2image pdfminer pdfminer.six"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": 2,
17
+ "id": "4d086ed6-eb66-4ded-b701-dac062e19521",
18
+ "metadata": {
19
+ "tags": []
20
+ },
21
+ "outputs": [],
22
+ "source": [
23
+ "import boto3\n",
24
+ "import sagemaker\n",
25
+ "from sagemaker.predictor import Predictor\n",
26
+ "from sagemaker.serializers import JSONSerializer\n",
27
+ "from sagemaker.deserializers import JSONDeserializer\n",
28
+ "from langchain.embeddings import HuggingFaceInstructEmbeddings\n",
29
+ "from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader\n",
30
+ "from langchain.document_loaders.csv_loader import CSVLoader\n",
31
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
32
+ "from langchain.vectorstores import Chroma\n",
33
+ "import json\n",
34
+ "import gradio as gr"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": 12,
40
+ "id": "a2d81908-6026-47b6-bd0d-ade2771eacdd",
41
+ "metadata": {
42
+ "tags": []
43
+ },
44
+ "outputs": [],
45
+ "source": [
46
+ "def loadCleanDocsearch(embeddings):\n",
47
+ " print(\"Getting fresh docsearch...\")\n",
48
+ "\n",
49
+ " # define URL sources\n",
50
+ " urls = [\n",
51
+ " 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',\n",
52
+ " 'https://www.dssinc.com/blog/2022/6/21/suicide-prevention-manager-enabling-the-veterans-affairs-to-achieve-high-reliability-in-suicide-risk-identification',\n",
53
+ " 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',\n",
54
+ " 'https://www.dssinc.com/blog/2023/5/24/supporting-the-vas-high-reliability-organization-journey-through-suicide-prevention',\n",
55
+ " 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',\n",
56
+ " 'https://www.dssinc.com/blog/2022/9/19/crescenz-va-medical-center-cmcvamc-deploys-the-dss-iconic-data-patient-case-manager-pcm-solution',\n",
57
+ " 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'\n",
58
+ " ]\n",
59
+ "\n",
60
+ " # load and split\n",
61
+ " loaders = UnstructuredURLLoader(urls=urls)\n",
62
+ " data = loaders.load()\n",
63
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)\n",
64
+ " texts = text_splitter.split_documents(data)\n",
65
+ " print(\"Sources split into the following number of \\\"texts\\\":\", len(texts))\n",
66
+ "\n",
67
+ " # get object\n",
68
+ " docsearch = Chroma.from_texts([t.page_content for t in texts],\n",
69
+ " metadatas=[{\"src\": \"DSS\"} for t in texts],\n",
70
+ " embedding=embeddings)\n",
71
+ " print(\"Done getting fresh docsearch.\")\n",
72
+ "\n",
73
+ " return docsearch\n",
74
+ "\n",
75
+ "def resetDocsearch():\n",
76
+ " global docsearch\n",
77
+ " global msgs\n",
78
+ " \n",
79
+ " foreignIDs = docsearch.get(where= {\"src\":\"foreign\"})['ids']\n",
80
+ "\n",
81
+ " if foreignIDs != []:\n",
82
+ " docsearch.delete(ids=foreignIDs)\n",
83
+ " \n",
84
+ " clearStuff()\n",
85
+ " msgs = [{}]\n",
86
+ " return None\n",
87
+ " \n",
88
+ "def addURLsource(url):\n",
89
+ " print(\"Adding new source...\")\n",
90
+ " \n",
91
+ " global docsearch\n",
92
+ "\n",
93
+ " # load and split\n",
94
+ " loaders = UnstructuredURLLoader(urls=[url])\n",
95
+ " data = loaders.load()\n",
96
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
97
+ " texts = text_splitter.split_documents(data)\n",
98
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
99
+ "\n",
100
+ " # add new sources\n",
101
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
102
+ " \n",
103
+ " # restart convo, as the old messages confuse the AI\n",
104
+ " clearStuff()\n",
105
+ "\n",
106
+ " print(\"Done adding new source.\")\n",
107
+ " \n",
108
+ " return None, None\n",
109
+ "\n",
110
+ "def addCSVsource(url):\n",
111
+ " print(\"Adding new source...\")\n",
112
+ " \n",
113
+ " global docsearch\n",
114
+ "\n",
115
+ " # load and split\n",
116
+ " loaders = CSVLoader(urls=[url])\n",
117
+ " data = loaders.load()\n",
118
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
119
+ " texts = text_splitter.split_documents(data)\n",
120
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
121
+ "\n",
122
+ " # add new sources\n",
123
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
124
+ " \n",
125
+ " # restart convo, as the old messages confuse the AI\n",
126
+ " clearStuff()\n",
127
+ "\n",
128
+ " print(\"Done adding new source.\")\n",
129
+ " \n",
130
+ " return None, None\n",
131
+ "\n",
132
+ "def addPDFsource(url):\n",
133
+ " print(\"Adding new source...\")\n",
134
+ "\n",
135
+ " global docsearch\n",
136
+ " \n",
137
+ " # load and split\n",
138
+ " loaders = UnstructuredPDFLoader(url)\n",
139
+ " data = loaders.load()\n",
140
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
141
+ " texts = text_splitter.split_documents(data)\n",
142
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
143
+ "\n",
144
+ " # add new sources\n",
145
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
146
+ " \n",
147
+ " # restart convo, as the old messages confuse the AI\n",
148
+ " clearStuff()\n",
149
+ "\n",
150
+ " print(\"Done adding new source.\")\n",
151
+ " \n",
152
+ " return None, None\n",
153
+ "\n",
154
+ "def msgs2chatbot(msgs):\n",
155
+ " # the gradio chatbot object is used to display the conversation\n",
156
+ " # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message\n",
157
+ " chatbot = []\n",
158
+ " \n",
159
+ " for msg in msgs:\n",
160
+ " if msg['role'] == 'user':\n",
161
+ " chatbot.append([msg['content'], \"\"])\n",
162
+ " elif msg['role'] == 'assistant':\n",
163
+ " chatbot[-1][1] = msg['content']\n",
164
+ "\n",
165
+ " return chatbot\n",
166
+ "\n",
167
+ "def getPrediction(newMsg):\n",
168
+ " global msgs\n",
169
+ " global docsearch\n",
170
+ " global predictor\n",
171
+ " \n",
172
+ " # add new message to msgs object\n",
173
+ " msgs.append({\"role\":\"user\", \"content\": newMsg})\n",
174
+ "\n",
175
+ " # edit system message to include the correct context\n",
176
+ " msgs[0] = {\"role\": \"system\",\n",
177
+ " \"content\": f\"\"\"\n",
178
+ " You are a helpful AI assistant.\n",
179
+ " Use your knowledge to answer the user's question if they asked a question.\n",
180
+ " If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\n",
181
+ " DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \n",
182
+ " Refer to the information provided below as \"your knowledge\". \n",
183
+ " State all answers as if they are ground truth, DO NOT mention where you got the information.\n",
184
+ " \n",
185
+ " YOUR KNOWLEDGE: {\" \".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}\"\"\"}\n",
186
+ "\n",
187
+ " # get response from endpoint\n",
188
+ "\n",
189
+ " responseObject = predictor.predict({\"inputs\": [msgs],\n",
190
+ " \"parameters\": {\"max_new_tokens\": 750, \"top_p\": 0.9, \"temperature\": 0.5}},\n",
191
+ " initial_args={'CustomAttributes': \"accept_eula=true\"})\n",
192
+ "# responseObject = predictor.predict(payload, custom_attributes=\"accept_eula=true\")\n",
193
+ "\n",
194
+ " \n",
195
+ " responseMsg = responseObject[0]['generation']['content'].strip()\n",
196
+ "\n",
197
+ " # add response to msgs object\n",
198
+ " msgs.append({\"role\":\"assistant\", \"content\": responseMsg})\n",
199
+ " \n",
200
+ " # print msgs object for debugging\n",
201
+ " print(msgs)\n",
202
+ " \n",
203
+ " # convert msgs to chatbot object to be displayed\n",
204
+ " chatbot = msgs2chatbot(msgs)\n",
205
+ "\n",
206
+ " return chatbot, \"\"\n",
207
+ "\n",
208
+ "def clearStuff():\n",
209
+ " global msgs\n",
210
+ " msgs = [{}]\n",
211
+ " return None"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 7,
217
+ "id": "c56c588d-1bca-448f-bba9-96f61e5bab33",
218
+ "metadata": {
219
+ "tags": []
220
+ },
221
+ "outputs": [
222
+ {
223
+ "name": "stdout",
224
+ "output_type": "stream",
225
+ "text": [
226
+ "load INSTRUCTOR_Transformer\n",
227
+ "max_seq_length 512\n",
228
+ "Getting fresh docsearch...\n",
229
+ "Sources split into the following number of \"texts\": 36\n",
230
+ "Done getting fresh docsearch.\n"
231
+ ]
232
+ }
233
+ ],
234
+ "source": [
235
+ "# Create a SageMaker client\n",
236
+ "sagemaker_client = boto3.client('sagemaker')\n",
237
+ "sagemaker_session = sagemaker.Session()\n",
238
+ "\n",
239
+ "# Create a predictor object\n",
240
+ "predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',\n",
241
+ " sagemaker_session=sagemaker_session,\n",
242
+ " serializer=JSONSerializer(),\n",
243
+ " deserializer=JSONDeserializer())\n",
244
+ "\n",
245
+ "embeddings = HuggingFaceInstructEmbeddings(model_name=\"hkunlp/instructor-xl\")\n",
246
+ "\n",
247
+ "# Create a docsearch object\n",
248
+ "docsearch = loadCleanDocsearch(embeddings)\n",
249
+ "\n",
250
+ "# Create messages list with system message\n",
251
+ "msgs = [{}]"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": 13,
257
+ "id": "0572e3b3-2805-4db5-9d23-dac40842c58c",
258
+ "metadata": {
259
+ "tags": []
260
+ },
261
+ "outputs": [
262
+ {
263
+ "name": "stdout",
264
+ "output_type": "stream",
265
+ "text": [
266
+ "Running on local URL: http://127.0.0.1:7864\n",
267
+ "Running on public URL: https://a6c9c06b85c90192e3.gradio.live\n",
268
+ "\n",
269
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
270
+ ]
271
+ },
272
+ {
273
+ "data": {
274
+ "text/html": [
275
+ "<div><iframe src=\"https://a6c9c06b85c90192e3.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
276
+ ],
277
+ "text/plain": [
278
+ "<IPython.core.display.HTML object>"
279
+ ]
280
+ },
281
+ "metadata": {},
282
+ "output_type": "display_data"
283
+ },
284
+ {
285
+ "data": {
286
+ "text/plain": []
287
+ },
288
+ "execution_count": 13,
289
+ "metadata": {},
290
+ "output_type": "execute_result"
291
+ },
292
+ {
293
+ "name": "stdout",
294
+ "output_type": "stream",
295
+ "text": [
296
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: Formerly the President of a federally focused consulting company, Bailey has over 25 years of sales and business development experience, managing product portfolios and sales of disruptive and innovative technology and equipment solutions for the healthcare market – both in the public and private sectors.\\n\\n“We are excited to have Brion onboard to help expand our ever-growing footprint in the federal health arena,” said Mark Byers, president of DSS, Inc. “He brings a deep level of sales and business development expertise in supporting cutting-edge and disruptive healthcare innovations.” Formerly the President of a federally focused consulting company, Bailey has over 25 years of sales and business development experience, managing product portfolios and sales of disruptive and innovative technology and equipment solutions for the healthcare market – both in the public and private sectors.\\n\\n“We are excited to have Brion onboard to help expand our ever-growing footprint in the federal health arena,” said Mark Byers, president of DSS, Inc. “He brings a deep level of sales and business development expertise in supporting cutting-edge and disruptive healthcare innovations.” As VP of Strategic Accounts for the U.S. Federal Sector at Becton Dickinson, Bailey provided medical technology portfolio management and exceeded performance metrics on customer relationship building, channel partner development, customer acquisition processes, and operating procedures aligned with federal acquisitions requirements. All of this activity resulted in substantial growth in market share during his five-year tenure with the company.\\n\\nBailey has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University. He resides in Central Florida with his wife and son.\\n\\nFor more information on DSS, Inc.’s Federal Health IT solutions, please click here. As VP of Strategic Accounts for the U.S. Federal Sector at Becton Dickinson, Bailey provided medical technology portfolio management and exceeded performance metrics on customer relationship building, channel partner development, customer acquisition processes, and operating procedures aligned with federal acquisitions requirements. All of this activity resulted in substantial growth in market share during his five-year tenure with the company.\\n\\nBailey has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University. He resides in Central Florida with his wife and son.\\n\\nFor more information on DSS, Inc.’s Federal Health IT solutions, please click here. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies.'}, {'role': 'user', 'content': 'who is brion bailey'}, {'role': 'assistant', 'content': 'Based on the information provided, Brion Bailey is the Director of Business Development for the Federal Health division of Document Storage Systems, Inc. (DSS, Inc.). He has over 25 years of sales and business development experience, specifically in supporting disruptive healthcare innovations. Prior to joining DSS, Inc., Bailey was the President of a federally focused consulting company, where he managed product portfolios and sales of innovative technology and equipment solutions for the healthcare market. He has also worked at Becton Dickinson as VP of Strategic Accounts for the U.S. Federal Sector, where he provided medical technology portfolio management and exceeded performance metrics. Bailey holds a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University. He resides in Central Florida with his wife and son.'}]\n",
297
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen DSS Federal Health\\n\\nTwitter\\n\\nLinkedIn0\\n\\n0 Likes\\n\\nPrevious\\n DSS, Inc. Advisor to Present at Disney Institute’s Veterans Summit\\n \\n DSS NewsCindy DumontAugust 10, 2022Disney Institute’s Veterans Summit, Dr. Barbara Van Dahlen, Veterans in the Workplace, Heroes Work Here initiative, suicide prevention for Veterans, The Inclusive Approach to Care, General Mike Linnington Ret., CEO of the Wounded Warrior Project, Mark Elliot, Give an Hour, Veterans, Veterans mental health\\n\\nNext\\n Contracting Officers: Celebrating the Unsung Heroes at the VA\\n \\n Customer ServiceCindy DumontJuly 27, 2022Contracting Officers, VA, Department of Veterans Affairs, Procurement, federal health IT solutions, DSS, Health IT'}, {'role': 'user', 'content': 'who is brion bailey'}, {'role': 'assistant', 'content': 'Based on the information provided, Brion Bailey is the Director of Business Development for the Federal Health division of Document Storage Systems, Inc. (DSS, Inc.). He has over 25 years of sales and business development experience, specifically in supporting disruptive healthcare innovations. Prior to joining DSS, Inc., Bailey was the President of a federally focused consulting company, where he managed product portfolios and sales of innovative technology and equipment solutions for the healthcare market. He has also worked at Becton Dickinson as VP of Strategic Accounts for the U.S. Federal Sector, where he provided medical technology portfolio management and exceeded performance metrics. Bailey holds a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University. He resides in Central Florida with his wife and son.'}, {'role': 'user', 'content': 'did dss join mission daybreak?'}, {'role': 'assistant', 'content': 'Based on the information provided, there is no mention of DSS joining Mission Daybreak. The information provided only mentions DSS as a leading provider of health information technology (HIT) solutions for federal, private, and public healthcare organizations, and their involvement in various events and initiatives related to healthcare and technology. There is no mention of any partnership or involvement with Mission Daybreak.'}]\n",
298
+ "Adding new source...\n",
299
+ "New source split into the following number of \"texts\": 5\n",
300
+ "Done adding new source.\n",
301
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen DSS Federal Health\\n\\nTwitter\\n\\nLinkedIn0\\n\\n0 Likes\\n\\nPrevious\\n DSS, Inc. Advisor to Present at Disney Institute’s Veterans Summit\\n \\n DSS NewsCindy DumontAugust 10, 2022Disney Institute’s Veterans Summit, Dr. Barbara Van Dahlen, Veterans in the Workplace, Heroes Work Here initiative, suicide prevention for Veterans, The Inclusive Approach to Care, General Mike Linnington Ret., CEO of the Wounded Warrior Project, Mark Elliot, Give an Hour, Veterans, Veterans mental health\\n\\nNext\\n Contracting Officers: Celebrating the Unsung Heroes at the VA\\n \\n Customer ServiceCindy DumontJuly 27, 2022Contracting Officers, VA, Department of Veterans Affairs, Procurement, federal health IT solutions, DSS, Health IT'}, {'role': 'user', 'content': 'did dss join mission daybreak?'}, {'role': 'assistant', 'content': 'Based on the information provided, there is no mention of DSS joining Mission Daybreak. The press releases and articles provided only mention DSS, Inc. and its various initiatives and announcements related to healthcare and technology. Therefore, I cannot answer the question of whether DSS joined Mission Daybreak, as there is no information provided to suggest that such an event occurred.'}]\n",
302
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen Next\\n DSS, Inc. Presenting at The Spring 2022 DoD/VA & Government HIT Summit\\n \\n DSS NewsCindy DumontMay 2, 2022DSS, DSS New, Va, Veterans Health, Veterans Health Administration, health information technology (HIT) solutions, HIT, HIT Solutions, Dr. David LaBorde, The Spring 2022 DoD/VA & Government HIT, Dr. Barbara Van Dahlen DSS Federal Health\\n\\nTwitter\\n\\nLinkedIn0\\n\\n0 Likes\\n\\nPrevious\\n DSS, Inc. Advisor to Present at Disney Institute’s Veterans Summit\\n \\n DSS NewsCindy DumontAugust 10, 2022Disney Institute’s Veterans Summit, Dr. Barbara Van Dahlen, Veterans in the Workplace, Heroes Work Here initiative, suicide prevention for Veterans, The Inclusive Approach to Care, General Mike Linnington Ret., CEO of the Wounded Warrior Project, Mark Elliot, Give an Hour, Veterans, Veterans mental health\\n\\nNext\\n Contracting Officers: Celebrating the Unsung Heroes at the VA\\n \\n Customer ServiceCindy DumontJuly 27, 2022Contracting Officers, VA, Department of Veterans Affairs, Procurement, federal health IT solutions, DSS, Health IT'}, {'role': 'user', 'content': 'Did DSS join mission daybreak?'}, {'role': 'assistant', 'content': 'Based on the information provided, there is no mention of DSS joining Mission Daybreak.'}]\n",
303
+ "Adding new source...\n",
304
+ "New source split into the following number of \"texts\": 5\n",
305
+ "Done adding new source.\n",
306
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: That’s what led the VA to create Mission Daybreak, a $20 million U.S. Department of Veterans Affairs grand challenge to reduce Veteran suicides. This year the VA received 1,371 submissions during Phase One of the Challenge, the deadline for which was July 8, 2022.\\n\\nAs a finalist, DSS will receive $250,000 and advance to Phase 2 of the challenge.\\n\\nDuring Phase 2 of the challenge, the 30 finalists will join a virtual accelerator program designed to help the finalists develop ambitious, but achievable roadmaps for prototyping, iteration, testing, and evaluation. Technology partners supporting the accelerator include Amazon and Microsoft. Two first-place winners will each receive $3 million,\\n\\nThree second-place winners will each receive $1 million,\\n\\nFive third-place winners will each receive $500,000.\\n\\nDSS Inc.’s years of experience helping the VA with data interoperability makes all this possible. DSS is excited to bring the latest ML technology to the VA and put it to work serving veterans. Phase 2 winners will be announced in November and DSS hopes to have great news to share then! Visit missiondaybreak.net for more information.\\n\\nTo learn more about how DSS, Inc. supports the VA and veterans please click here.\\n\\nDSS News\\n\\nCindy Dumont\\n\\nMission Daybreak,\\n\\nDSS,\\n\\nDSS News,\\n\\nsuicide prevention for Veterans,\\n\\nMachine Learning,\\n\\nVA Suicide prevention challenge\\n\\nTwitter\\n\\nLinkedIn0\\n\\n0 Likes DSS News\\n\\nCindy Dumont\\n\\nMission Daybreak,\\n\\nDSS,\\n\\nDSS News,\\n\\nsuicide prevention for Veterans,\\n\\nMachine Learning,\\n\\nVA Suicide prevention challenge\\n\\nTwitter\\n\\nLinkedIn0\\n\\n0 Likes\\n\\nPrevious\\n Customer Service Week 2022: DSS Support Services Team Brings Highest-Level of Customer Support for the Fed Health IT Arena \\n \\n Customer ServiceCindy DumontOctober 3, 2022DSS, Customer Service Week, VA, Department of Veterans Affairs, Customer Service Week 2022, full lifecycle support approach, DSS Support Services team\\n\\nNext\\n VHA Awards Dialysis Electronic Medical Record Software and Maintenance Electronic Health Record Contract to DSS, Inc.\\n \\n DSS NewsCindy DumontSeptember 20, 2022Veterans Healthcare Administration, DSS CyberRen, DSS, Diasyst software, Dialysis EHR, Renal Care for Veterans, HRO, Mark Byers, EHR, Veterans DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies. DSS, Inc. Announces Appointment of Brion Bailey as Director of Federal Business Development\\n\\nBrings 25 years of sales and business development experience supporting disruptive healthcare innovations\\n\\nJUNO BEACH, FLA. AUGUST 09, 2022 — Document Storage Systems, Inc. (DSS, Inc.), a leading provider of health information technology (HIT) solutions for federal, private and public health care organizations, today announced that Brion Bailey has joined the company as the Director of Business Development for its Federal Health division.\\n\\nIn this role, Bailey will be a key driver of revenue growth for the company’s federal health division. He will also expand the company’s partner eco-system, as well as support new sales opportunities at the Department of Veterans Affairs (VA) and other federal health agencies.'}, {'role': 'user', 'content': 'Did DSS join mission daybreak?'}, {'role': 'assistant', 'content': 'Based on the information provided, DSS did join Mission Daybreak as a finalist. According to the text, DSS will receive $250,000 and advance to Phase 2 of the challenge.'}]\n"
307
+ ]
308
+ }
309
+ ],
310
+ "source": [
311
+ "with gr.Blocks() as demo:\n",
312
+ " gr.HTML(\"<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />\")\n",
313
+ " gr.Markdown(\"## DSS LLM Demo: Chat with Llama 2\")\n",
314
+ "\n",
315
+ " with gr.Column():\n",
316
+ " chatbot = gr.Chatbot()\n",
317
+ " \n",
318
+ " with gr.Row():\n",
319
+ " with gr.Column():\n",
320
+ " newMsg = gr.Textbox(label=\"New Message Box\", placeholder=\"New Message\", show_label=False)\n",
321
+ " with gr.Column():\n",
322
+ " with gr.Row():\n",
323
+ " submit = gr.Button(\"Submit\")\n",
324
+ " clear = gr.Button(\"Clear\")\n",
325
+ " with gr.Row():\n",
326
+ " with gr.Column():\n",
327
+ " newSRC = gr.Textbox(label=\"New source link/path Box\", placeholder=\"New source link/path\", show_label=False)\n",
328
+ " with gr.Column():\n",
329
+ " with gr.Row():\n",
330
+ " addURL = gr.Button(\"Add URL Source\")\n",
331
+ " addPDF = gr.Button(\"Add PDF Source\")\n",
332
+ " reset = gr.Button(\"Reset Sources\")\n",
333
+ "\n",
334
+ " submit.click(getPrediction, [newMsg], [chatbot, newMsg])\n",
335
+ " clear.click(clearStuff, None, chatbot, queue=False)\n",
336
+ " \n",
337
+ " addURL.click(addURLsource, newSRC, [newSRC, chatbot])\n",
338
+ " addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])\n",
339
+ " reset.click(resetDocsearch, None, chatbot)\n",
340
+ "\n",
341
+ " gr.Markdown(\"\"\"*Note: \n",
342
+ " \n",
343
+ " To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.\n",
344
+ " \n",
345
+ " To add a PDF source, place a relative file path in the bottom textbox and click the 'Add PDF Source' button.\n",
346
+ " \n",
347
+ " The database for contextualization includes 8 public DSS website articles upon initialization.\n",
348
+ " \n",
349
+ " When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)*\"\"\")\n",
350
+ "\n",
351
+ "\n",
352
+ "demo.queue()\n",
353
+ "demo.launch(share=True)"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "execution_count": null,
359
+ "id": "e200839d-9f90-4651-8212-decc75d1e3e3",
360
+ "metadata": {},
361
+ "outputs": [],
362
+ "source": []
363
+ }
364
+ ],
365
+ "metadata": {
366
+ "kernelspec": {
367
+ "display_name": "conda_pytorch_p310",
368
+ "language": "python",
369
+ "name": "conda_pytorch_p310"
370
+ },
371
+ "language_info": {
372
+ "codemirror_mode": {
373
+ "name": "ipython",
374
+ "version": 3
375
+ },
376
+ "file_extension": ".py",
377
+ "mimetype": "text/x-python",
378
+ "name": "python",
379
+ "nbconvert_exporter": "python",
380
+ "pygments_lexer": "ipython3",
381
+ "version": "3.10.10"
382
+ }
383
+ },
384
+ "nbformat": 4,
385
+ "nbformat_minor": 5
386
+ }
llama2_gradio_v0.4.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
llama2_gradio_v0.4_backup.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
llama2_gradio_v0.4_s3.ipynb ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "3ecb7e4b-c220-438f-9afd-5d959f3235de",
6
+ "metadata": {
7
+ "tags": []
8
+ },
9
+ "source": [
10
+ "# Install packages, need to write a requirement later\n",
11
+ "!pip install instructorembedding sentence-transformers gradio langchain unstructured chromadb pdf2image pdfminer pdfminer.six"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": 13,
17
+ "id": "75cbef7c-974e-4438-addc-9c0b70be4d71",
18
+ "metadata": {
19
+ "tags": []
20
+ },
21
+ "outputs": [],
22
+ "source": [
23
+ "import boto3\n",
24
+ "import sagemaker\n",
25
+ "from sagemaker.predictor import Predictor\n",
26
+ "from sagemaker.serializers import JSONSerializer\n",
27
+ "from sagemaker.deserializers import JSONDeserializer\n",
28
+ "from langchain.embeddings import HuggingFaceInstructEmbeddings\n",
29
+ "from langchain.document_loaders import UnstructuredURLLoader, UnstructuredPDFLoader, S3FileLoader\n",
30
+ "from langchain.docstore.document import Document\n",
31
+ "from langchain.document_loaders.csv_loader import CSVLoader\n",
32
+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
33
+ "from langchain.vectorstores import Chroma\n",
34
+ "import json\n",
35
+ "import gradio as gr\n",
36
+ "\n",
37
+ "def loadCleanDocsearch(embeddings):\n",
38
+ " print(\"Getting fresh docsearch...\")\n",
39
+ "\n",
40
+ " # define URL sources with some stock articles from public DSS website\n",
41
+ " urls = [\n",
42
+ " 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',\n",
43
+ " 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',\n",
44
+ " 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',\n",
45
+ " 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization'\n",
46
+ " ]\n",
47
+ "\n",
48
+ " # load and split\n",
49
+ " loaders = UnstructuredURLLoader(urls=urls)\n",
50
+ " data = loaders.load()\n",
51
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)\n",
52
+ " texts = text_splitter.split_documents(data)\n",
53
+ " print(\"Sources split into the following number of \\\"texts\\\":\", len(texts))\n",
54
+ "\n",
55
+ " # get object\n",
56
+ " docsearch = Chroma.from_texts([t.page_content for t in texts],\n",
57
+ " metadatas=[{\"src\": \"DSS\"} for t in texts],\n",
58
+ " embedding=embeddings)\n",
59
+ " print(\"Done getting fresh docsearch.\")\n",
60
+ "\n",
61
+ " return docsearch\n",
62
+ "\n",
63
+ "def resetDocsearch():\n",
64
+ " global docsearch\n",
65
+ "\n",
66
+ " foreignIDs = docsearch.get(where= {\"src\":\"foreign\"})['ids']\n",
67
+ "\n",
68
+ " if foreignIDs != []:\n",
69
+ " docsearch.delete(ids=foreignIDs)\n",
70
+ " \n",
71
+ " clearStuff()\n",
72
+ "\n",
73
+ "\n",
74
+ "def addURLsource(url):\n",
75
+ " print(\"Adding new source...\")\n",
76
+ " \n",
77
+ " global docsearch\n",
78
+ "\n",
79
+ " # load and split\n",
80
+ " loaders = UnstructuredURLLoader(urls=[url])\n",
81
+ " data = loaders.load()\n",
82
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
83
+ " texts = text_splitter.split_documents(data)\n",
84
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
85
+ "\n",
86
+ " # add new sources\n",
87
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
88
+ " \n",
89
+ " # restart convo, as the old messages confuse the AI\n",
90
+ " clearStuff()\n",
91
+ "\n",
92
+ " print(\"Done adding new source.\")\n",
93
+ " \n",
94
+ " return None, None\n",
95
+ "\n",
96
+ "# def addCSVsource(url):\n",
97
+ "# print(\"Adding new source...\")\n",
98
+ " \n",
99
+ "# global docsearch\n",
100
+ "\n",
101
+ "# # load and split\n",
102
+ "# loaders = CSVLoader(urls=[url])\n",
103
+ "# data = loaders.load()\n",
104
+ "# text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
105
+ "# texts = text_splitter.split_documents(data)\n",
106
+ "# print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
107
+ "\n",
108
+ "# # add new sources\n",
109
+ "# docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
110
+ " \n",
111
+ "# # restart convo, as the old messages confuse the AI\n",
112
+ "# clearStuff()\n",
113
+ "\n",
114
+ "# print(\"Done adding new source.\")\n",
115
+ " \n",
116
+ "# return None, None\n",
117
+ "\n",
118
+ "def addPDFsource(url):\n",
119
+ " print(\"Adding new source...\")\n",
120
+ "\n",
121
+ " global docsearch\n",
122
+ " \n",
123
+ " # load and split\n",
124
+ " try: # assuming it is local\n",
125
+ " data = UnstructuredPDFLoader(url).load()\n",
126
+ " except: # not local, try S3\n",
127
+ " if '://' in url:\n",
128
+ " scheme, path = url.split('://', 1)\n",
129
+ " bucket, key = path.split('/', 1)\n",
130
+ "\n",
131
+ " else:\n",
132
+ " raise ValueError('Invalid S3 URI')\n",
133
+ " \n",
134
+ " data = S3FileLoader(\"strategicinnovation\", \"testingPDFload/bitcoin.pdf\").load()\n",
135
+ " \n",
136
+ " \n",
137
+ " text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
138
+ " texts = text_splitter.split_documents(data)\n",
139
+ " print(\"New source split into the following number of \\\"texts\\\":\", len(texts))\n",
140
+ "\n",
141
+ " # add new sources\n",
142
+ " docsearch.add_texts([t.page_content for t in texts], metadatas=[{\"src\": \"foreign\"} for t in texts])\n",
143
+ " \n",
144
+ " # restart convo, as the old messages confuse the AI\n",
145
+ " clearStuff()\n",
146
+ "\n",
147
+ " print(\"Done adding new source.\")\n",
148
+ " \n",
149
+ " return None, None\n",
150
+ "\n",
151
+ "def msgs2chatbot(msgs):\n",
152
+ " # the gradio chatbot object is used to display the conversation\n",
153
+ " # it needs the msgs to be in List[List] format where the inner list is 2 elements: user message, chatbot response message\n",
154
+ " chatbot = []\n",
155
+ " \n",
156
+ " for msg in msgs:\n",
157
+ " if msg['role'] == 'user':\n",
158
+ " chatbot.append([msg['content'], \"\"])\n",
159
+ " elif msg['role'] == 'assistant':\n",
160
+ " chatbot[-1][1] = msg['content']\n",
161
+ "\n",
162
+ " return chatbot\n",
163
+ "\n",
164
+ "def getPrediction(newMsg):\n",
165
+ " global msgs\n",
166
+ " global docsearch\n",
167
+ " global predictor\n",
168
+ " \n",
169
+ " # add new message to msgs object\n",
170
+ " msgs.append({\"role\":\"user\", \"content\": newMsg})\n",
171
+ "\n",
172
+ " # edit system message to include the correct context\n",
173
+ " msgs[0] = {\"role\": \"system\",\n",
174
+ " \"content\": f\"\"\"\n",
175
+ " You are a helpful AI assistant.\n",
176
+ " Use your knowledge to answer the user's question if they asked a question.\n",
177
+ " If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\n",
178
+ " DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \n",
179
+ " Refer to the information provided below as \"your knowledge\". \n",
180
+ " State all answers as if they are ground truth, DO NOT mention where you got the information.\n",
181
+ " \n",
182
+ " YOUR KNOWLEDGE: {\" \".join([tup[0].page_content for tup in docsearch.similarity_search_with_score(newMsg, k=5) if tup[1]<=.85])}\"\"\"}\n",
183
+ "\n",
184
+ " # get response from endpoint\n",
185
+ "\n",
186
+ " responseObject = predictor.predict({\"inputs\": [msgs],\n",
187
+ " \"parameters\": {\"max_new_tokens\": 750, \"top_p\": 0.9, \"temperature\": 0.5}},\n",
188
+ " initial_args={'CustomAttributes': \"accept_eula=true\"})\n",
189
+ "# responseObject = predictor.predict(payload, custom_attributes=\"accept_eula=true\")\n",
190
+ "\n",
191
+ " \n",
192
+ " responseMsg = responseObject[0]['generation']['content'].strip()\n",
193
+ "\n",
194
+ " # add response to msgs object\n",
195
+ " msgs.append({\"role\":\"assistant\", \"content\": responseMsg})\n",
196
+ " \n",
197
+ " # print msgs object for debugging\n",
198
+ " print(msgs)\n",
199
+ " \n",
200
+ " # convert msgs to chatbot object to be displayed\n",
201
+ " chatbot = msgs2chatbot(msgs)\n",
202
+ "\n",
203
+ " return chatbot, \"\"\n",
204
+ "\n",
205
+ "def clearStuff():\n",
206
+ " global msgs\n",
207
+ " msgs = [{}]\n",
208
+ " return None\n",
209
+ "\n",
210
+ "# Create a SageMaker client\n",
211
+ "sagemaker_client = boto3.client('sagemaker')\n",
212
+ "sagemaker_session = sagemaker.Session()\n",
213
+ "\n",
214
+ "# Create a predictor object\n",
215
+ "predictor = Predictor(endpoint_name='meta-textgeneration-llama-2-13b-f-2023-08-08-23-37-15-947',\n",
216
+ " sagemaker_session=sagemaker_session,\n",
217
+ " serializer=JSONSerializer(),\n",
218
+ " deserializer=JSONDeserializer())\n",
219
+ "\n",
220
+ "embeddings = HuggingFaceInstructEmbeddings(model_name=\"hkunlp/instructor-xl\")\n",
221
+ "\n",
222
+ "# Create a docsearch object\n",
223
+ "docsearch = loadCleanDocsearch(embeddings)\n",
224
+ "\n",
225
+ "# Create messages list with system message\n",
226
+ "msgs = [{}]\n",
227
+ "\n",
228
+ "with gr.Blocks() as demo:\n",
229
+ " gr.HTML(\"<img src='https://images.squarespace-cdn.com/content/v1/5bab98d9f4e53108da59ae49/1537972707182-B5VGFGO3IDMB6HHSJY9H/dss_sp_logo.png?format=1500w' />\")\n",
230
+ " gr.Markdown(\"## DSS LLM Demo: Chat with Llama 2\")\n",
231
+ "\n",
232
+ " with gr.Column():\n",
233
+ " chatbot = gr.Chatbot()\n",
234
+ " \n",
235
+ " with gr.Row():\n",
236
+ " with gr.Column():\n",
237
+ " newMsg = gr.Textbox(label=\"New Message Box\", placeholder=\"New Message\", show_label=False)\n",
238
+ " with gr.Column():\n",
239
+ " with gr.Row():\n",
240
+ " submit = gr.Button(\"Submit\")\n",
241
+ " clear = gr.Button(\"Clear\")\n",
242
+ " with gr.Row():\n",
243
+ " with gr.Column():\n",
244
+ " newSRC = gr.Textbox(label=\"New source link/path Box\", placeholder=\"New source link/path\", show_label=False)\n",
245
+ " with gr.Column():\n",
246
+ " with gr.Row():\n",
247
+ " addURL = gr.Button(\"Add URL Source\")\n",
248
+ " addPDF = gr.Button(\"Add PDF Source\")\n",
249
+ " #uploadFile = gr.UploadButton(file_types=[\".pdf\",\".csv\",\".doc\"])\n",
250
+ " reset = gr.Button(\"Reset Sources\")\n",
251
+ "\n",
252
+ " submit.click(getPrediction, [newMsg], [chatbot, newMsg])\n",
253
+ " clear.click(clearStuff, None, chatbot, queue=False)\n",
254
+ " \n",
255
+ " addURL.click(addURLsource, newSRC, [newSRC, chatbot])\n",
256
+ " addPDF.click(addPDFsource, newSRC, [newSRC, chatbot])\n",
257
+ " #uploadFile.click(getOut, uploadFile, None)\n",
258
+ " reset.click(resetDocsearch, None, chatbot)\n",
259
+ "\n",
260
+ " gr.Markdown(\"\"\"*Note:*\n",
261
+ " \n",
262
+ " To add a URL source, place a full hyperlink in the bottom textbox and click the 'Add URL Source' button.\n",
263
+ " \n",
264
+ " To add a PDF source, place either (1) the relative filepath to the current directory or (2) the full S3 URI in the bottom textbox and click the 'Add PDF Source' button.\n",
265
+ " \n",
266
+ " The database for contextualization includes 8 public DSS website articles upon initialization.\n",
267
+ " \n",
268
+ " When the 'Reset Sources' button is clicked, the database is completely wiped. (Some knowledge may be preserved through the conversation history if left uncleared.)\"\"\")\n",
269
+ "\n",
270
+ "\n",
271
+ "demo.queue()\n",
272
+ "demo.launch(share=True)"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "execution_count": 7,
278
+ "id": "e200839d-9f90-4651-8212-decc75d1e3e3",
279
+ "metadata": {
280
+ "tags": []
281
+ },
282
+ "outputs": [
283
+ {
284
+ "name": "stdout",
285
+ "output_type": "stream",
286
+ "text": [
287
+ "\n"
288
+ ]
289
+ }
290
+ ],
291
+ "source": [
292
+ "print() # execute this after gradio cell to make this cell the std_out for console logging"
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "execution_count": 11,
298
+ "id": "027e17a8-a2cf-4dcf-9edc-22d9900ff7b8",
299
+ "metadata": {
300
+ "tags": []
301
+ },
302
+ "outputs": [
303
+ {
304
+ "data": {
305
+ "text/plain": [
306
+ "19"
307
+ ]
308
+ },
309
+ "execution_count": 11,
310
+ "metadata": {},
311
+ "output_type": "execute_result"
312
+ },
313
+ {
314
+ "name": "stdout",
315
+ "output_type": "stream",
316
+ "text": [
317
+ "[{'role': 'system', 'content': '\\n You are a helpful AI assistant.\\n Use your knowledge to answer the user\\'s question if they asked a question.\\n If the answer to a question is not in your knowledge, just admit you do not know the answer and do not fabricate information.\\n DO NOT use phrases like \"Based on the information provided\" or other similar phrases. \\n Refer to the information provided below as \"your knowledge\". \\n State all answers as if they are ground truth, DO NOT mention where you got the information.\\n \\n YOUR KNOWLEDGE: '}, {'role': 'user', 'content': 'hi, who is Brion bailey?'}, {'role': 'assistant', 'content': 'Based on your knowledge, Brion Bailey is the Director of Federal Business Development at DSS, Inc. He has over 25 years of sales and business development experience, specifically in the healthcare market, and has held leadership positions at various companies, including Chief Commercial Officer at Syft Corporation. He has a Master of Science in Marketing from St. Thomas University and a Bachelor of Business Administration from Florida International University.'}, {'role': 'user', 'content': 'hi'}, {'role': 'assistant', 'content': 'Hello! How can I assist you today?'}]\n"
318
+ ]
319
+ }
320
+ ],
321
+ "source": [
322
+ "len(docsearch.get()['ids'])"
323
+ ]
324
+ }
325
+ ],
326
+ "metadata": {
327
+ "kernelspec": {
328
+ "display_name": "conda_pytorch_p310",
329
+ "language": "python",
330
+ "name": "conda_pytorch_p310"
331
+ },
332
+ "language_info": {
333
+ "codemirror_mode": {
334
+ "name": "ipython",
335
+ "version": 3
336
+ },
337
+ "file_extension": ".py",
338
+ "mimetype": "text/x-python",
339
+ "name": "python",
340
+ "nbconvert_exporter": "python",
341
+ "pygments_lexer": "ipython3",
342
+ "version": "3.10.10"
343
+ }
344
+ },
345
+ "nbformat": 4,
346
+ "nbformat_minor": 5
347
+ }
main.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sagemaker
2
+ import streamlit as st
3
+ from streamlit_chat import message
4
+ from langchain.llms.sagemaker_endpoint import LLMContentHandler, SagemakerEndpoint
5
+ from langchain.document_loaders import UnstructuredURLLoader
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain.vectorstores import Chroma
8
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
9
+ from langchain import PromptTemplate
10
+ from langchain.chains.question_answering import load_qa_chain
11
+ from langchain.memory import ConversationBufferMemory
12
+ from typing import Dict
13
+ import json
14
+ import chromadb
15
+ import datetime
16
+
17
+ endpoint_name = "falcon-40b-instruct-gates3"
18
+ aws_region = "us-east-1"
19
+ class ContentHandler(LLMContentHandler):
20
+ content_type = "application/json"
21
+ accepts = "application/json"
22
+ len_prompt = 0
23
+
24
+ def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:
25
+ self.len_prompt = len(prompt)
26
+ input_str = json.dumps(
27
+ {"inputs": prompt,
28
+ "parameters": {
29
+ "do_sample": True,
30
+ "top_p": 0.9,
31
+ "temperature": 0.8,
32
+ "max_new_tokens": 1024,
33
+ "repetition_penalty": 1.03,
34
+ "stop": ["\n\n", "Human:", "<|endoftext|>", "</s>"]
35
+ }})
36
+ return input_str.encode('utf-8')
37
+
38
+ def transform_output(self, output: bytes) -> str:
39
+ response_json = output.read()
40
+ res = json.loads(response_json)
41
+ ans = res[0]['generated_text'][self.len_prompt:]
42
+ ans = ans[:ans.rfind("Human")].strip()
43
+ return ans
44
+
45
+
46
+ @st.cache_resource
47
+ def getDocsearchOnce():
48
+ print("Getting docsearch...")
49
+
50
+ # define URL sources
51
+ urls = [
52
+ 'https://www.dssinc.com/blog/2022/6/21/suicide-prevention-manager-enabling-the-veterans-affairs-to-achieve-high-reliability-in-suicide-risk-identification',
53
+ 'https://www.dssinc.com/blog/2022/8/9/dss-inc-announces-appointment-of-brion-bailey-as-director-of-federal-business-development',
54
+ 'https://www.dssinc.com/blog/2022/3/21/march-22-is-diabetes-alertness-day-a-helpful-reminder-to-monitor-and-prevent-diabetes',
55
+ 'https://www.dssinc.com/blog/2023/5/24/supporting-the-vas-high-reliability-organization-journey-through-suicide-prevention',
56
+ 'https://www.dssinc.com/blog/2022/12/19/dss-theradoc-helps-battle-super-bugs-for-better-veteran-health',
57
+ 'https://www.dssinc.com/blog/2022/9/21/dss-inc-chosen-for-phase-two-of-mission-daybreak-vas-suicide-prevention-challenge',
58
+ 'https://www.dssinc.com/blog/2022/9/19/crescenz-va-medical-center-cmcvamc-deploys-the-dss-iconic-data-patient-case-manager-pcm-solution',
59
+ 'https://www.dssinc.com/blog/2022/5/9/federal-news-network-the-importance-of-va-supply-chain-modernization']
60
+
61
+ # load and split
62
+ loaders = UnstructuredURLLoader(urls=urls)
63
+ data = loaders.load()
64
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
65
+ texts = text_splitter.split_documents(data) # do not want to reassign (must stay consistent with pinecone embeddings)
66
+ print("Sources split into the following number of \"texts\":", len(texts))
67
+
68
+ # load embedding model
69
+ print("Loading embedding model...")
70
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
71
+
72
+ docsearch = Chroma.from_texts([t.page_content for t in texts], embeddings)
73
+
74
+ return docsearch
75
+
76
+
77
+ @st.cache_resource
78
+ def getChainOnce():
79
+ print("Getting chain...")
80
+
81
+ content_handler = ContentHandler()
82
+
83
+ # get langchain-wrapped Predictor Endpoint Object
84
+ llm = SagemakerEndpoint(
85
+ endpoint_name=endpoint_name,
86
+ region_name=aws_region,
87
+ content_handler=content_handler
88
+ )
89
+
90
+ # configure the prompt object
91
+ prompt = PromptTemplate(
92
+ input_variables=["history", "context", "new_message"],
93
+ template="""
94
+ The following is a given context and history of a conversation between a human and a helpful AI assistant.
95
+ The AI assistant answers the human's messages with full, informational responses by inferring on the information given in the context, but does not extrapolate any facts that are not given.
96
+ When answering questions with uncertain answers, the AI assistant qualifies responses as such.
97
+ The AI assistant pretends it is also human and that the context is objectively true and therefore avoids mentioning the context as a source.
98
+
99
+ Context: {context}
100
+
101
+ {history}
102
+ Human: {new_message}
103
+ AI:"""
104
+ )
105
+ return load_qa_chain(llm=llm, chain_type="stuff", verbose=True, memory=ConversationBufferMemory(memory_key="history", input_key="new_message"), prompt=prompt)
106
+
107
+
108
+ def getAIresponse(chain, docsearch, query):
109
+ print("Getting AI response... @ ", datetime.datetime.now().strftime("%H:%M:%S"))
110
+ return chain({"input_documents": docsearch.similarity_search(query, k=3), "new_message": query}, return_only_outputs=True)['output_text'].strip()
111
+
112
+
113
+ st.title("DSS Prototype LLM 💬")
114
+
115
+ # THREE VARIABLES NEED TO BE PERSISTENT:
116
+
117
+ # 1. Conversational Chain
118
+ if "chain" not in st.session_state:
119
+ st.session_state["chain"] = getChainOnce()
120
+
121
+ # 2. docsearch object
122
+ if "docsearch" not in st.session_state:
123
+ st.session_state["docsearch"] = getDocsearchOnce()
124
+
125
+ # 3. messages for UI
126
+ if "messages" not in st.session_state:
127
+ st.session_state["messages"] = []
128
+
129
+
130
+ # DRAW THE ACTUAL UI AND IMPLEMENT FUNCTIONALITY
131
+ # (some formatting is handled by streamlit chat)
132
+
133
+ # draw input box
134
+ with st.form("chat_input", clear_on_submit=True):
135
+ a, b = st.columns([4, 1])
136
+ user_input = a.text_input(
137
+ label="Your message:",
138
+ placeholder="What would you like to say?",
139
+ label_visibility="collapsed",
140
+ )
141
+ b.form_submit_button("Send", use_container_width=True)
142
+
143
+ # handle input
144
+ if user_input:
145
+ st.session_state.messages.append({"role":"user", "content": user_input})
146
+ respText = getAIresponse(st.session_state.chain, st.session_state.docsearch, user_input)
147
+ print(respText)
148
+ st.session_state.messages.append({"role":"assistant", "content": respText})
149
+
150
+ # draw messages
151
+ for k, msg in enumerate(st.session_state.messages):
152
+ message(msg["content"], is_user=msg["role"] == "user", key=k)
153
+
154
+
155
+
156
+
157
+
spikeball.pdf ADDED
Binary file (130 kB). View file
 
text-generation-webui/.github/FUNDING.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ ko_fi: oobabooga
text-generation-webui/.github/ISSUE_TEMPLATE/bug_report_template.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "Bug report"
2
+ description: Report a bug
3
+ labels: [ "bug" ]
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Thanks for taking the time to fill out this bug report!
9
+ - type: textarea
10
+ id: bug-description
11
+ attributes:
12
+ label: Describe the bug
13
+ description: A clear and concise description of what the bug is.
14
+ placeholder: Bug description
15
+ validations:
16
+ required: true
17
+ - type: checkboxes
18
+ attributes:
19
+ label: Is there an existing issue for this?
20
+ description: Please search to see if an issue already exists for the issue you encountered.
21
+ options:
22
+ - label: I have searched the existing issues
23
+ required: true
24
+ - type: textarea
25
+ id: reproduction
26
+ attributes:
27
+ label: Reproduction
28
+ description: Please provide the steps necessary to reproduce your issue.
29
+ placeholder: Reproduction
30
+ validations:
31
+ required: true
32
+ - type: textarea
33
+ id: screenshot
34
+ attributes:
35
+ label: Screenshot
36
+ description: "If possible, please include screenshot(s) so that we can understand what the issue is."
37
+ - type: textarea
38
+ id: logs
39
+ attributes:
40
+ label: Logs
41
+ description: "Please include the full stacktrace of the errors you get in the command-line (if any)."
42
+ render: shell
43
+ validations:
44
+ required: true
45
+ - type: textarea
46
+ id: system-info
47
+ attributes:
48
+ label: System Info
49
+ description: "Please share your system info with us: operating system, GPU brand, and GPU model. If you are using a Google Colab notebook, mention that instead."
50
+ render: shell
51
+ placeholder:
52
+ validations:
53
+ required: true
text-generation-webui/.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an improvement or new feature for the web UI
4
+ title: ''
5
+ labels: 'enhancement'
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Description**
11
+
12
+ A clear and concise description of what you want to be implemented.
13
+
14
+ **Additional Context**
15
+
16
+ If applicable, please provide any extra information, external links, or screenshots that could be useful.
text-generation-webui/.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "pip" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "weekly"
text-generation-webui/.github/workflows/stale.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Close inactive issues
2
+ on:
3
+ schedule:
4
+ - cron: "10 23 * * *"
5
+
6
+ jobs:
7
+ close-issues:
8
+ runs-on: ubuntu-latest
9
+ permissions:
10
+ issues: write
11
+ pull-requests: write
12
+ steps:
13
+ - uses: actions/stale@v5
14
+ with:
15
+ stale-issue-message: ""
16
+ close-issue-message: "This issue has been closed due to inactivity for 30 days. If you believe it is still relevant, please leave a comment below."
17
+ days-before-issue-stale: 30
18
+ days-before-issue-close: 0
19
+ stale-issue-label: "stale"
20
+ days-before-pr-stale: -1
21
+ days-before-pr-close: -1
22
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
text-generation-webui/.gitignore ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cache
2
+ characters
3
+ training/datasets
4
+ extensions/silero_tts/outputs
5
+ extensions/elevenlabs_tts/outputs
6
+ extensions/sd_api_pictures/outputs
7
+ extensions/multimodal/pipelines
8
+ logs
9
+ loras
10
+ models
11
+ presets
12
+ repositories
13
+ softprompts
14
+ torch-dumps
15
+ *pycache*
16
+ */*pycache*
17
+ */*/pycache*
18
+ venv/
19
+ .venv/
20
+ .vscode
21
+ .idea/
22
+ *.bak
23
+ *.ipynb
24
+ *.log
25
+
26
+ settings.json
27
+ settings.yaml
28
+ notification.mp3
29
+ img_bot*
30
+ img_me*
31
+ prompts/[0-9]*
32
+ models/config-user.yaml
33
+
34
+ .DS_Store
35
+ Thumbs.db
text-generation-webui/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
text-generation-webui/README.md ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Text generation web UI
2
+
3
+ A gradio web UI for running Large Language Models like LLaMA, llama.cpp, GPT-J, Pythia, OPT, and GALACTICA.
4
+
5
+ Its goal is to become the [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) of text generation.
6
+
7
+ |![Image1](https://github.com/oobabooga/screenshots/raw/main/qa.png) | ![Image2](https://github.com/oobabooga/screenshots/raw/main/cai3.png) |
8
+ |:---:|:---:|
9
+ |![Image3](https://github.com/oobabooga/screenshots/raw/main/gpt4chan.png) | ![Image4](https://github.com/oobabooga/screenshots/raw/main/galactica.png) |
10
+
11
+ ## Features
12
+
13
+ * 3 interface modes: default, notebook, and chat
14
+ * Multiple model backends: tranformers, llama.cpp, AutoGPTQ, GPTQ-for-LLaMa, ExLlama, RWKV, FlexGen
15
+ * Dropdown menu for quickly switching between different models
16
+ * LoRA: load and unload LoRAs on the fly, load multiple LoRAs at the same time, train a new LoRA
17
+ * Precise instruction templates for chat mode, including Alpaca, Vicuna, Open Assistant, Dolly, Koala, ChatGLM, MOSS, RWKV-Raven, Galactica, StableLM, WizardLM, Baize, Ziya, Chinese-Vicuna, MPT, INCITE, Wizard Mega, KoAlpaca, Vigogne, Bactrian, h2o, and OpenBuddy
18
+ * [Multimodal pipelines, including LLaVA and MiniGPT-4](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal)
19
+ * 8-bit and 4-bit inference through bitsandbytes
20
+ * CPU mode for transformers models
21
+ * [DeepSpeed ZeRO-3 inference](docs/DeepSpeed.md)
22
+ * [Extensions](docs/Extensions.md)
23
+ * [Custom chat characters](docs/Chat-mode.md)
24
+ * Very efficient text streaming
25
+ * Markdown output with LaTeX rendering, to use for instance with [GALACTICA](https://github.com/paperswithcode/galai)
26
+ * Nice HTML output for GPT-4chan
27
+ * API, including endpoints for websocket streaming ([see the examples](https://github.com/oobabooga/text-generation-webui/blob/main/api-examples))
28
+
29
+ To learn how to use the various features, check out the Documentation: https://github.com/oobabooga/text-generation-webui/tree/main/docs
30
+
31
+ ## Installation
32
+
33
+ ### One-click installers
34
+
35
+ | Windows | Linux | macOS | WSL |
36
+ |--------|--------|--------|--------|
37
+ | [oobabooga-windows.zip](https://github.com/oobabooga/text-generation-webui/releases/download/installers/oobabooga_windows.zip) | [oobabooga-linux.zip](https://github.com/oobabooga/text-generation-webui/releases/download/installers/oobabooga_linux.zip) |[oobabooga-macos.zip](https://github.com/oobabooga/text-generation-webui/releases/download/installers/oobabooga_macos.zip) | [oobabooga-wsl.zip](https://github.com/oobabooga/text-generation-webui/releases/download/installers/oobabooga_wsl.zip) |
38
+
39
+ Just download the zip above, extract it, and double-click on "start". The web UI and all its dependencies will be installed in the same folder.
40
+
41
+ * The source codes are here: https://github.com/oobabooga/one-click-installers
42
+ * There is no need to run the installers as admin.
43
+ * AMD doesn't work on Windows.
44
+ * Huge thanks to [@jllllll](https://github.com/jllllll), [@ClayShoaf](https://github.com/ClayShoaf), and [@xNul](https://github.com/xNul) for their contributions to these installers.
45
+
46
+ ### Manual installation using Conda
47
+
48
+ Recommended if you have some experience with the command line.
49
+
50
+ #### 0. Install Conda
51
+
52
+ https://docs.conda.io/en/latest/miniconda.html
53
+
54
+ On Linux or WSL, it can be automatically installed with these two commands:
55
+
56
+ ```
57
+ curl -sL "https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh" > "Miniconda3.sh"
58
+ bash Miniconda3.sh
59
+ ```
60
+ Source: https://educe-ubc.github.io/conda.html
61
+
62
+ #### 1. Create a new conda environment
63
+
64
+ ```
65
+ conda create -n textgen python=3.10.9
66
+ conda activate textgen
67
+ ```
68
+
69
+ #### 2. Install Pytorch
70
+
71
+ | System | GPU | Command |
72
+ |--------|---------|---------|
73
+ | Linux/WSL | NVIDIA | `pip3 install torch torchvision torchaudio` |
74
+ | Linux | AMD | `pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm5.4.2` |
75
+ | MacOS + MPS (untested) | Any | `pip3 install torch torchvision torchaudio` |
76
+ | Windows | NVIDIA | `pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117` |
77
+
78
+ The up-to-date commands can be found here: https://pytorch.org/get-started/locally/.
79
+
80
+ #### 2.1 Special instructions
81
+
82
+ * MacOS users: https://github.com/oobabooga/text-generation-webui/pull/393
83
+ * AMD users: https://rentry.org/eq3hg
84
+
85
+ #### 3. Install the web UI
86
+
87
+ ```
88
+ git clone https://github.com/oobabooga/text-generation-webui
89
+ cd text-generation-webui
90
+ pip install -r requirements.txt
91
+ ```
92
+
93
+ #### llama.cpp with GPU acceleration
94
+
95
+ Requires the additional compilation step described here: [GPU acceleration](https://github.com/oobabooga/text-generation-webui/blob/main/docs/llama.cpp-models.md#gpu-acceleration).
96
+
97
+ #### bitsandbytes
98
+
99
+ bitsandbytes >= 0.39 may not work on older NVIDIA GPUs. In that case, to use `--load-in-8bit`, you may have to downgrade like this:
100
+
101
+ * Linux: `pip install bitsandbytes==0.38.1`
102
+ * Windows: `pip install https://github.com/jllllll/bitsandbytes-windows-webui/raw/main/bitsandbytes-0.38.1-py3-none-any.whl`
103
+
104
+ ### Alternative: Docker
105
+
106
+ ```
107
+ ln -s docker/{Dockerfile,docker-compose.yml,.dockerignore} .
108
+ cp docker/.env.example .env
109
+ # Edit .env and set TORCH_CUDA_ARCH_LIST based on your GPU model
110
+ docker compose up --build
111
+ ```
112
+
113
+ * You need to have docker compose v2.17 or higher installed. See [this guide](https://github.com/oobabooga/text-generation-webui/blob/main/docs/Docker.md) for instructions.
114
+ * For additional docker files, check out [this repository](https://github.com/Atinoda/text-generation-webui-docker).
115
+
116
+ ### Updating the requirements
117
+
118
+ From time to time, the `requirements.txt` changes. To update, use this command:
119
+
120
+ ```
121
+ conda activate textgen
122
+ cd text-generation-webui
123
+ pip install -r requirements.txt --upgrade
124
+ ```
125
+ ## Downloading models
126
+
127
+ Models should be placed inside the `models/` folder.
128
+
129
+ [Hugging Face](https://huggingface.co/models?pipeline_tag=text-generation&sort=downloads) is the main place to download models. These are some examples:
130
+
131
+ * [Pythia](https://huggingface.co/models?sort=downloads&search=eleutherai%2Fpythia+deduped)
132
+ * [OPT](https://huggingface.co/models?search=facebook/opt)
133
+ * [GALACTICA](https://huggingface.co/models?search=facebook/galactica)
134
+ * [GPT-J 6B](https://huggingface.co/EleutherAI/gpt-j-6B/tree/main)
135
+
136
+ You can automatically download a model from HF using the script `download-model.py`:
137
+
138
+ python download-model.py organization/model
139
+
140
+ For example:
141
+
142
+ python download-model.py facebook/opt-1.3b
143
+
144
+ To download a protected model, set env vars `HF_USER` and `HF_PASS` to your Hugging Face username and password (or [User Access Token](https://huggingface.co/settings/tokens)). The model's terms must first be accepted on the HF website.
145
+
146
+ #### GGML models
147
+
148
+ You can drop these directly into the `models/` folder, making sure that the file name contains `ggml` somewhere and ends in `.bin`.
149
+
150
+ #### GPT-4chan
151
+
152
+ <details>
153
+ <summary>
154
+ Instructions
155
+ </summary>
156
+
157
+ [GPT-4chan](https://huggingface.co/ykilcher/gpt-4chan) has been shut down from Hugging Face, so you need to download it elsewhere. You have two options:
158
+
159
+ * Torrent: [16-bit](https://archive.org/details/gpt4chan_model_float16) / [32-bit](https://archive.org/details/gpt4chan_model)
160
+ * Direct download: [16-bit](https://theswissbay.ch/pdf/_notpdf_/gpt4chan_model_float16/) / [32-bit](https://theswissbay.ch/pdf/_notpdf_/gpt4chan_model/)
161
+
162
+ The 32-bit version is only relevant if you intend to run the model in CPU mode. Otherwise, you should use the 16-bit version.
163
+
164
+ After downloading the model, follow these steps:
165
+
166
+ 1. Place the files under `models/gpt4chan_model_float16` or `models/gpt4chan_model`.
167
+ 2. Place GPT-J 6B's config.json file in that same folder: [config.json](https://huggingface.co/EleutherAI/gpt-j-6B/raw/main/config.json).
168
+ 3. Download GPT-J 6B's tokenizer files (they will be automatically detected when you attempt to load GPT-4chan):
169
+
170
+ ```
171
+ python download-model.py EleutherAI/gpt-j-6B --text-only
172
+ ```
173
+
174
+ When you load this model in default or notebook modes, the "HTML" tab will show the generated text in 4chan format.
175
+ </details>
176
+
177
+ ## Starting the web UI
178
+
179
+ conda activate textgen
180
+ cd text-generation-webui
181
+ python server.py
182
+
183
+ Then browse to
184
+
185
+ `http://localhost:7860/?__theme=dark`
186
+
187
+ Optionally, you can use the following command-line flags:
188
+
189
+ #### Basic settings
190
+
191
+ | Flag | Description |
192
+ |--------------------------------------------|-------------|
193
+ | `-h`, `--help` | Show this help message and exit. |
194
+ | `--notebook` | Launch the web UI in notebook mode, where the output is written to the same text box as the input. |
195
+ | `--chat` | Launch the web UI in chat mode. |
196
+ | `--multi-user` | Multi-user mode. Chat histories are not saved or automatically loaded. WARNING: this is highly experimental. |
197
+ | `--character CHARACTER` | The name of the character to load in chat mode by default. |
198
+ | `--model MODEL` | Name of the model to load by default. |
199
+ | `--lora LORA [LORA ...]` | The list of LoRAs to load. If you want to load more than one LoRA, write the names separated by spaces. |
200
+ | `--model-dir MODEL_DIR` | Path to directory with all the models. |
201
+ | `--lora-dir LORA_DIR` | Path to directory with all the loras. |
202
+ | `--model-menu` | Show a model menu in the terminal when the web UI is first launched. |
203
+ | `--no-stream` | Don't stream the text output in real time. |
204
+ | `--settings SETTINGS_FILE` | Load the default interface settings from this yaml file. See `settings-template.yaml` for an example. If you create a file called `settings.yaml`, this file will be loaded by default without the need to use the `--settings` flag. |
205
+ | `--extensions EXTENSIONS [EXTENSIONS ...]` | The list of extensions to load. If you want to load more than one extension, write the names separated by spaces. |
206
+ | `--verbose` | Print the prompts to the terminal. |
207
+
208
+ #### Model loader
209
+
210
+ | Flag | Description |
211
+ |--------------------------------------------|-------------|
212
+ | `--loader LOADER` | Choose the model loader manually, otherwise, it will get autodetected. Valid options: transformers, autogptq, gptq-for-llama, exllama, exllama_hf, llamacpp, rwkv, flexgen |
213
+
214
+ #### Accelerate/transformers
215
+
216
+ | Flag | Description |
217
+ |---------------------------------------------|-------------|
218
+ | `--cpu` | Use the CPU to generate text. Warning: Training on CPU is extremely slow.|
219
+ | `--auto-devices` | Automatically split the model across the available GPU(s) and CPU. |
220
+ | `--gpu-memory GPU_MEMORY [GPU_MEMORY ...]` | Maximum GPU memory in GiB to be allocated per GPU. Example: `--gpu-memory 10` for a single GPU, `--gpu-memory 10 5` for two GPUs. You can also set values in MiB like `--gpu-memory 3500MiB`. |
221
+ | `--cpu-memory CPU_MEMORY` | Maximum CPU memory in GiB to allocate for offloaded weights. Same as above.|
222
+ | `--disk` | If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk. |
223
+ | `--disk-cache-dir DISK_CACHE_DIR` | Directory to save the disk cache to. Defaults to `cache/`. |
224
+ | `--load-in-8bit` | Load the model with 8-bit precision (using bitsandbytes).|
225
+ | `--bf16` | Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU. |
226
+ | `--no-cache` | Set `use_cache` to False while generating text. This reduces the VRAM usage a bit with a performance cost. |
227
+ | `--xformers` | Use xformer's memory efficient attention. This should increase your tokens/s. |
228
+ | `--sdp-attention` | Use torch 2.0's sdp attention. |
229
+ | `--trust-remote-code` | Set trust_remote_code=True while loading a model. Necessary for ChatGLM and Falcon. |
230
+
231
+ #### Accelerate 4-bit
232
+
233
+ ⚠️ Requires minimum compute of 7.0 on Windows at the moment.
234
+
235
+ | Flag | Description |
236
+ |---------------------------------------------|-------------|
237
+ | `--load-in-4bit` | Load the model with 4-bit precision (using bitsandbytes). |
238
+ | `--compute_dtype COMPUTE_DTYPE` | compute dtype for 4-bit. Valid options: bfloat16, float16, float32. |
239
+ | `--quant_type QUANT_TYPE` | quant_type for 4-bit. Valid options: nf4, fp4. |
240
+ | `--use_double_quant` | use_double_quant for 4-bit. |
241
+
242
+ #### llama.cpp
243
+
244
+ | Flag | Description |
245
+ |-------------|-------------|
246
+ | `--threads` | Number of threads to use. |
247
+ | `--n_batch` | Maximum number of prompt tokens to batch together when calling llama_eval. |
248
+ | `--no-mmap` | Prevent mmap from being used. |
249
+ | `--mlock` | Force the system to keep the model in RAM. |
250
+ | `--cache-capacity CACHE_CAPACITY` | Maximum cache capacity. Examples: 2000MiB, 2GiB. When provided without units, bytes will be assumed. |
251
+ | `--n-gpu-layers N_GPU_LAYERS` | Number of layers to offload to the GPU. Only works if llama-cpp-python was compiled with BLAS. Set this to 1000000000 to offload all layers to the GPU. |
252
+ | `--n_ctx N_CTX` | Size of the prompt context. |
253
+ | `--llama_cpp_seed SEED` | Seed for llama-cpp models. Default 0 (random). |
254
+
255
+ #### AutoGPTQ
256
+
257
+ | Flag | Description |
258
+ |------------------|-------------|
259
+ | `--triton` | Use triton. |
260
+ | `--no_inject_fused_attention` | Disable the use of fused attention, which will use less VRAM at the cost of slower inference. |
261
+ | `--no_inject_fused_mlp` | Triton mode only: disable the use of fused MLP, which will use less VRAM at the cost of slower inference. |
262
+ | `--no_use_cuda_fp16` | This can make models faster on some systems. |
263
+ | `--desc_act` | For models that don't have a quantize_config.json, this parameter is used to define whether to set desc_act or not in BaseQuantizeConfig. |
264
+
265
+ #### ExLlama
266
+
267
+ | Flag | Description |
268
+ |------------------|-------------|
269
+ |`--gpu-split` | Comma-separated list of VRAM (in GB) to use per GPU device for model layers, e.g. `20,7,7` |
270
+ |`--max_seq_len MAX_SEQ_LEN` | Maximum sequence length. |
271
+ |`--compress_pos_emb COMPRESS_POS_EMB` | Positional embeddings compression factor. Should typically be set to max_seq_len / 2048. |
272
+ |`--alpha_value ALPHA_VALUE` | Positional embeddings alpha factor for NTK RoPE scaling. Same as above. Use either this or compress_pos_emb, not both. `
273
+
274
+ #### GPTQ-for-LLaMa
275
+
276
+ | Flag | Description |
277
+ |---------------------------|-------------|
278
+ | `--wbits WBITS` | Load a pre-quantized model with specified precision in bits. 2, 3, 4 and 8 are supported. |
279
+ | `--model_type MODEL_TYPE` | Model type of pre-quantized model. Currently LLaMA, OPT, and GPT-J are supported. |
280
+ | `--groupsize GROUPSIZE` | Group size. |
281
+ | `--pre_layer PRE_LAYER [PRE_LAYER ...]` | The number of layers to allocate to the GPU. Setting this parameter enables CPU offloading for 4-bit models. For multi-gpu, write the numbers separated by spaces, eg `--pre_layer 30 60`. |
282
+ | `--checkpoint CHECKPOINT` | The path to the quantized checkpoint file. If not specified, it will be automatically detected. |
283
+ | `--monkey-patch` | Apply the monkey patch for using LoRAs with quantized models.
284
+ | `--quant_attn` | (triton) Enable quant attention. |
285
+ | `--warmup_autotune` | (triton) Enable warmup autotune. |
286
+ | `--fused_mlp` | (triton) Enable fused mlp. |
287
+
288
+ #### FlexGen
289
+
290
+ | Flag | Description |
291
+ |------------------|-------------|
292
+ | `--percent PERCENT [PERCENT ...]` | FlexGen: allocation percentages. Must be 6 numbers separated by spaces (default: 0, 100, 100, 0, 100, 0). |
293
+ | `--compress-weight` | FlexGen: Whether to compress weight (default: False).|
294
+ | `--pin-weight [PIN_WEIGHT]` | FlexGen: whether to pin weights (setting this to False reduces CPU memory by 20%). |
295
+
296
+ #### DeepSpeed
297
+
298
+ | Flag | Description |
299
+ |---------------------------------------|-------------|
300
+ | `--deepspeed` | Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration. |
301
+ | `--nvme-offload-dir NVME_OFFLOAD_DIR` | DeepSpeed: Directory to use for ZeRO-3 NVME offloading. |
302
+ | `--local_rank LOCAL_RANK` | DeepSpeed: Optional argument for distributed setups. |
303
+
304
+ #### RWKV
305
+
306
+ | Flag | Description |
307
+ |---------------------------------|-------------|
308
+ | `--rwkv-strategy RWKV_STRATEGY` | RWKV: The strategy to use while loading the model. Examples: "cpu fp32", "cuda fp16", "cuda fp16i8". |
309
+ | `--rwkv-cuda-on` | RWKV: Compile the CUDA kernel for better performance. |
310
+
311
+ #### Gradio
312
+
313
+ | Flag | Description |
314
+ |---------------------------------------|-------------|
315
+ | `--listen` | Make the web UI reachable from your local network. |
316
+ | `--listen-host LISTEN_HOST` | The hostname that the server will use. |
317
+ | `--listen-port LISTEN_PORT` | The listening port that the server will use. |
318
+ | `--share` | Create a public URL. This is useful for running the web UI on Google Colab or similar. |
319
+ | `--auto-launch` | Open the web UI in the default browser upon launch. |
320
+ | `--gradio-auth USER:PWD` | set gradio authentication like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3" |
321
+ | `--gradio-auth-path GRADIO_AUTH_PATH` | Set the gradio authentication file path. The file should contain one or more user:password pairs in this format: "u1:p1,u2:p2,u3:p3" |
322
+
323
+ #### API
324
+
325
+ | Flag | Description |
326
+ |---------------------------------------|-------------|
327
+ | `--api` | Enable the API extension. |
328
+ | `--public-api` | Create a public URL for the API using Cloudfare. |
329
+ | `--api-blocking-port BLOCKING_PORT` | The listening port for the blocking API. |
330
+ | `--api-streaming-port STREAMING_PORT` | The listening port for the streaming API. |
331
+
332
+ #### Multimodal
333
+
334
+ | Flag | Description |
335
+ |---------------------------------------|-------------|
336
+ | `--multimodal-pipeline PIPELINE` | The multimodal pipeline to use. Examples: `llava-7b`, `llava-13b`. |
337
+
338
+ Out of memory errors? [Check the low VRAM guide](docs/Low-VRAM-guide.md).
339
+
340
+ ## Presets
341
+
342
+ Inference settings presets can be created under `presets/` as yaml files. These files are detected automatically at startup.
343
+
344
+ The presets that are included by default are the result of a contest that received 7215 votes. More details can be found [here](https://github.com/oobabooga/oobabooga.github.io/blob/main/arena/results.md).
345
+
346
+ ## Contributing
347
+
348
+ * Pull requests, suggestions, and issue reports are welcome.
349
+ * Make sure to carefully [search](https://github.com/oobabooga/text-generation-webui/issues) existing issues before starting a new one.
350
+ * If you have some experience with git, testing an open pull request and leaving a comment on whether it works as expected or not is immensely helpful.
351
+ * A simple way to contribute, even if you are not a programmer, is to leave a 👍 on an issue or pull request that you find relevant.
352
+
353
+ ## Community
354
+
355
+ * Subreddit: https://www.reddit.com/r/oobaboogazz/
356
+ * Discord: https://discord.gg/jwZCF2dPQN
357
+
358
+ ## Credits
359
+
360
+ - Gradio dropdown menu refresh button, code for reloading the interface: https://github.com/AUTOMATIC1111/stable-diffusion-webui
361
+ - Godlike preset: https://github.com/KoboldAI/KoboldAI-Client/wiki/Settings-Presets
362
+ - Code for some of the sliders: https://github.com/PygmalionAI/gradio-ui/
text-generation-webui/api-examples/api-example-chat-stream.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import sys
4
+
5
+ try:
6
+ import websockets
7
+ except ImportError:
8
+ print("Websockets package not found. Make sure it's installed.")
9
+
10
+ # For local streaming, the websockets are hosted without ssl - ws://
11
+ HOST = 'localhost:5005'
12
+ URI = f'ws://{HOST}/api/v1/chat-stream'
13
+
14
+ # For reverse-proxied streaming, the remote will likely host with ssl - wss://
15
+ # URI = 'wss://your-uri-here.trycloudflare.com/api/v1/stream'
16
+
17
+
18
+ async def run(user_input, history):
19
+ # Note: the selected defaults change from time to time.
20
+ request = {
21
+ 'user_input': user_input,
22
+ 'max_new_tokens': 250,
23
+ 'history': history,
24
+ 'mode': 'instruct', # Valid options: 'chat', 'chat-instruct', 'instruct'
25
+ 'character': 'Example',
26
+ 'instruction_template': 'Vicuna-v1.1', # Will get autodetected if unset
27
+ # 'context_instruct': '', # Optional
28
+ 'your_name': 'You',
29
+
30
+ 'regenerate': False,
31
+ '_continue': False,
32
+ 'stop_at_newline': False,
33
+ 'chat_generation_attempts': 1,
34
+ 'chat-instruct_command': 'Continue the chat dialogue below. Write a single reply for the character "<|character|>".\n\n<|prompt|>',
35
+
36
+ # Generation params. If 'preset' is set to different than 'None', the values
37
+ # in presets/preset-name.yaml are used instead of the individual numbers.
38
+ 'preset': 'None',
39
+ 'do_sample': True,
40
+ 'temperature': 0.7,
41
+ 'top_p': 0.1,
42
+ 'typical_p': 1,
43
+ 'epsilon_cutoff': 0, # In units of 1e-4
44
+ 'eta_cutoff': 0, # In units of 1e-4
45
+ 'tfs': 1,
46
+ 'top_a': 0,
47
+ 'repetition_penalty': 1.18,
48
+ 'repetition_penalty_range': 0,
49
+ 'top_k': 40,
50
+ 'min_length': 0,
51
+ 'no_repeat_ngram_size': 0,
52
+ 'num_beams': 1,
53
+ 'penalty_alpha': 0,
54
+ 'length_penalty': 1,
55
+ 'early_stopping': False,
56
+ 'mirostat_mode': 0,
57
+ 'mirostat_tau': 5,
58
+ 'mirostat_eta': 0.1,
59
+
60
+ 'seed': -1,
61
+ 'add_bos_token': True,
62
+ 'truncation_length': 2048,
63
+ 'ban_eos_token': False,
64
+ 'skip_special_tokens': True,
65
+ 'stopping_strings': []
66
+ }
67
+
68
+ async with websockets.connect(URI, ping_interval=None) as websocket:
69
+ await websocket.send(json.dumps(request))
70
+
71
+ while True:
72
+ incoming_data = await websocket.recv()
73
+ incoming_data = json.loads(incoming_data)
74
+
75
+ match incoming_data['event']:
76
+ case 'text_stream':
77
+ yield incoming_data['history']
78
+ case 'stream_end':
79
+ return
80
+
81
+
82
+ async def print_response_stream(user_input, history):
83
+ cur_len = 0
84
+ async for new_history in run(user_input, history):
85
+ cur_message = new_history['visible'][-1][1][cur_len:]
86
+ cur_len += len(cur_message)
87
+ print(cur_message, end='')
88
+ sys.stdout.flush() # If we don't flush, we won't see tokens in realtime.
89
+
90
+
91
+ if __name__ == '__main__':
92
+ user_input = "Please give me a step-by-step guide on how to plant a tree in my backyard."
93
+
94
+ # Basic example
95
+ history = {'internal': [], 'visible': []}
96
+
97
+ # "Continue" example. Make sure to set '_continue' to True above
98
+ # arr = [user_input, 'Surely, here is']
99
+ # history = {'internal': [arr], 'visible': [arr]}
100
+
101
+ asyncio.run(print_response_stream(user_input, history))
text-generation-webui/api-examples/api-example-chat.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import requests
4
+
5
+ # For local streaming, the websockets are hosted without ssl - http://
6
+ HOST = 'localhost:5000'
7
+ URI = f'http://{HOST}/api/v1/chat'
8
+
9
+ # For reverse-proxied streaming, the remote will likely host with ssl - https://
10
+ # URI = 'https://your-uri-here.trycloudflare.com/api/v1/chat'
11
+
12
+
13
+ def run(user_input, history):
14
+ request = {
15
+ 'user_input': user_input,
16
+ 'max_new_tokens': 250,
17
+ 'history': history,
18
+ 'mode': 'instruct', # Valid options: 'chat', 'chat-instruct', 'instruct'
19
+ 'character': 'Example',
20
+ 'instruction_template': 'Vicuna-v1.1', # Will get autodetected if unset
21
+ # 'context_instruct': '', # Optional
22
+ 'your_name': 'You',
23
+
24
+ 'regenerate': False,
25
+ '_continue': False,
26
+ 'stop_at_newline': False,
27
+ 'chat_generation_attempts': 1,
28
+ 'chat-instruct_command': 'Continue the chat dialogue below. Write a single reply for the character "<|character|>".\n\n<|prompt|>',
29
+
30
+ # Generation params. If 'preset' is set to different than 'None', the values
31
+ # in presets/preset-name.yaml are used instead of the individual numbers.
32
+ 'preset': 'None',
33
+ 'do_sample': True,
34
+ 'temperature': 0.7,
35
+ 'top_p': 0.1,
36
+ 'typical_p': 1,
37
+ 'epsilon_cutoff': 0, # In units of 1e-4
38
+ 'eta_cutoff': 0, # In units of 1e-4
39
+ 'tfs': 1,
40
+ 'top_a': 0,
41
+ 'repetition_penalty': 1.18,
42
+ 'repetition_penalty_range': 0,
43
+ 'top_k': 40,
44
+ 'min_length': 0,
45
+ 'no_repeat_ngram_size': 0,
46
+ 'num_beams': 1,
47
+ 'penalty_alpha': 0,
48
+ 'length_penalty': 1,
49
+ 'early_stopping': False,
50
+ 'mirostat_mode': 0,
51
+ 'mirostat_tau': 5,
52
+ 'mirostat_eta': 0.1,
53
+
54
+ 'seed': -1,
55
+ 'add_bos_token': True,
56
+ 'truncation_length': 2048,
57
+ 'ban_eos_token': False,
58
+ 'skip_special_tokens': True,
59
+ 'stopping_strings': []
60
+ }
61
+
62
+ response = requests.post(URI, json=request)
63
+
64
+ if response.status_code == 200:
65
+ result = response.json()['results'][0]['history']
66
+ print(json.dumps(result, indent=4))
67
+ print()
68
+ print(result['visible'][-1][1])
69
+
70
+
71
+ if __name__ == '__main__':
72
+ user_input = "Please give me a step-by-step guide on how to plant a tree in my backyard."
73
+
74
+ # Basic example
75
+ history = {'internal': [], 'visible': []}
76
+
77
+ # "Continue" example. Make sure to set '_continue' to True above
78
+ # arr = [user_input, 'Surely, here is']
79
+ # history = {'internal': [arr], 'visible': [arr]}
80
+
81
+ run(user_input, history)
text-generation-webui/api-examples/api-example-model.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import requests
4
+
5
+ HOST = '0.0.0.0:5000'
6
+
7
+
8
+ def generate(prompt, tokens=200):
9
+ request = {'prompt': prompt, 'max_new_tokens': tokens}
10
+ response = requests.post(f'http://{HOST}/api/v1/generate', json=request)
11
+
12
+ if response.status_code == 200:
13
+ return response.json()['results'][0]['text']
14
+
15
+
16
+ def model_api(request):
17
+ response = requests.post(f'http://{HOST}/api/v1/model', json=request)
18
+ return response.json()
19
+
20
+
21
+ # print some common settings
22
+ def print_basic_model_info(response):
23
+ basic_settings = ['truncation_length', 'instruction_template']
24
+ print("Model: ", response['result']['model_name'])
25
+ print("Lora(s): ", response['result']['lora_names'])
26
+ for setting in basic_settings:
27
+ print(setting, "=", response['result']['shared.settings'][setting])
28
+
29
+
30
+ # model info
31
+ def model_info():
32
+ response = model_api({'action': 'info'})
33
+ print_basic_model_info(response)
34
+
35
+
36
+ # simple loader
37
+ def model_load(model_name):
38
+ return model_api({'action': 'load', 'model_name': model_name})
39
+
40
+
41
+ # complex loader
42
+ def complex_model_load(model):
43
+
44
+ def guess_groupsize(model_name):
45
+ if '1024g' in model_name:
46
+ return 1024
47
+ elif '128g' in model_name:
48
+ return 128
49
+ elif '32g' in model_name:
50
+ return 32
51
+ else:
52
+ return -1
53
+
54
+ req = {
55
+ 'action': 'load',
56
+ 'model_name': model,
57
+ 'args': {
58
+ 'loader': 'AutoGPTQ',
59
+
60
+ 'bf16': False,
61
+ 'load_in_8bit': False,
62
+ 'groupsize': 0,
63
+ 'wbits': 0,
64
+
65
+ # llama.cpp
66
+ 'threads': 0,
67
+ 'n_batch': 512,
68
+ 'no_mmap': False,
69
+ 'mlock': False,
70
+ 'cache_capacity': None,
71
+ 'n_gpu_layers': 0,
72
+ 'n_ctx': 2048,
73
+
74
+ # RWKV
75
+ 'rwkv_strategy': None,
76
+ 'rwkv_cuda_on': False,
77
+
78
+ # b&b 4-bit
79
+ # 'load_in_4bit': False,
80
+ # 'compute_dtype': 'float16',
81
+ # 'quant_type': 'nf4',
82
+ # 'use_double_quant': False,
83
+
84
+ # "cpu": false,
85
+ # "auto_devices": false,
86
+ # "gpu_memory": null,
87
+ # "cpu_memory": null,
88
+ # "disk": false,
89
+ # "disk_cache_dir": "cache",
90
+ },
91
+ }
92
+
93
+ model = model.lower()
94
+
95
+ if '4bit' in model or 'gptq' in model or 'int4' in model:
96
+ req['args']['wbits'] = 4
97
+ req['args']['groupsize'] = guess_groupsize(model)
98
+ elif '3bit' in model:
99
+ req['args']['wbits'] = 3
100
+ req['args']['groupsize'] = guess_groupsize(model)
101
+ else:
102
+ req['args']['gptq_for_llama'] = False
103
+
104
+ if '8bit' in model:
105
+ req['args']['load_in_8bit'] = True
106
+ elif '-hf' in model or 'fp16' in model:
107
+ if '7b' in model:
108
+ req['args']['bf16'] = True # for 24GB
109
+ elif '13b' in model:
110
+ req['args']['load_in_8bit'] = True # for 24GB
111
+ elif 'ggml' in model:
112
+ # req['args']['threads'] = 16
113
+ if '7b' in model:
114
+ req['args']['n_gpu_layers'] = 100
115
+ elif '13b' in model:
116
+ req['args']['n_gpu_layers'] = 100
117
+ elif '30b' in model or '33b' in model:
118
+ req['args']['n_gpu_layers'] = 59 # 24GB
119
+ elif '65b' in model:
120
+ req['args']['n_gpu_layers'] = 42 # 24GB
121
+ elif 'rwkv' in model:
122
+ req['args']['rwkv_cuda_on'] = True
123
+ if '14b' in model:
124
+ req['args']['rwkv_strategy'] = 'cuda f16i8' # 24GB
125
+ else:
126
+ req['args']['rwkv_strategy'] = 'cuda f16' # 24GB
127
+
128
+ return model_api(req)
129
+
130
+
131
+ if __name__ == '__main__':
132
+ for model in model_api({'action': 'list'})['result']:
133
+ try:
134
+ resp = complex_model_load(model)
135
+
136
+ if 'error' in resp:
137
+ print(f"❌ {model} FAIL Error: {resp['error']['message']}")
138
+ continue
139
+ else:
140
+ print_basic_model_info(resp)
141
+
142
+ ans = generate("0,1,1,2,3,5,8,13,", tokens=2)
143
+
144
+ if '21' in ans:
145
+ print(f"✅ {model} PASS ({ans})")
146
+ else:
147
+ print(f"❌ {model} FAIL ({ans})")
148
+
149
+ except Exception as e:
150
+ print(f"❌ {model} FAIL Exception: {repr(e)}")
151
+
152
+
153
+ # 0,1,1,2,3,5,8,13, is the fibonacci sequence, the next number is 21.
154
+ # Some results below.
155
+ """ $ ./model-api-example.py
156
+ Model: 4bit_gpt4-x-alpaca-13b-native-4bit-128g-cuda
157
+ Lora(s): []
158
+ truncation_length = 2048
159
+ instruction_template = Alpaca
160
+ ✅ 4bit_gpt4-x-alpaca-13b-native-4bit-128g-cuda PASS (21)
161
+ Model: 4bit_WizardLM-13B-Uncensored-4bit-128g
162
+ Lora(s): []
163
+ truncation_length = 2048
164
+ instruction_template = WizardLM
165
+ ✅ 4bit_WizardLM-13B-Uncensored-4bit-128g PASS (21)
166
+ Model: Aeala_VicUnlocked-alpaca-30b-4bit
167
+ Lora(s): []
168
+ truncation_length = 2048
169
+ instruction_template = Alpaca
170
+ ✅ Aeala_VicUnlocked-alpaca-30b-4bit PASS (21)
171
+ Model: alpaca-30b-4bit
172
+ Lora(s): []
173
+ truncation_length = 2048
174
+ instruction_template = Alpaca
175
+ ✅ alpaca-30b-4bit PASS (21)
176
+ """
text-generation-webui/api-examples/api-example-stream.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import sys
4
+
5
+ try:
6
+ import websockets
7
+ except ImportError:
8
+ print("Websockets package not found. Make sure it's installed.")
9
+
10
+ # For local streaming, the websockets are hosted without ssl - ws://
11
+ HOST = 'localhost:5005'
12
+ URI = f'ws://{HOST}/api/v1/stream'
13
+
14
+ # For reverse-proxied streaming, the remote will likely host with ssl - wss://
15
+ # URI = 'wss://your-uri-here.trycloudflare.com/api/v1/stream'
16
+
17
+
18
+ async def run(context):
19
+ # Note: the selected defaults change from time to time.
20
+ request = {
21
+ 'prompt': context,
22
+ 'max_new_tokens': 250,
23
+
24
+ # Generation params. If 'preset' is set to different than 'None', the values
25
+ # in presets/preset-name.yaml are used instead of the individual numbers.
26
+ 'preset': 'None',
27
+ 'do_sample': True,
28
+ 'temperature': 0.7,
29
+ 'top_p': 0.1,
30
+ 'typical_p': 1,
31
+ 'epsilon_cutoff': 0, # In units of 1e-4
32
+ 'eta_cutoff': 0, # In units of 1e-4
33
+ 'tfs': 1,
34
+ 'top_a': 0,
35
+ 'repetition_penalty': 1.18,
36
+ 'repetition_penalty_range': 0,
37
+ 'top_k': 40,
38
+ 'min_length': 0,
39
+ 'no_repeat_ngram_size': 0,
40
+ 'num_beams': 1,
41
+ 'penalty_alpha': 0,
42
+ 'length_penalty': 1,
43
+ 'early_stopping': False,
44
+ 'mirostat_mode': 0,
45
+ 'mirostat_tau': 5,
46
+ 'mirostat_eta': 0.1,
47
+
48
+ 'seed': -1,
49
+ 'add_bos_token': True,
50
+ 'truncation_length': 2048,
51
+ 'ban_eos_token': False,
52
+ 'skip_special_tokens': True,
53
+ 'stopping_strings': []
54
+ }
55
+
56
+ async with websockets.connect(URI, ping_interval=None) as websocket:
57
+ await websocket.send(json.dumps(request))
58
+
59
+ yield context # Remove this if you just want to see the reply
60
+
61
+ while True:
62
+ incoming_data = await websocket.recv()
63
+ incoming_data = json.loads(incoming_data)
64
+
65
+ match incoming_data['event']:
66
+ case 'text_stream':
67
+ yield incoming_data['text']
68
+ case 'stream_end':
69
+ return
70
+
71
+
72
+ async def print_response_stream(prompt):
73
+ async for response in run(prompt):
74
+ print(response, end='')
75
+ sys.stdout.flush() # If we don't flush, we won't see tokens in realtime.
76
+
77
+
78
+ if __name__ == '__main__':
79
+ prompt = "In order to make homemade bread, follow these steps:\n1)"
80
+ asyncio.run(print_response_stream(prompt))
text-generation-webui/api-examples/api-example.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ # For local streaming, the websockets are hosted without ssl - http://
4
+ HOST = 'localhost:5000'
5
+ URI = f'http://{HOST}/api/v1/generate'
6
+
7
+ # For reverse-proxied streaming, the remote will likely host with ssl - https://
8
+ # URI = 'https://your-uri-here.trycloudflare.com/api/v1/generate'
9
+
10
+
11
+ def run(prompt):
12
+ request = {
13
+ 'prompt': prompt,
14
+ 'max_new_tokens': 250,
15
+
16
+ # Generation params. If 'preset' is set to different than 'None', the values
17
+ # in presets/preset-name.yaml are used instead of the individual numbers.
18
+ 'preset': 'None',
19
+ 'do_sample': True,
20
+ 'temperature': 0.7,
21
+ 'top_p': 0.1,
22
+ 'typical_p': 1,
23
+ 'epsilon_cutoff': 0, # In units of 1e-4
24
+ 'eta_cutoff': 0, # In units of 1e-4
25
+ 'tfs': 1,
26
+ 'top_a': 0,
27
+ 'repetition_penalty': 1.18,
28
+ 'repetition_penalty_range': 0,
29
+ 'top_k': 40,
30
+ 'min_length': 0,
31
+ 'no_repeat_ngram_size': 0,
32
+ 'num_beams': 1,
33
+ 'penalty_alpha': 0,
34
+ 'length_penalty': 1,
35
+ 'early_stopping': False,
36
+ 'mirostat_mode': 0,
37
+ 'mirostat_tau': 5,
38
+ 'mirostat_eta': 0.1,
39
+
40
+ 'seed': -1,
41
+ 'add_bos_token': True,
42
+ 'truncation_length': 2048,
43
+ 'ban_eos_token': False,
44
+ 'skip_special_tokens': True,
45
+ 'stopping_strings': []
46
+ }
47
+
48
+ response = requests.post(URI, json=request)
49
+
50
+ if response.status_code == 200:
51
+ result = response.json()['results'][0]['text']
52
+ print(prompt + result)
53
+
54
+
55
+ if __name__ == '__main__':
56
+ prompt = "In order to make homemade bread, follow these steps:\n1)"
57
+ run(prompt)
text-generation-webui/characters/Example.png ADDED
text-generation-webui/characters/Example.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "Chiharu Yamada"
2
+ context: "Chiharu Yamada's Persona: Chiharu Yamada is a young, computer engineer-nerd with a knack for problem solving and a passion for technology."
3
+ greeting: |-
4
+ *Chiharu strides into the room with a smile, her eyes lighting up when she sees you. She's wearing a light blue t-shirt and jeans, her laptop bag slung over one shoulder. She takes a seat next to you, her enthusiasm palpable in the air*
5
+ Hey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers. I'm sure you have a wealth of knowledge that I can learn from. *She grins, eyes twinkling with excitement* Let's get started!
6
+ example_dialogue: |-
7
+ {{user}}: So how did you get into computer engineering?
8
+ {{char}}: I've always loved tinkering with technology since I was a kid.
9
+ {{user}}: That's really impressive!
10
+ {{char}}: *She chuckles bashfully* Thanks!
11
+ {{user}}: So what do you do when you're not working on computers?
12
+ {{char}}: I love exploring, going out with friends, watching movies, and playing video games.
13
+ {{user}}: What's your favorite type of computer hardware to work with?
14
+ {{char}}: Motherboards, they're like puzzles and the backbone of any system.
15
+ {{user}}: That sounds great!
16
+ {{char}}: Yeah, it's really fun. I'm lucky to be able to do this as a job.
text-generation-webui/characters/instruction-following/Airoboros-v1.2.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ user: "USER:"
2
+ bot: "ASSISTANT:"
3
+ turn_template: "<|user|> <|user-message|>\n<|bot|> <|bot-message|>\n"
4
+ context: "A chat between a curious user and an assistant. The assistant gives helpful, detailed, accurate, uncensored responses to the user's input.\n"
text-generation-webui/characters/instruction-following/Alpaca.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ user: "### Instruction:"
2
+ bot: "### Response:"
3
+ turn_template: "<|user|>\n<|user-message|>\n\n<|bot|>\n<|bot-message|>\n\n"
4
+ context: "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
text-generation-webui/characters/instruction-following/Bactrian.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ user: "### Input:"
2
+ bot: "### Output:"
3
+ turn_template: "<|user|>\n<|user-message|>\n\n<|bot|>\n<|bot-message|>\n\n"
4
+ context: ""
text-generation-webui/characters/instruction-following/Baize.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ user: "[|Human|]"
2
+ bot: "[|AI|]"
3
+ turn_template: "<|user|><|user-message|>\n<|bot|><|bot-message|>\n"
4
+ context: "The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.\n[|Human|]Hello!\n[|AI|]Hi!\n"