robert commited on
Commit
c882f64
1 Parent(s): fd6729b

Updated chat app with OpenAI flow using Langchain

Browse files
Files changed (1) hide show
  1. app.py +52 -3
app.py CHANGED
@@ -1,7 +1,56 @@
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
  demo.launch()
 
1
+ import os
2
+
3
  import gradio as gr
4
+ from langchain.schema import AIMessage, HumanMessage
5
+ from langchain_openai import ChatOpenAI
6
+ from pydantic import BaseModel, SecretStr
7
+
8
+
9
+ class APIKey(BaseModel):
10
+ api_key: SecretStr
11
+
12
+
13
+ def set_api_key(api_key: SecretStr):
14
+ os.environ["OPENAI_API_KEY"] = api_key.get_secret_value()
15
+ llm = ChatOpenAI(temperature=1.0, model="gpt-3.5-turbo-0125")
16
+ return llm
17
+
18
+
19
+ def predict(message, chat_history, api_key):
20
+ api_key_model = APIKey(api_key=api_key)
21
+ llm = set_api_key(api_key_model.api_key)
22
+
23
+ history_langchain_format = []
24
+ for human, ai in chat_history:
25
+ history_langchain_format.append(HumanMessage(content=human))
26
+ history_langchain_format.append(AIMessage(content=ai))
27
+ history_langchain_format.append(HumanMessage(content=message))
28
+ openai_response = llm.invoke(history_langchain_format)
29
+ chat_history.append((message, openai_response.content))
30
+ return "", chat_history
31
+
32
+
33
+ with gr.Blocks() as demo:
34
+ with gr.Row():
35
+ api_key = gr.Textbox(
36
+ label="Please enter your OpenAI API key",
37
+ type="password",
38
+ elem_id="lets-chat-langchain-oakey",
39
+ )
40
+
41
+ with gr.Row():
42
+ msg = gr.Textbox(label="Please enter your message")
43
+
44
+ with gr.Row():
45
+ chatbot = gr.Chatbot(label="OpenAI Chatbot")
46
+
47
+ with gr.Row():
48
+ clear = gr.ClearButton([msg, chatbot])
49
+
50
+ def respond(message, chat_history, api_key):
51
+ return predict(message, chat_history, api_key)
52
 
53
+ api_key.submit(respond, [msg, chatbot, api_key], [msg, chatbot])
54
+ msg.submit(respond, [msg, chatbot, api_key], [msg, chatbot])
55
 
 
56
  demo.launch()