mkumar87AI commited on
Commit
f4d8de3
β€’
1 Parent(s): 7c629c6

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -0
app.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """SimpleChatBot_OpenSourceModel.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1q7EXhcR6gncrcwySFbN7u9fOIwTc4LtD
8
+
9
+ ##*** Note : *** You will be NOT be charged for this exercise. Everything is OpenSource
10
+
11
+ ### This notebook presents how to make a simple conversational chatbot using Open Source language model that we will download from hugging-face hub
12
+
13
+ ### Fix the UTF-8 encoding
14
+ """
15
+
16
+ import locale
17
+ locale.getpreferredencoding = lambda: "UTF-8"
18
+
19
+ """### Install the python packages. They are need to execute necessary to make the program work"""
20
+
21
+ pip install -qq -U langchain transformers sentence-transformers bitsandbytes accelerate
22
+
23
+ !pip install git+https://github.com/huggingface/transformers@v4.31-release
24
+
25
+ !pip install transformers -U
26
+
27
+ """### Import the necessary libraries"""
28
+
29
+ from langchain.llms.huggingface_pipeline import HuggingFacePipeline
30
+ import torch
31
+ from transformers import AutoModelForCausalLM, AutoTokenizer
32
+ from transformers import BitsAndBytesConfig
33
+ from langchain.chains import LLMChain
34
+ from langchain.prompts import PromptTemplate
35
+ from langchain.embeddings import (OpenAIEmbeddings, HuggingFaceEmbeddings)
36
+ from langchain.schema import StrOutputParser
37
+ from langchain.schema.runnable import RunnablePassthrough
38
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
39
+ from langchain.vectorstores import Chroma
40
+ from langchain.document_loaders import PyPDFLoader
41
+ from langchain.callbacks.manager import CallbackManager
42
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
43
+
44
+ """### Select and download the model from Hugging face
45
+
46
+ #### Hugging face hub contains a lot of pre-trained AI models related to computer vision, NLP, etc. For our task, we would need to use a text-generation model. Follow the steps below to choose and download a model
47
+
48
+ 1. Go to this link -> https://huggingface.co/models?pipeline_tag=text-generation&sort=trending
49
+
50
+ 2. For this example, we will be using the Mitsral 7B Instruct v0.2 [https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2]
51
+ """
52
+
53
+ torch.set_default_device("cuda")
54
+
55
+ model_id = "mistralai/Mistral-7B-Instruct-v0.2"
56
+ model = AutoModelForCausalLM.from_pretrained(model_id,
57
+ device_map='auto',
58
+ torch_dtype="auto",
59
+ load_in_4bit=True,
60
+ trust_remote_code=True,
61
+ low_cpu_mem_usage=True)
62
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
63
+
64
+ """### Setup the pipeline using tokenizer and model
65
+
66
+ """
67
+
68
+ from transformers import pipeline
69
+
70
+ pipe = pipeline(
71
+ task = "text-generation",
72
+ model = model,
73
+ tokenizer = tokenizer,
74
+ pad_token_id = tokenizer.eos_token_id,
75
+ temperature = 0.3,
76
+ top_k = 50,
77
+ top_p = 0.95,
78
+ max_new_tokens=3072,
79
+ repetition_penalty = 1.2
80
+ )
81
+
82
+ """### Create an llm object"""
83
+
84
+ llm = HuggingFacePipeline(pipeline = pipe)
85
+
86
+ """### Create a simple prompt tempelate using Langchain framework"""
87
+
88
+ template = """
89
+ "<s>[INST] You are a question and answering bot
90
+ You always respond with a funny twist, and keep your
91
+ answers short. Now answer this Question : {question}.
92
+ To keep you more stateful, you also get help with previous
93
+ chat history : {chat_history}[/INST]
94
+ """
95
+ prompt = PromptTemplate(template=template, input_variables=["question", "chat_history"])
96
+
97
+ """### Create an llm chain"""
98
+
99
+ llm_chain = LLMChain(prompt=prompt, llm=llm)
100
+
101
+ """### Try invoking the LLM, with a simple chain"""
102
+
103
+ def ask_me_chat_completions(query, chat_history, llm_chain):
104
+ response = llm_chain.run({"question":query,"chat_history":chat_history})
105
+ return response
106
+
107
+ """### Question and Answer segment
108
+
109
+ #### **Activity : ** Try the following things
110
+
111
+ 1. Search on the internet regarding the context length of the model
112
+ Check when does the model reach its context limit and stops responding ?
113
+ 2. Can you do anything in the prompt to fit more conversations in the context length ?
114
+ 3. Can you programtically increase the context window ?
115
+ 4. Can you programatically make the memory management better ?
116
+ """
117
+
118
+ query = None
119
+ chat_history = []
120
+ while query != "q":
121
+ query = input("Ask your questions here, press q to quit: ")
122
+ if query != "q":
123
+ response = ask_me_chat_completions(query, chat_history, llm_chain)
124
+ print(f'Your query returned the following response: {response}')
125
+ chat_history.append(response)