kz919 commited on
Commit
a9ded25
1 Parent(s): 1472a42

revert to streamlit

Browse files
Files changed (1) hide show
  1. app.py +151 -108
app.py CHANGED
@@ -1,8 +1,17 @@
1
- import gradio as gr
 
2
  from openai import OpenAI
3
  import time
4
  import re
5
 
 
 
 
 
 
 
 
 
6
  # Available models
7
  MODELS = [
8
  "Meta-Llama-3.1-405B-Instruct",
@@ -10,18 +19,20 @@ MODELS = [
10
  "Meta-Llama-3.1-8B-Instruct"
11
  ]
12
 
13
- def create_client(api_key, base_url):
14
- return OpenAI(
15
- api_key=api_key,
16
- base_url=base_url
17
- )
 
 
18
 
19
  def chat_with_ai(message, chat_history, system_prompt):
20
  messages = [
21
  {"role": "system", "content": system_prompt},
22
  ]
23
 
24
- for human, ai in chat_history:
25
  messages.append({"role": "user", "content": human})
26
  messages.append({"role": "assistant", "content": ai})
27
 
@@ -29,13 +40,11 @@ def chat_with_ai(message, chat_history, system_prompt):
29
 
30
  return messages
31
 
32
- def respond(message, chat_history, model, system_prompt, thinking_budget, api_key, base_url):
33
- client = create_client(api_key, base_url)
34
- messages = chat_with_ai(message, chat_history, system_prompt.format(budget=thinking_budget))
35
  response = ""
36
  start_time = time.time()
37
-
38
- try:
39
  for chunk in client.chat.completions.create(
40
  model=model,
41
  messages=messages,
@@ -44,113 +53,147 @@ def respond(message, chat_history, model, system_prompt, thinking_budget, api_ke
44
  content = chunk.choices[0].delta.content or ""
45
  response += content
46
  yield response, time.time() - start_time
47
- except Exception as e:
48
- yield f"Error: {str(e)}", time.time() - start_time
49
 
50
- def parse_response(response):
 
51
  answer_match = re.search(r'<answer>(.*?)</answer>', response, re.DOTALL)
52
  reflection_match = re.search(r'<reflection>(.*?)</reflection>', response, re.DOTALL)
53
 
54
  answer = answer_match.group(1).strip() if answer_match else ""
55
  reflection = reflection_match.group(1).strip() if reflection_match else ""
56
 
57
- steps = re.findall(r'<step>(.*?)</step>', response, re.DOTALL)
58
-
59
- return answer, reflection, steps
60
-
61
- def process_chat(message, history, model, system_prompt, thinking_budget, api_key, base_url):
62
- if not api_key or not base_url:
63
- history.append((message, "Please provide both API Key and Base URL before starting the chat."))
64
- return history, history
65
-
66
- full_response = ""
67
- thinking_time = 0
68
 
69
- for response, elapsed_time in respond(message, history, model, system_prompt, thinking_budget, api_key, base_url):
70
- full_response = response
71
- thinking_time = elapsed_time
72
-
73
- if full_response.startswith("Error:"):
74
- history.append((message, full_response))
75
- return history, history
76
-
77
- answer, reflection, steps = parse_response(full_response)
78
-
79
- formatted_response = f"**Answer:** {answer}\n\n**Reflection:** {reflection}\n\n**Thinking Steps:**\n"
80
- for i, step in enumerate(steps, 1):
81
- formatted_response += f"**Step {i}:** {step}\n"
82
-
83
- formatted_response += f"\n**Thinking time:** {thinking_time:.2f} s"
84
-
85
- history.append((message, formatted_response))
86
- return history, history
87
-
88
- with gr.Blocks() as demo:
89
- gr.Markdown("# Llama3.1-Instruct-O1")
90
- gr.Markdown("[Powered by Llama3.1 models through SN Cloud](https://sambanova.ai/fast-api?api_ref=907266)")
91
-
92
- with gr.Row():
93
- api_key = gr.Textbox(label="API Key", type="password")
94
- base_url = gr.Textbox(label="Base URL", value="https://api.endpoints.anyscale.com/v1")
95
-
96
- with gr.Row():
97
- model = gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[0])
98
- thinking_budget = gr.Slider(minimum=1, maximum=100, value=1, step=1, label="Thinking Budget")
99
 
100
- system_prompt = gr.Textbox(
101
- label="System Prompt",
102
- value="""
103
- You are a helpful assistant in normal conversation.
104
- When given a problem to solve, you are an expert problem-solving assistant. Your task is to provide a detailed, step-by-step solution to a given question. Follow these instructions carefully:
105
-
106
- 1. Read the given question carefully and reset counter between <count> and </count> to {budget}
107
- 2. Generate a detailed, logical step-by-step solution.
108
- 3. Enclose each step of your solution within <step> and </step> tags.
109
- 4. You are allowed to use at most {budget} steps (starting budget), keep track of it by counting down within tags <count> </count>, STOP GENERATING MORE STEPS when hitting 0, you don't have to use all of them.
110
- 5. Do a self-reflection when you are unsure about how to proceed, based on the self-reflection and reward, decides whether you need to return to the previous steps.
111
- 6. After completing the solution steps, reorganize and synthesize the steps into the final answer within <answer> and </answer> tags.
112
- 7. Provide a critical, honest and subjective self-evaluation of your reasoning process within <reflection> and </reflection> tags.
113
- 8. Assign a quality score to your solution as a float between 0.0 (lowest quality) and 1.0 (highest quality), enclosed in <reward> and </reward> tags.
114
-
115
- Example format:
116
- <count> [starting budget] </count>
 
 
 
 
 
117
 
118
- <step> [Content of step 1] </step>
119
- <count> [remaining budget] </count>
120
-
121
- <step> [Content of step 2] </step>
122
- <reflection> [Evaluation of the steps so far] </reflection>
123
- <reward> [Float between 0.0 and 1.0] </reward>
124
- <count> [remaining budget] </count>
125
-
126
- <step> [Content of step 3 or Content of some previous step] </step>
127
- <count> [remaining budget] </count>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
- ...
130
-
131
- <step> [Content of final step] </step>
132
- <count> [remaining budget] </count>
 
 
 
 
 
 
133
 
134
- <answer> [Final Answer] </answer>
135
-
136
- <reflection> [Evaluation of the solution] </reflection>
137
-
138
- <reward> [Float between 0.0 and 1.0] </reward>
139
- """,
140
- lines=10
141
- )
142
 
143
- chatbot_ui = gr.Chatbot()
144
- msg = gr.Textbox(label="Type your message here...")
145
- clear = gr.Button("Clear Chat")
146
-
147
- chat_history = gr.State([])
148
-
149
- msg.submit(
150
- process_chat, # Use the renamed function
151
- [msg, chat_history, model, system_prompt, thinking_budget, api_key, base_url],
152
- [chatbot_ui, chat_history]
153
- )
154
- clear.click(lambda: ([], []), None, [chatbot_ui, chat_history], queue=False)
155
 
156
- demo.launch()
 
 
1
+ import os
2
+ import streamlit as st
3
  from openai import OpenAI
4
  import time
5
  import re
6
 
7
+ # Set up API key
8
+ API_KEY = os.getenv("API_KEY")
9
+ URL = os.getenv("URL")
10
+ client = OpenAI(
11
+ api_key=API_KEY,
12
+ base_url=URL
13
+ )
14
+
15
  # Available models
16
  MODELS = [
17
  "Meta-Llama-3.1-405B-Instruct",
 
19
  "Meta-Llama-3.1-8B-Instruct"
20
  ]
21
 
22
+ # Available search strategies
23
+ SEARCH_STRATEGY = [
24
+ "None",
25
+ "Greedy-Best-Score",
26
+ "Iterative-Refinement",
27
+ "Monte-Carlo-Tree-Search"
28
+ ]
29
 
30
  def chat_with_ai(message, chat_history, system_prompt):
31
  messages = [
32
  {"role": "system", "content": system_prompt},
33
  ]
34
 
35
+ for human, ai, _ in chat_history:
36
  messages.append({"role": "user", "content": human})
37
  messages.append({"role": "assistant", "content": ai})
38
 
 
40
 
41
  return messages
42
 
43
+ def respond(message, chat_history, model, system_prompt, thinking_budget):
44
+ messages = chat_with_ai(message, chat_history, system_prompt.format(budget = thinking_budget))
 
45
  response = ""
46
  start_time = time.time()
47
+ with st.spinner("AI is thinking..."):
 
48
  for chunk in client.chat.completions.create(
49
  model=model,
50
  messages=messages,
 
53
  content = chunk.choices[0].delta.content or ""
54
  response += content
55
  yield response, time.time() - start_time
 
 
56
 
57
+ def parse_and_display_response(response):
58
+ # Extract answer and reflection
59
  answer_match = re.search(r'<answer>(.*?)</answer>', response, re.DOTALL)
60
  reflection_match = re.search(r'<reflection>(.*?)</reflection>', response, re.DOTALL)
61
 
62
  answer = answer_match.group(1).strip() if answer_match else ""
63
  reflection = reflection_match.group(1).strip() if reflection_match else ""
64
 
65
+ # Remove answer, reflection, and final reward from the main response
66
+ response = re.sub(r'<answer>.*?</answer>', '', response, flags=re.DOTALL)
67
+ response = re.sub(r'<reflection>.*?</reflection>', '', response, flags=re.DOTALL)
68
+ response = re.sub(r'<reward>.*?</reward>\s*$', '', response, flags=re.DOTALL)
 
 
 
 
 
 
 
69
 
70
+ # Extract and display steps
71
+ steps = re.findall(r'<step>(.*?)</step>', response, re.DOTALL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ with st.expander("Show thinking process", expanded=False):
74
+ for i, step in enumerate(steps, 1):
75
+ st.markdown(f"**Step {i}:**")
76
+ st.write(step.strip())
77
+ st.markdown("---")
78
+
79
+ # Display answer and reflection
80
+ if answer:
81
+ st.markdown("### Answer:")
82
+ st.write(answer)
83
+
84
+ if reflection:
85
+ st.markdown("### Reflection:")
86
+ st.write(reflection)
87
+
88
+ def display_message_with_code_blocks(message):
89
+ # First, check if the message contains the special tags
90
+ if '<step>' in message or '<answer>' in message or '<reflection>' in message:
91
+ parse_and_display_response(message)
92
+ else:
93
+ # If not, use the original display logic
94
+ parts = re.split(r'(```[\s\S]*?```)', message)
95
 
96
+ for part in parts:
97
+ if part.startswith('```') and part.endswith('```'):
98
+ # This is a code block
99
+ code = part.strip('`').strip()
100
+ lang = code.split('\n')[0] if '\n' in code else ''
101
+ code = '\n'.join(code.split('\n')[1:]) if lang else code
102
+ st.code(code, language=lang, line_numbers=True)
103
+ else:
104
+ # This is regular text
105
+ st.write(part)
106
+
107
+ def main():
108
+ st.set_page_config(page_title="AI Chatbot", layout="wide")
109
+
110
+ st.title("Llama3.1-Instruct-O1")
111
+ st.markdown("<a href='https://sambanova.ai/fast-api?api_ref=907266' target='_blank'>Powered by Llama3.1 models through SN Cloud</a>", unsafe_allow_html=True)
112
+
113
+ if "chat_history" not in st.session_state:
114
+ st.session_state.chat_history = []
115
+
116
+ col1, col2 = st.columns([1, 1])
117
+
118
+ with col1:
119
+ model = st.selectbox("Select Model", MODELS, index=0)
120
+ thinking_budget = st.slider("Thinking Budget", 1, 100, 1, help="Control how much it thinks, pick between 1 to 100 inclusive")
121
+
122
+ with col2:
123
+ system_prompt = st.text_area(
124
+ "System Prompt",
125
+ value="""
126
+ You are a helpful assistant in normal conversation.
127
+ When given a problem to solve, you are an expert problem-solving assistant. Your task is to provide a detailed, step-by-step solution to a given question. Follow these instructions carefully:
128
+
129
+ 1. Read the given question carefully and reset counter between <count> and </count> to {budget}
130
+ 2. Generate a detailed, logical step-by-step solution.
131
+ 3. Enclose each step of your solution within <step> and </step> tags.
132
+ 4. You are allowed to use at most {budget} steps (starting budget), keep track of it by counting down within tags <count> </count>, STOP GENERATING MORE STEPS when hitting 0, you don't have to use all of them.
133
+ 5. Do a self-reflection when you are unsure about how to proceed, based on the self-reflection and reward, decides whether you need to return to the previous steps.
134
+ 6. After completing the solution steps, reorganize and synthesize the steps into the final answer within <answer> and </answer> tags.
135
+ 7. Provide a critical, honest and subjective self-evaluation of your reasoning process within <reflection> and </reflection> tags.
136
+ 8. Assign a quality score to your solution as a float between 0.0 (lowest quality) and 1.0 (highest quality), enclosed in <reward> and </reward> tags.
137
+
138
+ Example format:
139
+ <count> [starting budget] </count>
140
+
141
+ <step> [Content of step 1] </step>
142
+ <count> [remaining budget] </count>
143
+
144
+ <step> [Content of step 2] </step>
145
+ <reflection> [Evaluation of the steps so far] </reflection>
146
+ <reward> [Float between 0.0 and 1.0] </reward>
147
+ <count> [remaining budget] </count>
148
+
149
+ <step> [Content of step 3 or Content of some previous step] </step>
150
+ <count> [remaining budget] </count>
151
+
152
+ ...
153
+
154
+ <step> [Content of final step] </step>
155
+ <count> [remaining budget] </count>
156
+
157
+ <answer> [Final Answer] </answer>
158
+
159
+ <reflection> [Evaluation of the solution] </reflection>
160
+
161
+ <reward> [Float between 0.0 and 1.0] </reward>
162
+ """,
163
+ height=200
164
+ )
165
+
166
+ st.markdown("---")
167
+
168
+ for human, ai, thinking_time in st.session_state.chat_history:
169
+ with st.chat_message("human"):
170
+ st.write(human)
171
+ with st.chat_message("ai"):
172
+ display_message_with_code_blocks(ai)
173
+ st.caption(f"Thinking time: {thinking_time:.2f} s")
174
+
175
+ message = st.chat_input("Type your message here...")
176
+
177
+ if message:
178
+ with st.chat_message("human"):
179
+ st.write(message)
180
 
181
+ with st.chat_message("ai"):
182
+ response_placeholder = st.empty()
183
+ time_placeholder = st.empty()
184
+ for response, elapsed_time in respond(message, st.session_state.chat_history, model, system_prompt, thinking_budget):
185
+ response_placeholder.markdown(response)
186
+ time_placeholder.caption(f"Thinking time: {elapsed_time:.2f} s")
187
+ response_placeholder.empty()
188
+ time_placeholder.empty()
189
+ display_message_with_code_blocks(response)
190
+ time_placeholder.caption(f"Thinking time: {elapsed_time:.2f} s")
191
 
192
+ st.session_state.chat_history.append((message, response, elapsed_time))
 
 
 
 
 
 
 
193
 
194
+ if st.button("Clear Chat"):
195
+ st.session_state.chat_history = []
196
+ st.experimental_rerun()
 
 
 
 
 
 
 
 
 
197
 
198
+ if __name__ == "__main__":
199
+ main()