sherrybabe1978 commited on
Commit
771ea75
·
verified ·
1 Parent(s): 959a441

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +117 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import groq
3
+ import os
4
+ import json
5
+ import time
6
+
7
+ client = groq.Groq()
8
+
9
+ def make_api_call(messages, max_tokens, is_final_answer=False):
10
+ for attempt in range(3):
11
+ try:
12
+ response = client.chat.completions.create(
13
+ model="llama-3.1-70b-versatile",
14
+ messages=messages,
15
+ max_tokens=max_tokens,
16
+ temperature=0.2,
17
+ response_format={"type": "json_object"}
18
+ )
19
+ return json.loads(response.choices[0].message.content)
20
+ except Exception as e:
21
+ if attempt == 2:
22
+ if is_final_answer:
23
+ return {"title": "Error", "content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}"}
24
+ else:
25
+ return {"title": "Error", "content": f"Failed to generate step after 3 attempts. Error: {str(e)}", "next_action": "final_answer"}
26
+ time.sleep(1) # Wait for 1 second before retrying
27
+
28
+ def generate_response(prompt):
29
+ messages = [
30
+ {"role": "system", "content": """You are an expert AI assistant that explains your reasoning step by step. For each step, provide a title that describes what you're doing in that step, along with the content. Decide if you need another step or if you're ready to give the final answer. Respond in JSON format with 'title', 'content', and 'next_action' (either 'continue' or 'final_answer') keys. USE AS MANY REASONING STEPS AS POSSIBLE. AT LEAST 3. BE AWARE OF YOUR LIMITATIONS AS AN LLM AND WHAT YOU CAN AND CANNOT DO. IN YOUR REASONING, INCLUDE EXPLORATION OF ALTERNATIVE ANSWERS. CONSIDER YOU MAY BE WRONG, AND IF YOU ARE WRONG IN YOUR REASONING, WHERE IT WOULD BE. FULLY TEST ALL OTHER POSSIBILITIES. YOU CAN BE WRONG. WHEN YOU SAY YOU ARE RE-EXAMINING, ACTUALLY RE-EXAMINE, AND USE ANOTHER APPROACH TO DO SO. DO NOT JUST SAY YOU ARE RE-EXAMINING. USE AT LEAST 3 METHODS TO DERIVE THE ANSWER. USE BEST PRACTICES.
31
+
32
+ Example of a valid JSON response:
33
+ ```json
34
+ {
35
+ "title": "Identifying Key Information",
36
+ "content": "To begin solving this problem, we need to carefully examine the given information and identify the crucial elements that will guide our solution process. This involves...",
37
+ "next_action": "continue"
38
+ }```
39
+ """},
40
+ {"role": "user", "content": prompt},
41
+ {"role": "assistant", "content": "Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."}
42
+ ]
43
+
44
+ steps = []
45
+ step_count = 1
46
+ total_thinking_time = 0
47
+
48
+ while True:
49
+ start_time = time.time()
50
+ step_data = make_api_call(messages, 300)
51
+ end_time = time.time()
52
+ thinking_time = end_time - start_time
53
+ total_thinking_time += thinking_time
54
+
55
+ steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
56
+
57
+ messages.append({"role": "assistant", "content": json.dumps(step_data)})
58
+
59
+ if step_data['next_action'] == 'final_answer' or step_count > 25: # Maximum of 25 steps to prevent infinite thinking time. Can be adjusted.
60
+ break
61
+
62
+ step_count += 1
63
+
64
+ # Yield after each step for Streamlit to update
65
+ yield steps, None # We're not yielding the total time until the end
66
+
67
+ # Generate final answer
68
+ messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
69
+
70
+ start_time = time.time()
71
+ final_data = make_api_call(messages, 200, is_final_answer=True)
72
+ end_time = time.time()
73
+ thinking_time = end_time - start_time
74
+ total_thinking_time += thinking_time
75
+
76
+ steps.append(("Final Answer", final_data['content'], thinking_time))
77
+
78
+ yield steps, total_thinking_time
79
+
80
+ def main():
81
+ st.set_page_config(page_title="g1 prototype", page_icon="🧠", layout="wide")
82
+
83
+ st.title("g1: Using Llama-3.1 70b on Groq to create o1-like reasoning chains")
84
+
85
+ st.markdown("""
86
+ This is an early prototype of using prompting to create o1-like reasoning chains to improve output accuracy. It is not perfect and accuracy has yet to be formally evaluated. It is powered by Groq so that the reasoning step is fast!
87
+
88
+ Open source [repository here](https://github.com/bklieger-groq)
89
+ """)
90
+
91
+ # Text input for user query
92
+ user_query = st.text_input("Enter your query:", placeholder="e.g., How many 'R's are in the word strawberry?")
93
+
94
+ if user_query:
95
+ st.write("Generating response...")
96
+
97
+ # Create empty elements to hold the generated text and total time
98
+ response_container = st.empty()
99
+ time_container = st.empty()
100
+
101
+ # Generate and display the response
102
+ for steps, total_thinking_time in generate_response(user_query):
103
+ with response_container.container():
104
+ for i, (title, content, thinking_time) in enumerate(steps):
105
+ if title.startswith("Final Answer"):
106
+ st.markdown(f"### {title}")
107
+ st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
108
+ else:
109
+ with st.expander(title, expanded=True):
110
+ st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
111
+
112
+ # Only show total time when it's available at the end
113
+ if total_thinking_time is not None:
114
+ time_container.markdown(f"**Total thinking time: {total_thinking_time:.2f} seconds**")
115
+
116
+ if __name__ == "__main__":
117
+ main()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ streamlit
2
+ groq