arrafmousa commited on
Commit
9b17d0f
·
verified ·
1 Parent(s): eeb3999

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -61
app.py CHANGED
@@ -1,64 +1,161 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
1
+ import os
2
+
3
+ # Init with fake key
4
+ if 'OPENAI_API_KEY' not in os.environ:
5
+ os.environ['OPENAI_API_KEY'] = 'none'
6
+
7
+ import openai
8
+ import pandas as pd
9
+ import streamlit as st
10
+ from IPython.core.display import HTML
11
+ from PIL import Image
12
+ from langchain.callbacks import wandb_tracing_enabled
13
+ from chemcrow.agents import ChemCrow, make_tools
14
+ from chemcrow.frontend.streamlit_callback_handler import \
15
+ StreamlitCallbackHandlerChem
16
+ from utils import oai_key_isvalid
17
+
18
+ from dotenv import load_dotenv
19
+
20
+ load_dotenv()
21
+ ss = st.session_state
22
+ ss.prompt = None
23
+
24
+ icon = Image.open('assets/logo0.png')
25
+ st.set_page_config(
26
+ page_title="ChemCrow",
27
+ page_icon = icon
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  )
29
 
30
+ # Set width of sidebar
31
+ st.markdown(
32
+ """
33
+ <style>
34
+ [data-testid="stSidebar"][aria-expanded="true"]{
35
+ min-width: 450px;
36
+ max-width: 450px;
37
+ }
38
+ """,
39
+ unsafe_allow_html=True,
40
+ )
41
+
42
+
43
+ def instantiate_agent(model):
44
+ ss.agent = ChemCrow(
45
+ model=model,
46
+ tools_model=model,
47
+ temp=0.1,
48
+ openai_api_key=ss.get('api_key'),
49
+ api_keys={
50
+ 'RXN4CHEM_API_KEY': st.secrets['RXN4CHEM_API_KEY'],
51
+ 'CHEMSPACE_API_KEY': st.secrets['CHEMSPACE_API_KEY']
52
+ }
53
+ ).agent_executor
54
+ return ss.agent
55
+
56
+ instantiate_agent('gpt-4-0613')
57
+ tools = ss.agent.tools
58
+
59
+ tool_list = pd.Series(
60
+ {f"✅ {t.name}":t.description for t in tools}
61
+ ).reset_index()
62
+ tool_list.columns = ['Tool', 'Description']
63
+
64
+ def on_api_key_change():
65
+ api_key = ss.get('api_key') or os.getenv('OPENAI_API_KEY')
66
+ # Check if key is valid
67
+ if not oai_key_isvalid(api_key):
68
+ st.write("Please input a valid OpenAI API key.")
69
+
70
+ def run_prompt(prompt):
71
+ agent = instantiate_agent(ss.get('model_select'))
72
+ st.chat_message("user").write(prompt)
73
+ with st.chat_message("assistant"):
74
+ st_callback = StreamlitCallbackHandlerChem(
75
+ st.container(),
76
+ max_thought_containers = 3,
77
+ collapse_completed_thoughts = False,
78
+ output_placeholder=ss
79
+ )
80
+ try:
81
+ with wandb_tracing_enabled():
82
+ response = agent.run(prompt, callbacks=[st_callback])
83
+ st.write(response)
84
+ except openai.error.AuthenticationError:
85
+ st.write("Please input a valid OpenAI API key")
86
+ except openai.error.APIError:
87
+ # Handle specific API errors here
88
+ print("OpenAI API error, please try again!")
89
+
90
+
91
+ pre_prompts = [
92
+ 'How can I synthesize safinamide?',
93
+ (
94
+ 'Predict the product of a mixture of Ethylidenecyclohexane and HBr. '
95
+ 'Then predict the same reaction, adding methyl peroxide into the '
96
+ 'mixture. Compare the two products and explain the reaction mechanism.'
97
+ ),
98
+ (
99
+ 'What is the boiling point of the reaction product between '
100
+ 'isoamyl alcohol and acetic acid?'
101
+ ),
102
+ 'Tell me how to synthesize vanilline, and the price of the precursors.'
103
+ ]
104
+
105
+ # sidebar
106
+ with st.sidebar:
107
+ chemcrow_logo = Image.open('assets/chemcrow-logo-bold-new.png')
108
+ st.image(chemcrow_logo)
109
+
110
+ # Input OpenAI api key
111
+ st.text_input(
112
+ 'Input your OpenAI API key.',
113
+ placeholder = 'Input your OpenAI API key.',
114
+ type='password',
115
+ key='api_key',
116
+ on_change=on_api_key_change,
117
+ label_visibility="collapsed"
118
+ )
119
+
120
+ # Input model to use
121
+ st.selectbox(
122
+ 'Select model to use',
123
+ ['gpt-4-0613', 'gpt-3.5-turbo', 'gpt-4o-mini'],
124
+ key='model_select',
125
+ )
126
+
127
+ # Display prompt examples
128
+ st.markdown('# What can I ask?')
129
+ cols = st.columns(2)
130
+ with cols[0]:
131
+ st.button(
132
+ "How can I synthesize safinamide?",
133
+ on_click=lambda: run_prompt(pre_prompts[0]),
134
+ )
135
+ st.button(
136
+ "Explain mechanism of bromoaddition reaction",
137
+ on_click=lambda: run_prompt(pre_prompts[1]),
138
+ )
139
+ with cols[1]:
140
+ st.button(
141
+ 'Predict properties of a reaction product',
142
+ on_click=lambda: run_prompt(pre_prompts[2]),
143
+ )
144
+ st.button(
145
+ 'Synthesize molecule with price of precursors',
146
+ on_click=lambda: run_prompt(pre_prompts[3]),
147
+ )
148
+
149
+ st.markdown('---')
150
+ # Display available tools
151
+ st.markdown(f"# {len(tool_list)} available tools")
152
+ st.dataframe(
153
+ tool_list,
154
+ use_container_width=True,
155
+ hide_index=True,
156
+ height=200
157
+ )
158
 
159
+ # Execute agent on user input
160
+ if user_input := st.chat_input():
161
+ run_prompt(user_input)