leezhuuu commited on
Commit
b2aa5c8
·
verified ·
1 Parent(s): 21c4a75

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -0
app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import json
4
+ import time
5
+ import requests
6
+
7
+ # 配置变量
8
+ DEFAULT_API_URL = "https://api.groq.com/openai/v1/chat/completions"
9
+ DEFAULT_MODEL = "llama-3.2-90b-text-preview"
10
+
11
+ def make_api_call(messages, max_tokens, is_final_answer=False):
12
+ for attempt in range(3):
13
+ try:
14
+ data = {
15
+ "model": st.session_state.model,
16
+ "messages": messages,
17
+ "max_tokens": max_tokens,
18
+ "temperature": 0.2,
19
+ "response_format": {"type": "json_object"}
20
+ }
21
+ headers = {
22
+ "Content-Type": "application/json",
23
+ "Authorization": f"Bearer {st.session_state.api_key}"
24
+ }
25
+ response = requests.post(st.session_state.api_url, headers=headers, json=data)
26
+ response.raise_for_status()
27
+ return json.loads(response.json()['choices'][0]['message']['content'])
28
+ except Exception as e:
29
+ if attempt == 2:
30
+ if is_final_answer:
31
+ return {"title": "错误", "content": f"3次尝试后无法生成最终答案。错误: {str(e)}"}
32
+ else:
33
+ return {"title": "错误", "content": f"3次尝试后无法生成步骤。错误: {str(e)}", "next_action": "final_answer"}
34
+ time.sleep(1) # 重试前等待1秒
35
+
36
+ def generate_response(prompt):
37
+ messages = [
38
+ {"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.
39
+
40
+ Example of a valid JSON response:```json
41
+ {
42
+ "title": "Identifying Key Information",
43
+ "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...",
44
+ "next_action": "continue"
45
+ }```
46
+ """},
47
+ {"role": "user", "content": prompt},
48
+ {"role": "assistant", "content": "Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."}
49
+ ]
50
+
51
+ steps = []
52
+ step_count = 1
53
+ total_thinking_time = 0
54
+
55
+ while True:
56
+ start_time = time.time()
57
+ step_data = make_api_call(messages, 300)
58
+ end_time = time.time()
59
+ thinking_time = end_time - start_time
60
+ total_thinking_time += thinking_time
61
+
62
+ steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
63
+
64
+ messages.append({"role": "assistant", "content": json.dumps(step_data)})
65
+
66
+ if step_data['next_action'] == 'final_answer' or step_count > 25: # Maximum of 25 steps to prevent infinite thinking time. Can be adjusted.
67
+ break
68
+
69
+ step_count += 1
70
+
71
+ # Yield after each step for Streamlit to update
72
+ yield steps, None # We're not yielding the total time until the end
73
+
74
+ # Generate final answer
75
+ messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
76
+
77
+ start_time = time.time()
78
+ final_data = make_api_call(messages, 200, is_final_answer=True)
79
+ end_time = time.time()
80
+ thinking_time = end_time - start_time
81
+ total_thinking_time += thinking_time
82
+
83
+ steps.append(("Final Answer", final_data['content'], thinking_time))
84
+
85
+ yield steps, total_thinking_time
86
+
87
+ def main():
88
+ st.set_page_config(page_title="g1 prototype", page_icon="🧠", layout="wide")
89
+
90
+ st.title("g1: Using Llama-3.2-90b-text-preview on Groq to create o1-like reasoning chains")
91
+
92
+ st.markdown("""
93
+ 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!
94
+
95
+ Original repository [here](https://github.com/bklieger-groq), forked repository [here](https://github.com/leezhuuuuu/o1)
96
+ """)
97
+
98
+ # 初始化会话状态变量
99
+ if 'api_url' not in st.session_state:
100
+ st.session_state.api_url = DEFAULT_API_URL
101
+ if 'api_key' not in st.session_state:
102
+ st.session_state.api_key = ""
103
+ if 'model' not in st.session_state:
104
+ st.session_state.model = DEFAULT_MODEL
105
+
106
+ # 配置输入
107
+ st.sidebar.header("API配置")
108
+ st.session_state.api_url = st.sidebar.text_input("API URL:", value=st.session_state.api_url)
109
+ st.session_state.api_key = st.sidebar.text_input("API Key:", value=st.session_state.api_key, type="password")
110
+ st.session_state.model = st.sidebar.text_input("模型:", value=st.session_state.model)
111
+
112
+ # 用户查询输入
113
+ user_query = st.text_input("Enter your query:", placeholder="e.g., How many 'R's are in the word strawberry?")
114
+
115
+ if user_query and st.session_state.api_key:
116
+ st.write("Generating response...")
117
+
118
+ # Create empty elements to hold the generated text and total time
119
+ response_container = st.empty()
120
+ time_container = st.empty()
121
+
122
+ # Generate and display the response
123
+ for steps, total_thinking_time in generate_response(user_query):
124
+ with response_container.container():
125
+ for i, (title, content, thinking_time) in enumerate(steps):
126
+ if title.startswith("Final Answer"):
127
+ st.markdown(f"### {title}")
128
+ st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
129
+ else:
130
+ with st.expander(title, expanded=True):
131
+ st.markdown(content.replace('\n', '<br>'), unsafe_allow_html=True)
132
+ # Only show total time when it's available at the end
133
+ if total_thinking_time is not None:
134
+ time_container.markdown(f"**Total thinking time: {total_thinking_time:.2f} seconds**")
135
+ elif user_query:
136
+ st.warning("请在侧边栏中输入有效的API密钥。")
137
+
138
+ if __name__ == "__main__":
139
+ main()