xylin commited on
Commit
0bbe696
·
verified ·
1 Parent(s): dd7476e

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +80 -0
  2. g1.py +90 -0
  3. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import time
5
+ import groq
6
+ from g1 import generate_response
7
+
8
+ def format_steps(steps, total_time):
9
+ md_content = ""
10
+ for title, content, thinking_time in steps:
11
+ if title == "Final Answer":
12
+ md_content += f"### {title}\n"
13
+ md_content += f"{content}\n"
14
+ else:
15
+ md_content += f"#### {title}\n"
16
+ md_content += f"{content}\n"
17
+ md_content += f"_Thinking time for this step: {thinking_time:.2f} seconds_\n"
18
+ md_content += "\n---\n"
19
+ if total_time!=0:
20
+ md_content += f"\n**Total thinking time: {total_time:.2f} seconds**"
21
+ return md_content
22
+
23
+ def main(api_key, user_query):
24
+ if not api_key:
25
+ yield "Please enter your Groq API key to proceed."
26
+ return
27
+
28
+ if not user_query:
29
+ yield "Please enter a query to get started."
30
+ return
31
+
32
+ try:
33
+ # Initialize the Groq client with the provided API key
34
+ client = groq.Groq(api_key=api_key)
35
+ except Exception as e:
36
+ yield f"Failed to initialize Groq client. Error: {str(e)}"
37
+ return
38
+
39
+ try:
40
+ for steps, total_time in generate_response(user_query, custom_client=client):
41
+ formatted_steps = format_steps(steps, total_time if total_time is not None else 0)
42
+ yield formatted_steps
43
+ except Exception as e:
44
+ yield f"An error occurred during processing. Error: {str(e)}"
45
+ return
46
+
47
+ # Define the Gradio interface
48
+ with gr.Blocks() as demo:
49
+ gr.Markdown("# 🧠 g1: Using Llama-3.1 70b on Groq to Create O1-like Reasoning Chains")
50
+
51
+ gr.Markdown("""
52
+ 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!
53
+
54
+ Open source [repository here](https://github.com/bklieger-groq)
55
+ """)
56
+
57
+ with gr.Row():
58
+ with gr.Column():
59
+ api_input = gr.Textbox(
60
+ label="Enter your Groq API Key:",
61
+ placeholder="Your Groq API Key",
62
+ type="password"
63
+ )
64
+ user_input = gr.Textbox(
65
+ label="Enter your query:",
66
+ placeholder="e.g., How many 'R's are in the word strawberry?",
67
+ lines=2
68
+ )
69
+ submit_btn = gr.Button("Generate Response")
70
+ gr.Markdown("\n")
71
+
72
+ with gr.Row():
73
+ with gr.Column():
74
+ output_md = gr.Markdown()
75
+
76
+ submit_btn.click(fn=main, inputs=[api_input, user_input], outputs=output_md)
77
+
78
+ # Launch the Gradio app
79
+ if __name__ == "__main__":
80
+ demo.launch()
g1.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import groq
2
+ import time
3
+ import os
4
+ import json
5
+
6
+ client = groq.Groq()
7
+
8
+ def make_api_call(messages, max_tokens, is_final_answer=False, custom_client=None):
9
+ global client
10
+ if custom_client != None:
11
+ client = custom_client
12
+
13
+ for attempt in range(3):
14
+ try:
15
+ if is_final_answer:
16
+ response = client.chat.completions.create(
17
+ model="llama-3.1-70b-versatile",
18
+ messages=messages,
19
+ max_tokens=max_tokens,
20
+ temperature=0.2,
21
+ )
22
+ return response.choices[0].message.content
23
+ else:
24
+ response = client.chat.completions.create(
25
+ model="llama-3.1-70b-versatile",
26
+ messages=messages,
27
+ max_tokens=max_tokens,
28
+ temperature=0.2,
29
+ response_format={"type": "json_object"}
30
+ )
31
+ return json.loads(response.choices[0].message.content)
32
+ except Exception as e:
33
+ if attempt == 2:
34
+ if is_final_answer:
35
+ return {"title": "Error", "content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}"}
36
+ else:
37
+ return {"title": "Error", "content": f"Failed to generate step after 3 attempts. Error: {str(e)}", "next_action": "final_answer"}
38
+ time.sleep(1) # Wait for 1 second before retrying
39
+
40
+ def generate_response(prompt, custom_client=None):
41
+ messages = [
42
+ {"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.
43
+
44
+ Example of a valid JSON response:
45
+ ```json
46
+ {
47
+ "title": "Identifying Key Information",
48
+ "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...",
49
+ "next_action": "continue"
50
+ }```
51
+ """},
52
+ {"role": "user", "content": prompt},
53
+ {"role": "assistant", "content": "Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."}
54
+ ]
55
+
56
+ steps = []
57
+ step_count = 1
58
+ total_thinking_time = 0
59
+
60
+ while True:
61
+ start_time = time.time()
62
+ step_data = make_api_call(messages, 300, custom_client=custom_client)
63
+ end_time = time.time()
64
+ thinking_time = end_time - start_time
65
+ total_thinking_time += thinking_time
66
+
67
+ steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
68
+
69
+ messages.append({"role": "assistant", "content": json.dumps(step_data)})
70
+
71
+ if step_data['next_action'] == 'final_answer' or step_count > 25: # Maximum of 25 steps to prevent infinite thinking time. Can be adjusted.
72
+ break
73
+
74
+ step_count += 1
75
+
76
+ # Yield after each step for Streamlit to update
77
+ yield steps, None # We're not yielding the total time until the end
78
+
79
+ # Generate final answer
80
+ messages.append({"role": "user", "content": "Please provide the final answer based solely on your reasoning above. Do not use JSON formatting. Only provide the text response without any titles or preambles. Retain any formatting as instructed by the original prompt, such as exact formatting for free response or multiple choice."})
81
+
82
+ start_time = time.time()
83
+ final_data = make_api_call(messages, 1200, is_final_answer=True, custom_client=custom_client)
84
+ end_time = time.time()
85
+ thinking_time = end_time - start_time
86
+ total_thinking_time += thinking_time
87
+
88
+ steps.append(("Final Answer", final_data, thinking_time))
89
+
90
+ yield steps, total_thinking_time
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ groq