kz919 commited on
Commit
ea7e2a4
1 Parent(s): cc7a8f5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -0
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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",
18
+ "Meta-Llama-3.1-70B-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
+
39
+ messages.append({"role": "user", "content": message})
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,
51
+ stream=True
52
+ ):
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()