Nymbo commited on
Commit
9996a91
·
verified ·
1 Parent(s): ad61ff3

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +156 -0
  2. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import groq
3
+ import os
4
+ import json
5
+ import time
6
+
7
+ def make_api_call(client, messages, max_tokens, is_final_answer=False):
8
+ for attempt in range(3):
9
+ try:
10
+ response = client.chat.completions.create(
11
+ model="llama-3.1-70b-versatile",
12
+ messages=messages,
13
+ max_tokens=max_tokens,
14
+ temperature=0.2,
15
+ response_format={"type": "json_object"}
16
+ )
17
+ return json.loads(response.choices[0].message.content)
18
+ except Exception as e:
19
+ if attempt == 2:
20
+ if is_final_answer:
21
+ return {"title": "Error", "content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}"}
22
+ else:
23
+ return {"title": "Error", "content": f"Failed to generate step after 3 attempts. Error: {str(e)}", "next_action": "final_answer"}
24
+ time.sleep(1) # Wait for 1 second before retrying
25
+
26
+ def generate_response(client, prompt):
27
+ messages = [
28
+ {"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.
29
+
30
+ Example of a valid JSON response:
31
+ ```json
32
+ {
33
+ "title": "Identifying Key Information",
34
+ "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...",
35
+ "next_action": "continue"
36
+ }```
37
+ """ },
38
+ {"role": "user", "content": prompt},
39
+ {"role": "assistant", "content": "Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."}
40
+ ]
41
+
42
+ steps = []
43
+ step_count = 1
44
+ total_thinking_time = 0
45
+
46
+ while True:
47
+ start_time = time.time()
48
+ step_data = make_api_call(client, messages, 300)
49
+ end_time = time.time()
50
+ thinking_time = end_time - start_time
51
+ total_thinking_time += thinking_time
52
+
53
+ # Handle potential errors
54
+ if step_data.get('title') == "Error":
55
+ steps.append((f"Step {step_count}: {step_data.get('title')}", step_data.get('content'), thinking_time))
56
+ break
57
+
58
+ step_title = f"Step {step_count}: {step_data.get('title', 'No Title')}"
59
+ step_content = step_data.get('content', 'No Content')
60
+ steps.append((step_title, step_content, thinking_time))
61
+
62
+ messages.append({"role": "assistant", "content": json.dumps(step_data)})
63
+
64
+ if step_data.get('next_action') == 'final_answer':
65
+ break
66
+
67
+ step_count += 1
68
+
69
+ # Generate final answer
70
+ messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
71
+
72
+ start_time = time.time()
73
+ final_data = make_api_call(client, messages, 200, is_final_answer=True)
74
+ end_time = time.time()
75
+ thinking_time = end_time - start_time
76
+ total_thinking_time += thinking_time
77
+
78
+ if final_data.get('title') == "Error":
79
+ steps.append(("Final Answer", final_data.get('content'), thinking_time))
80
+ else:
81
+ steps.append(("Final Answer", final_data.get('content', 'No Content'), thinking_time))
82
+
83
+ return steps, total_thinking_time
84
+
85
+ def format_steps(steps, total_time):
86
+ html_content = ""
87
+ for title, content, thinking_time in steps:
88
+ if title == "Final Answer":
89
+ html_content += "<h3>{}</h3>".format(title)
90
+ html_content += "<p>{}</p>".format(content.replace('\n', '<br>'))
91
+ else:
92
+ html_content += """
93
+ <details>
94
+ <summary><strong>{}</strong></summary>
95
+ <p>{}</p>
96
+ <p><em>Thinking time for this step: {:.2f} seconds</em></p>
97
+ </details>
98
+ <br>
99
+ """.format(title, content.replace('\n', '<br>'), thinking_time)
100
+ html_content += "<strong>Total thinking time: {:.2f} seconds</strong>".format(total_time)
101
+ return html_content
102
+
103
+ def main(api_key, user_query):
104
+ if not api_key:
105
+ return "Please enter your Groq API key to proceed.", ""
106
+
107
+ if not user_query:
108
+ return "Please enter a query to get started.", ""
109
+
110
+ try:
111
+ # Initialize the Groq client with the provided API key
112
+ client = groq.Groq(api_key=api_key)
113
+ except Exception as e:
114
+ return f"Failed to initialize Groq client. Error: {str(e)}", ""
115
+
116
+ try:
117
+ steps, total_time = generate_response(client, user_query)
118
+ formatted_steps = format_steps(steps, total_time)
119
+ except Exception as e:
120
+ return f"An error occurred during processing. Error: {str(e)}", ""
121
+
122
+ return formatted_steps, ""
123
+
124
+ # Define the Gradio interface
125
+ with gr.Blocks() as demo:
126
+ gr.Markdown("# 🧠 g1: Using Llama-3.1 70b on Groq to Create O1-like Reasoning Chains")
127
+
128
+ gr.Markdown("""
129
+ 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!
130
+
131
+ Open source [repository here](https://github.com/bklieger-groq)
132
+ """)
133
+
134
+ with gr.Row():
135
+ with gr.Column():
136
+ api_input = gr.Textbox(
137
+ label="Enter your Groq API Key:",
138
+ placeholder="Your Groq API Key",
139
+ type="password"
140
+ )
141
+ user_input = gr.Textbox(
142
+ label="Enter your query:",
143
+ placeholder="e.g., How many 'R's are in the word strawberry?",
144
+ lines=2
145
+ )
146
+ submit_btn = gr.Button("Generate Response")
147
+
148
+ with gr.Row():
149
+ with gr.Column():
150
+ output_html = gr.HTML()
151
+
152
+ submit_btn.click(fn=main, inputs=[api_input, user_input], outputs=output_html)
153
+
154
+ # Launch the Gradio app
155
+ if __name__ == "__main__":
156
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ groq