akhaliq HF staff commited on
Commit
64ed550
1 Parent(s): 6f49f08

streaming outputs

Browse files
Files changed (1) hide show
  1. app.py +35 -35
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]:
@@ -26,9 +26,10 @@ def make_api_call(api_key: str, messages: List[Dict[str, str]], max_tokens: int,
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
 
@@ -48,14 +49,20 @@ 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 +70,33 @@ 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")
@@ -114,20 +128,6 @@ def main():
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 +135,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],
@@ -146,4 +146,4 @@ def main():
146
  demo.launch()
147
 
148
  if __name__ == "__main__":
149
- main()
 
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]:
 
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) -> Generator[Tuple[List[Tuple[str, str]], float], None, None]:
30
  """
31
  Generate a response to the given prompt using a step-by-step reasoning approach.
32
+ This function is now a generator that yields each step as it's generated.
33
  """
34
  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."""
35
 
 
49
  thinking_time = time.time() - start_time
50
  total_thinking_time += thinking_time
51
 
52
+ step_title = f"Step {step_count}: {step_data['title']}"
53
+ step_content = step_data['content']
54
+ steps.append((step_title, step_content))
55
  messages.append({"role": "assistant", "content": json.dumps(step_data)})
56
 
57
+ # Yield the current conversation and total thinking time
58
+ yield steps, total_thinking_time
59
+
60
  if step_data.get('next_action') == 'final_answer':
61
  break
62
 
63
  step_count += 1
64
 
65
+ # Request the final answer
66
  messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
67
 
68
  start_time = time.time()
 
70
  thinking_time = time.time() - start_time
71
  total_thinking_time += thinking_time
72
 
73
+ steps.append(("Final Answer", final_data.get('content', 'No final answer provided.')))
74
+
75
+ # Yield the final conversation and total thinking time
76
+ yield steps, total_thinking_time
77
 
78
+ def respond(api_key: str, message: str, history: List[Tuple[str, str]]) -> Generator[Tuple[List[Tuple[str, str]], str], None, None]:
79
  """
80
+ Generator function to handle responses and yield updates for streaming.
81
  """
82
+ if not api_key:
83
+ yield history, "Please provide a valid Cerebras API key."
84
+ return
85
+
86
+ # Initialize the generator
87
+ response_generator = generate_response(api_key, message)
88
+
89
+ for steps, total_time in response_generator:
90
+ conversation = history.copy()
91
+ for title, content in steps[len(conversation)//2:]:
92
+ if title.startswith("Step"):
93
+ conversation.append(("Assistant", f"**{title}**\n\n{content}"))
94
+ elif title == "Final Answer":
95
+ conversation.append(("Assistant", f"**{title}**\n\n{content}"))
96
+ else:
97
+ conversation.append(("Assistant", content))
98
+ yield conversation, f"**Total thinking time:** {total_time:.2f} seconds"
99
 
 
100
  def main():
101
  with gr.Blocks() as demo:
102
  gr.Markdown("# o1-like Chain of Thought - LLaMA-3.1 70B on Cerebras")
 
128
  interactive=False
129
  )
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  submit_btn.click(
132
  fn=respond,
133
  inputs=[api_key_input, user_input, chatbot],
 
135
  queue=True
136
  )
137
 
138
+ # Allow pressing Enter to submit
139
  user_input.submit(
140
  fn=respond,
141
  inputs=[api_key_input, user_input, chatbot],
 
146
  demo.launch()
147
 
148
  if __name__ == "__main__":
149
+ main()