akhaliq HF staff commited on
Commit
ebc0424
1 Parent(s): f70e833

Create app.py

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