Spaces:
saq1b
/
Sleeping

Saqib commited on
Commit
11d9668
·
verified ·
1 Parent(s): 370df13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -29
app.py CHANGED
@@ -1,20 +1,14 @@
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:
@@ -23,9 +17,9 @@ def make_api_call(client, messages, max_tokens, is_final_answer=False):
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
@@ -34,9 +28,9 @@ Example of a valid JSON response:
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 = []
@@ -45,7 +39,7 @@ Example of a valid JSON response:
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
@@ -59,7 +53,7 @@ Example of a valid JSON response:
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
@@ -67,10 +61,10 @@ Example of a valid JSON response:
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
@@ -102,19 +96,30 @@ def format_steps(steps, total_time):
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)}", ""
@@ -123,10 +128,10 @@ def main(api_key, user_query):
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
  """)
@@ -134,8 +139,8 @@ with gr.Blocks() as demo:
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(
@@ -153,4 +158,4 @@ with gr.Blocks() as demo:
153
 
154
  # Launch the Gradio app
155
  if __name__ == "__main__":
156
- demo.launch()
 
1
  import gradio as gr
2
+ import google.generativeai as genai
3
  import os
4
  import json
5
  import time
6
 
7
+ def make_api_call(model, messages, max_tokens, is_final_answer=False):
8
  for attempt in range(3):
9
  try:
10
+ response = model.generate_content(messages)
11
+ return json.loads(response.text)
 
 
 
 
 
 
12
  except Exception as e:
13
  if attempt == 2:
14
  if is_final_answer:
 
17
  return {"title": "Error", "content": f"Failed to generate step after 3 attempts. Error: {str(e)}", "next_action": "final_answer"}
18
  time.sleep(1) # Wait for 1 second before retrying
19
 
20
+ def generate_response(model, prompt):
21
  messages = [
22
+ {"role": "user", "parts": ["""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.
23
 
24
  Example of a valid JSON response:
25
  ```json
 
28
  "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...",
29
  "next_action": "continue"
30
  }```
31
+
32
+ Now, please respond to the following prompt: """ + prompt]},
33
+ {"role": "model", "parts": ["Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."]}
34
  ]
35
 
36
  steps = []
 
39
 
40
  while True:
41
  start_time = time.time()
42
+ step_data = make_api_call(model, messages, 300)
43
  end_time = time.time()
44
  thinking_time = end_time - start_time
45
  total_thinking_time += thinking_time
 
53
  step_content = step_data.get('content', 'No Content')
54
  steps.append((step_title, step_content, thinking_time))
55
 
56
+ messages.append({"role": "model", "parts": [json.dumps(step_data)]})
57
 
58
  if step_data.get('next_action') == 'final_answer':
59
  break
 
61
  step_count += 1
62
 
63
  # Generate final answer
64
+ messages.append({"role": "user", "parts": ["Please provide the final answer based on your reasoning above."]})
65
 
66
  start_time = time.time()
67
+ final_data = make_api_call(model, messages, 200, is_final_answer=True)
68
  end_time = time.time()
69
  thinking_time = end_time - start_time
70
  total_thinking_time += thinking_time
 
96
 
97
  def main(api_key, user_query):
98
  if not api_key:
99
+ return "Please enter your Google API key to proceed.", ""
100
 
101
  if not user_query:
102
  return "Please enter a query to get started.", ""
103
 
104
  try:
105
+ # Initialize the Google Gemini model with the provided API key
106
+ genai.configure(api_key=api_key)
107
+ # generation_config = {
108
+ # "temperature": 0.2,
109
+ # "top_p": 0.95,
110
+ # "top_k": 64,
111
+ # "max_output_tokens": 8192,
112
+ # "response_mime_type": "text/plain",
113
+ # }
114
+ model = genai.GenerativeModel(
115
+ model_name="gemini-1.5-flash-exp-0827",
116
+ # generation_config=generation_config,
117
+ )
118
  except Exception as e:
119
+ return f"Failed to initialize Google Gemini model. Error: {str(e)}", ""
120
 
121
  try:
122
+ steps, total_time = generate_response(model, user_query)
123
  formatted_steps = format_steps(steps, total_time)
124
  except Exception as e:
125
  return f"An error occurred during processing. Error: {str(e)}", ""
 
128
 
129
  # Define the Gradio interface
130
  with gr.Blocks() as demo:
131
+ gr.Markdown("# 🧠 g1: Using Google Gemini to Create O1-like Reasoning Chains")
132
 
133
  gr.Markdown("""
134
+ 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 Google Gemini for fast reasoning steps!
135
 
136
  Open source [repository here](https://github.com/bklieger-groq)
137
  """)
 
139
  with gr.Row():
140
  with gr.Column():
141
  api_input = gr.Textbox(
142
+ label="Enter your Google API Key:",
143
+ placeholder="Your Google API Key",
144
  type="password"
145
  )
146
  user_input = gr.Textbox(
 
158
 
159
  # Launch the Gradio app
160
  if __name__ == "__main__":
161
+ demo.launch()