vikaskookna commited on
Commit
5d38eed
·
1 Parent(s): 0930722

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -16
app.py CHANGED
@@ -2,22 +2,123 @@ import gradio as gr
2
  import os
3
  from langchain.agents import load_tools
4
  from langchain.agents import initialize_agent
5
- from langchain import PromptTemplate, HuggingFaceHub, LLMChain
 
6
  from langchain.llms import OpenAI
 
 
 
7
 
8
- def funct(key, sentence):
9
- os.environ["OPENAI_API_KEY"] = key
10
- llm = OpenAI(temperature=0)
11
-
12
- # Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.
13
- tools = load_tools(["serpapi", "llm-math"], llm=llm)
14
-
15
- agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- return agent.run(sentence)
 
 
 
 
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  with gr.Blocks() as app:
 
 
 
 
 
21
  with gr.Row():
22
  with gr.Column():
23
  gr.HTML(
@@ -25,9 +126,15 @@ with gr.Blocks() as app:
25
 
26
  openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...)",
27
  show_label=False, lines=1, type='password')
28
- message = gr.Textbox(label='input')
29
- sentiment = gr.Textbox(label='chatbot')
30
- submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
 
 
 
 
 
 
31
 
32
  gr.Examples(
33
  examples=["How many people live in Canada?",
@@ -40,9 +147,14 @@ with gr.Blocks() as app:
40
  "if I remove all the pairs of sunglasses from the desk, how many purple items remain on it?"],
41
  inputs=message
42
  )
 
 
43
 
44
- submit.click(fn=funct,
45
- inputs=[openai_api_key_textbox, message],
46
- outputs=sentiment)
 
 
 
47
 
48
  app.launch(debug=True)
 
2
  import os
3
  from langchain.agents import load_tools
4
  from langchain.agents import initialize_agent
5
+ from langchain import PromptTemplate, HuggingFaceHub, LLMChain, ConversationChain
6
+
7
  from langchain.llms import OpenAI
8
+ from langchain.chains.conversation.memory import ConversationBufferMemory
9
+ from threading import Lock
10
+ import openai
11
 
12
+ from openai.error import AuthenticationError, InvalidRequestError, RateLimitError
13
+ from typing import Optional, Tuple
14
+
15
+ TOOLS_DEFAULT_LIST = ['serpapi', 'pal-math']
16
+ MAX_TOKENS = 512
17
+ PROMPT_TEMPLATE = PromptTemplate(
18
+ input_variables=["original_words"],
19
+ template="Restate the following: \n{original_words}\n",
20
+ )
21
+
22
+ BUG_FOUND_MSG = "Congratulations, you've found a bug in this application!"
23
+ AUTH_ERR_MSG = "Please paste your OpenAI key."
24
+
25
+ def run_chain(chain, inp, capture_hidden_text):
26
+ output = ""
27
+ hidden_text = None
28
+ try:
29
+ output = chain.run(input=inp)
30
+ except AuthenticationError as ae:
31
+ output = AUTH_ERR_MSG
32
+ except RateLimitError as rle:
33
+ output = "\n\nRateLimitError: " + str(rle)
34
+ except ValueError as ve:
35
+ output = "\n\nValueError: " + str(ve)
36
+ except InvalidRequestError as ire:
37
+ output = "\n\nInvalidRequestError: " + str(ire)
38
+ except Exception as e:
39
+ output = "\n\n" + BUG_FOUND_MSG + ":\n\n" + str(e)
40
+
41
+ return output, hidden_text
42
+
43
+ def transform_text(desc, express_chain):
44
+
45
+ formatted_prompt = PROMPT_TEMPLATE.format(
46
+ original_words=desc
47
+ )
48
+ generated_text = desc
49
+
50
+ # replace all newlines with <br> in generated_text
51
+ generated_text = generated_text.replace("\n", "\n\n")
52
+
53
+ return generated_text
54
+
55
+ class ChatWrapper:
56
+
57
+ def __init__(self):
58
+ self.lock = Lock()
59
+
60
+ def __call__(
61
+ self, api_key: str, inp: str, history: Optional[Tuple[str, str]], chain: Optional[ConversationChain], express_chain: Optional[LLMChain]):
62
+ """Execute the chat functionality."""
63
+ self.lock.acquire()
64
+ try:
65
+ history = history or []
66
+ # If chain is None, that is because no API key was provided.
67
+ output = "Please paste your OpenAI key to use this application."
68
+ hidden_text = output
69
 
70
+ if chain and chain != "":
71
+ # Set OpenAI key
72
+ openai.api_key = api_key
73
+ output, hidden_text = run_chain(chain, inp, capture_hidden_text=False)
74
+ print('output1', output)
75
 
76
+ output = transform_text(output, express_chain)
77
+ print('output2', output)
78
+ text_to_display = output
79
+ history.append((inp, text_to_display))
80
+
81
+ except Exception as e:
82
+ raise e
83
+ finally:
84
+ self.lock.release()
85
+ # return history, history, html_video, temp_file, ""
86
+ return history, history
87
+
88
+
89
+ chat = ChatWrapper()
90
+
91
+ def load_chain(tools_list, llm):
92
+ chain = None
93
+ express_chain = None
94
+ print("\ntools_list", tools_list)
95
+ tool_names = tools_list
96
+ tools = load_tools(tool_names, llm=llm)
97
+
98
+ memory = ConversationBufferMemory(memory_key="chat_history")
99
+
100
+ chain = initialize_agent(tools, llm, agent="conversational-react-description", verbose=True, memory=memory)
101
+ express_chain = LLMChain(llm=llm, prompt=PROMPT_TEMPLATE, verbose=True)
102
+ return chain, express_chain
103
+
104
+
105
+ def set_openai_api_key(api_key):
106
+ """Set the api key and return chain.
107
+ If no api_key, then None is returned.
108
+ """
109
+
110
+ os.environ["OPENAI_API_KEY"] = api_key
111
+ llm = OpenAI(temperature=0, max_tokens=MAX_TOKENS)
112
+ chain, express_chain = load_chain(TOOLS_DEFAULT_LIST, llm)
113
+ os.environ["OPENAI_API_KEY"] = ""
114
+ return chain, express_chain, llm
115
 
116
  with gr.Blocks() as app:
117
+ llm_state = gr.State()
118
+ history_state = gr.State()
119
+ chain_state = gr.State()
120
+ express_chain_state = gr.State()
121
+
122
  with gr.Row():
123
  with gr.Column():
124
  gr.HTML(
 
126
 
127
  openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...)",
128
  show_label=False, lines=1, type='password')
129
+ with gr.Row():
130
+
131
+ with gr.Column(scale=3):
132
+ chatbot = gr.Chatbot()
133
+ with gr.Row():
134
+ message = gr.Textbox(label="What's on your mind??",
135
+ placeholder="What's the answer to life, the universe, and everything?",
136
+ lines=1)
137
+ submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
138
 
139
  gr.Examples(
140
  examples=["How many people live in Canada?",
 
147
  "if I remove all the pairs of sunglasses from the desk, how many purple items remain on it?"],
148
  inputs=message
149
  )
150
+ message.submit(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state,
151
+ express_chain_state], outputs=[chatbot, history_state])
152
 
153
+ submit.click(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state,
154
+ express_chain_state], outputs=[chatbot, history_state])
155
+
156
+ openai_api_key_textbox.change(set_openai_api_key,
157
+ inputs=[openai_api_key_textbox],
158
+ outputs=[chain_state, express_chain_state, llm_state])
159
 
160
  app.launch(debug=True)