File size: 7,867 Bytes
a9ded25
 
ea7e2a4
 
 
 
a9ded25
 
 
 
 
 
 
 
ea7e2a4
 
 
 
 
 
 
a9ded25
 
 
 
 
 
 
ea7e2a4
 
 
 
 
 
a9ded25
ea7e2a4
 
 
 
 
 
 
a9ded25
 
ea7e2a4
 
a9ded25
ea7e2a4
 
 
 
 
 
 
 
 
a9ded25
 
ea7e2a4
 
 
 
 
 
a9ded25
 
 
 
f50326e
a9ded25
 
f50326e
a9ded25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea7e2a4
a9ded25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea7e2a4
a9ded25
 
 
 
 
 
 
 
 
 
ea7e2a4
a9ded25
ea7e2a4
a9ded25
 
 
ea7e2a4
a9ded25
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import os
import streamlit as st
from openai import OpenAI
import time
import re

# Set up API key
API_KEY = os.getenv("API_KEY")
URL = os.getenv("URL")
client = OpenAI(
    api_key=API_KEY,
    base_url=URL
)

# Available models
MODELS = [
    "Meta-Llama-3.1-405B-Instruct",
    "Meta-Llama-3.1-70B-Instruct",
    "Meta-Llama-3.1-8B-Instruct"
]

# Available search strategies
SEARCH_STRATEGY = [
    "None",
    "Greedy-Best-Score",
    "Iterative-Refinement",
    "Monte-Carlo-Tree-Search"
]

def chat_with_ai(message, chat_history, system_prompt):
    messages = [
        {"role": "system", "content": system_prompt},
    ]
    
    for human, ai, _ in chat_history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": ai})
    
    messages.append({"role": "user", "content": message})
    
    return messages

def respond(message, chat_history, model, system_prompt, thinking_budget):
    messages = chat_with_ai(message, chat_history, system_prompt.format(budget = thinking_budget))
    response = ""
    start_time = time.time()
    with st.spinner("AI is thinking..."):
        for chunk in client.chat.completions.create(
            model=model,
            messages=messages,
            stream=True
        ):
            content = chunk.choices[0].delta.content or ""
            response += content
            yield response, time.time() - start_time

def parse_and_display_response(response):
    # Extract answer and reflection
    answer_match = re.search(r'<answer>(.*?)</answer>', response, re.DOTALL)
    reflection_match = re.search(r'<reflection>(.*?)</reflection>', response, re.DOTALL)
    
    answer = answer_match.group(1).strip() if answer_match else ""
    reflection = reflection_match.group(1).strip() if reflection_match else ""
    
    # Remove answer, reflection, and final reward from the main response
    response = re.sub(r'<answer>.*?</answer>', '', response, flags=re.DOTALL)
    response = re.sub(r'<reflection>.*?</reflection>', '', response, flags=re.DOTALL)
    response = re.sub(r'<reward>.*?</reward>\s*$', '', response, flags=re.DOTALL)
    
    # Extract and display steps
    steps = re.findall(r'<step>(.*?)</step>', response, re.DOTALL)
    
    with st.expander("Show thinking process", expanded=False):
        for i, step in enumerate(steps, 1):
            st.markdown(f"**Step {i}:**")
            st.write(step.strip())
            st.markdown("---")
    
    # Display answer and reflection
    if answer:
        st.markdown("### Answer:")
        st.write(answer)
    
    if reflection:
        st.markdown("### Reflection:")
        st.write(reflection)

def display_message_with_code_blocks(message):
    # First, check if the message contains the special tags
    if '<step>' in message or '<answer>' in message or '<reflection>' in message:
        parse_and_display_response(message)
    else:
        # If not, use the original display logic
        parts = re.split(r'(```[\s\S]*?```)', message)
        
        for part in parts:
            if part.startswith('```') and part.endswith('```'):
                # This is a code block
                code = part.strip('`').strip()
                lang = code.split('\n')[0] if '\n' in code else ''
                code = '\n'.join(code.split('\n')[1:]) if lang else code
                st.code(code, language=lang, line_numbers=True)
            else:
                # This is regular text
                st.write(part)

def main():
    st.set_page_config(page_title="AI Chatbot", layout="wide")
    
    st.title("Llama3.1-Instruct-O1")
    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)
    
    if "chat_history" not in st.session_state:
        st.session_state.chat_history = []
    
    col1, col2 = st.columns([1, 1])
    
    with col1:
        model = st.selectbox("Select Model", MODELS, index=0)
        thinking_budget = st.slider("Thinking Budget", 1, 100, 1, help="Control how much it thinks, pick between 1 to 100 inclusive")
    
    with col2:
        system_prompt = st.text_area(
            "System Prompt",
            value="""
            You are a helpful assistant in normal conversation.
            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:

            1. Read the given question carefully and reset counter between <count> and </count> to {budget}
            2. Generate a detailed, logical step-by-step solution.
            3. Enclose each step of your solution within <step> and </step> tags.
            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.
            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.
            6. After completing the solution steps, reorganize and synthesize the steps into the final answer within <answer> and </answer> tags.
            7. Provide a critical, honest and subjective self-evaluation of your reasoning process within <reflection> and </reflection> tags.
            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.

            Example format:            
            <count> [starting budget] </count>
            
            <step> [Content of step 1] </step>
            <count> [remaining budget] </count>

            <step> [Content of step 2] </step>
            <reflection> [Evaluation of the steps so far] </reflection>
            <reward> [Float between 0.0 and 1.0] </reward>
            <count> [remaining budget] </count>

            <step> [Content of step 3 or Content of some previous step] </step>
            <count> [remaining budget] </count>
            
            ...

            <step>  [Content of final step] </step>
            <count> [remaining budget] </count>
            
            <answer> [Final Answer] </answer>

            <reflection> [Evaluation of the solution] </reflection>

            <reward> [Float between 0.0 and 1.0] </reward>
            """,
            height=200
        )
    
    st.markdown("---")
    
    for human, ai, thinking_time in st.session_state.chat_history:
        with st.chat_message("human"):
            st.write(human)
        with st.chat_message("ai"):
            display_message_with_code_blocks(ai)
            st.caption(f"Thinking time: {thinking_time:.2f} s")
    
    message = st.chat_input("Type your message here...")
    
    if message:
        with st.chat_message("human"):
            st.write(message)
        
        with st.chat_message("ai"):
            response_placeholder = st.empty()
            time_placeholder = st.empty()
            for response, elapsed_time in respond(message, st.session_state.chat_history, model, system_prompt, thinking_budget):
                response_placeholder.markdown(response)
                time_placeholder.caption(f"Thinking time: {elapsed_time:.2f} s")
            response_placeholder.empty()
            time_placeholder.empty()
            display_message_with_code_blocks(response)
            time_placeholder.caption(f"Thinking time: {elapsed_time:.2f} s")
        
        st.session_state.chat_history.append((message, response, elapsed_time))
    
    if st.button("Clear Chat"):
        st.session_state.chat_history = []
        st.experimental_rerun()

if __name__ == "__main__":
    main()