Bazedgul commited on
Commit
f0f4259
1 Parent(s): 71c8834

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional, Tuple
3
+
4
+ import gradio as gr
5
+ from langchain.chains import ConversationChain
6
+ from langchain.llms import OpenAI
7
+
8
+
9
+ def load_chain():
10
+ """Logic for loading the chain you want to use should go here."""
11
+ llm = OpenAI(temperature=0)
12
+ chain = ConversationChain(llm=llm)
13
+ return chain
14
+
15
+
16
+ def set_openai_api_key(api_key: str):
17
+ """Set the api key and return chain.
18
+ If no api_key, then None is returned.
19
+ """
20
+ if api_key:
21
+ os.environ["OPENAI_API_KEY"] = api_key
22
+ chain = load_chain()
23
+ os.environ["OPENAI_API_KEY"] = ""
24
+ return chain
25
+
26
+
27
+ def chat(
28
+ inp: str, history: Optional[Tuple[str, str]], chain: Optional[ConversationChain]
29
+ ):
30
+ """Execute the chat functionality."""
31
+ history = history or []
32
+ # If chain is None, that is because no API key was provided.
33
+ if chain is None:
34
+ history.append((inp, "Please paste your OpenAI key to use"))
35
+ return history, history
36
+ # Run chain and append input.
37
+ output = chain.run(input=inp)
38
+ history.append((inp, output))
39
+ return history, history
40
+
41
+
42
+ block = gr.Blocks(css=".gradio-container {background-color: lightgray}")
43
+
44
+ with block:
45
+ with gr.Row():
46
+ gr.Markdown("<h3><center>LangChain Demo</center></h3>")
47
+
48
+ openai_api_key_textbox = gr.Textbox(
49
+ placeholder="Paste your OpenAI API key (sk-...)",
50
+ show_label=False,
51
+ lines=1,
52
+ type="password",
53
+ )
54
+
55
+ chatbot = gr.Chatbot()
56
+
57
+ with gr.Row():
58
+ message = gr.Textbox(
59
+ label="What's your question?",
60
+ placeholder="What's the answer to life, the universe, and everything?",
61
+ lines=1,
62
+ )
63
+ submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
64
+
65
+ gr.Examples(
66
+ examples=[
67
+ "Hi! How's it going?",
68
+ "What should I do tonight?",
69
+ "Whats 2 + 2?",
70
+ ],
71
+ inputs=message,
72
+ )
73
+
74
+ gr.HTML("Demo application of a LangChain chain.")
75
+
76
+ gr.HTML(
77
+ "<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain 🦜️🔗</a></center>"
78
+ )
79
+
80
+ state = gr.State()
81
+ agent_state = gr.State()
82
+
83
+ submit.click(chat, inputs=[message, state, agent_state], outputs=[chatbot, state])
84
+ message.submit(chat, inputs=[message, state, agent_state], outputs=[chatbot, state])
85
+
86
+ openai_api_key_textbox.change(
87
+ set_openai_api_key,
88
+ inputs=[openai_api_key_textbox],
89
+ outputs=[agent_state],
90
+ )
91
+
92
+ block.launch(debug=True)