daniel-cerebras commited on
Commit
a836b76
1 Parent(s): 6f49f08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -36
app.py CHANGED
@@ -2,7 +2,7 @@ import gradio as gr
2
  import time
3
  import json
4
  from cerebras.cloud.sdk import Cerebras
5
- from typing import List, Dict, Tuple, Any
6
  from tenacity import retry, stop_after_attempt, wait_fixed
7
 
8
  def make_api_call(api_key: str, messages: List[Dict[str, str]], max_tokens: int, is_final_answer: bool = False) -> Dict[str, Any]:
@@ -12,6 +12,7 @@ def make_api_call(api_key: str, messages: List[Dict[str, str]], max_tokens: int,
12
  client = Cerebras(api_key=api_key)
13
 
14
  try:
 
15
  response = client.chat.completions.create(
16
  model="llama3.1-70b",
17
  messages=messages,
@@ -19,16 +20,31 @@ def make_api_call(api_key: str, messages: List[Dict[str, str]], max_tokens: int,
19
  temperature=0.2,
20
  response_format={"type": "json_object"}
21
  )
22
- return json.loads(response.choices[0].message.content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  except Exception as e:
24
  if is_final_answer:
25
  return {"title": "Error", "content": f"Failed to generate final answer. Error: {str(e)}"}
26
  else:
27
  return {"title": "Error", "content": f"Failed to generate step. Error: {str(e)}", "next_action": "final_answer"}
28
 
29
- def generate_response(api_key: str, prompt: str) -> Tuple[List[Tuple[str, str, float]], float]:
30
  """
31
  Generate a response to the given prompt using a step-by-step reasoning approach.
 
32
  """
33
  system_message = """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."""
34
 
@@ -41,6 +57,8 @@ def generate_response(api_key: str, prompt: str) -> Tuple[List[Tuple[str, str, f
41
  steps = []
42
  step_count = 1
43
  total_thinking_time = 0
 
 
44
 
45
  while True:
46
  start_time = time.time()
@@ -48,14 +66,24 @@ def generate_response(api_key: str, prompt: str) -> Tuple[List[Tuple[str, str, f
48
  thinking_time = time.time() - start_time
49
  total_thinking_time += thinking_time
50
 
51
- steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
 
 
 
 
 
 
52
  messages.append({"role": "assistant", "content": json.dumps(step_data)})
53
 
 
 
 
54
  if step_data.get('next_action') == 'final_answer':
55
  break
56
 
57
  step_count += 1
58
 
 
59
  messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
60
 
61
  start_time = time.time()
@@ -63,26 +91,36 @@ def generate_response(api_key: str, prompt: str) -> Tuple[List[Tuple[str, str, f
63
  thinking_time = time.time() - start_time
64
  total_thinking_time += thinking_time
65
 
66
- steps.append(("Final Answer", final_data.get('content', 'No final answer provided.'), thinking_time))
67
-
68
- return steps, total_thinking_time
 
 
 
 
 
 
69
 
70
- def generate_ui(api_key: str, prompt: str) -> Tuple[List[Tuple[str, str]], float]:
71
  """
72
- Generate the UI output based on the response to the given prompt.
73
  """
74
- steps, total_time = generate_response(api_key, prompt)
75
- conversation = []
76
- for title, content, _ in steps:
77
- if title.startswith("Step"):
78
- conversation.append(("Assistant", f"**{title}**\n\n{content}"))
79
- elif title == "Final Answer":
80
- conversation.append(("Assistant", f"**{title}**\n\n{content}"))
81
- else:
82
- conversation.append(("Assistant", content))
83
- return conversation, total_time
 
 
 
 
 
84
 
85
- # Gradio Blocks Interface with a Chatbot component and API key input
86
  def main():
87
  with gr.Blocks() as demo:
88
  gr.Markdown("# o1-like Chain of Thought - LLaMA-3.1 70B on Cerebras")
@@ -109,25 +147,11 @@ def main():
109
  submit_btn = gr.Button("Submit")
110
 
111
  thinking_time_display = gr.Textbox(
112
- label="Total Thinking Time",
113
  value="",
114
  interactive=False
115
  )
116
 
117
- def respond(api_key, message, history):
118
- if not api_key:
119
- return history, "Please provide a valid Cerebras API key."
120
-
121
- steps, total_time = generate_response(api_key, message)
122
- for title, content, _ in steps:
123
- if title.startswith("Step"):
124
- history.append(("Assistant", f"**{title}**\n\n{content}"))
125
- elif title == "Final Answer":
126
- history.append(("Assistant", f"**{title}**\n\n{content}"))
127
- else:
128
- history.append(("Assistant", content))
129
- return history, f"**Total thinking time:** {total_time:.2f} seconds"
130
-
131
  submit_btn.click(
132
  fn=respond,
133
  inputs=[api_key_input, user_input, chatbot],
@@ -135,7 +159,7 @@ def main():
135
  queue=True
136
  )
137
 
138
- # Optional: Allow pressing Enter to submit
139
  user_input.submit(
140
  fn=respond,
141
  inputs=[api_key_input, user_input, chatbot],
 
2
  import time
3
  import json
4
  from cerebras.cloud.sdk import Cerebras
5
+ from typing import List, Dict, Tuple, Any, Generator
6
  from tenacity import retry, stop_after_attempt, wait_fixed
7
 
8
  def make_api_call(api_key: str, messages: List[Dict[str, str]], max_tokens: int, is_final_answer: bool = False) -> Dict[str, Any]:
 
12
  client = Cerebras(api_key=api_key)
13
 
14
  try:
15
+ start_time = time.time()
16
  response = client.chat.completions.create(
17
  model="llama3.1-70b",
18
  messages=messages,
 
20
  temperature=0.2,
21
  response_format={"type": "json_object"}
22
  )
23
+ end_time = time.time()
24
+
25
+ content = json.loads(response.choices[0].message.content)
26
+
27
+ # Calculate tokens per second
28
+ total_tokens = response.usage.total_tokens
29
+ elapsed_time = end_time - start_time
30
+ tokens_per_second = total_tokens / elapsed_time if elapsed_time > 0 else 0
31
+
32
+ content['token_info'] = {
33
+ 'total_tokens': total_tokens,
34
+ 'tokens_per_second': tokens_per_second
35
+ }
36
+
37
+ return content
38
  except Exception as e:
39
  if is_final_answer:
40
  return {"title": "Error", "content": f"Failed to generate final answer. Error: {str(e)}"}
41
  else:
42
  return {"title": "Error", "content": f"Failed to generate step. Error: {str(e)}", "next_action": "final_answer"}
43
 
44
+ def generate_response(api_key: str, prompt: str) -> Generator[Tuple[List[Tuple[str, str]], float, int, float], None, None]:
45
  """
46
  Generate a response to the given prompt using a step-by-step reasoning approach.
47
+ This function is now a generator that yields each step as it's generated.
48
  """
49
  system_message = """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."""
50
 
 
57
  steps = []
58
  step_count = 1
59
  total_thinking_time = 0
60
+ total_tokens = 0
61
+ total_tokens_per_second = 0
62
 
63
  while True:
64
  start_time = time.time()
 
66
  thinking_time = time.time() - start_time
67
  total_thinking_time += thinking_time
68
 
69
+ token_info = step_data.pop('token_info', {'total_tokens': 0, 'tokens_per_second': 0})
70
+ total_tokens += token_info['total_tokens']
71
+ total_tokens_per_second += token_info['tokens_per_second']
72
+
73
+ step_title = f"Step {step_count}: {step_data['title']}"
74
+ step_content = f"{step_data['content']}\n\n**Cerebras LLM Call Duration: {thinking_time:.2f} seconds**\n**Tokens: {token_info['total_tokens']}, Tokens/s: {token_info['tokens_per_second']:.2f}**"
75
+ steps.append((step_title, step_content))
76
  messages.append({"role": "assistant", "content": json.dumps(step_data)})
77
 
78
+ # Yield the current conversation, total thinking time, total tokens, and average tokens per second
79
+ yield steps, total_thinking_time, total_tokens, total_tokens_per_second / step_count if step_count > 0 else 0
80
+
81
  if step_data.get('next_action') == 'final_answer':
82
  break
83
 
84
  step_count += 1
85
 
86
+ # Request the final answer
87
  messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
88
 
89
  start_time = time.time()
 
91
  thinking_time = time.time() - start_time
92
  total_thinking_time += thinking_time
93
 
94
+ token_info = final_data.pop('token_info', {'total_tokens': 0, 'tokens_per_second': 0})
95
+ total_tokens += token_info['total_tokens']
96
+ total_tokens_per_second += token_info['tokens_per_second']
97
+
98
+ final_content = f"{final_data.get('content', 'No final answer provided.')}\n\n**Final answer thinking time: {thinking_time:.2f} seconds**\n**Tokens: {token_info['total_tokens']}, Tokens/s: {token_info['tokens_per_second']:.2f}**"
99
+ steps.append(("Final Answer", final_content))
100
+
101
+ # Yield the final conversation, total thinking time, total tokens, and average tokens per second
102
+ yield steps, total_thinking_time, total_tokens, total_tokens_per_second / (step_count + 1)
103
 
104
+ def respond(api_key: str, message: str, history: List[Tuple[str, str]]) -> Generator[Tuple[List[Tuple[str, str]], str], None, None]:
105
  """
106
+ Generator function to handle responses and yield updates for streaming.
107
  """
108
+ if not api_key:
109
+ yield history, "Please provide a valid Cerebras API key."
110
+ return
111
+
112
+ # Initialize the generator
113
+ response_generator = generate_response(api_key, message)
114
+
115
+ for steps, total_time, total_tokens, avg_tokens_per_second in response_generator:
116
+ conversation = history.copy()
117
+ for title, content in steps[len(conversation):]:
118
+ if title.startswith("Step") or title == "Final Answer":
119
+ conversation.append((title, content))
120
+ else:
121
+ conversation.append((title, content))
122
+ yield conversation, f"**Total thinking time:** {total_time:.2f} seconds\n**Total tokens:** {total_tokens}\n**Average tokens/s:** {avg_tokens_per_second:.2f}"
123
 
 
124
  def main():
125
  with gr.Blocks() as demo:
126
  gr.Markdown("# o1-like Chain of Thought - LLaMA-3.1 70B on Cerebras")
 
147
  submit_btn = gr.Button("Submit")
148
 
149
  thinking_time_display = gr.Textbox(
150
+ label="Performance Metrics",
151
  value="",
152
  interactive=False
153
  )
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  submit_btn.click(
156
  fn=respond,
157
  inputs=[api_key_input, user_input, chatbot],
 
159
  queue=True
160
  )
161
 
162
+ # Allow pressing Enter to submit
163
  user_input.submit(
164
  fn=respond,
165
  inputs=[api_key_input, user_input, chatbot],