daniel-cerebras's picture
Create app.py
3ca90f6 verified
raw
history blame
No virus
4.57 kB
import gradio as gr
import time
import json
from cerebras.cloud.sdk import Cerebras
from typing import List, Dict, Tuple, Any
from tenacity import retry, stop_after_attempt, wait_fixed
def make_api_call(api_key: str, messages: List[Dict[str, str]], max_tokens: int, is_final_answer: bool = False) -> Dict[str, Any]:
"""
Make an API call to the Cerebras chat completions endpoint with retry logic.
"""
client = Cerebras(api_key=api_key)
try:
response = client.chat.completions.create(
model="llama3.1-70b",
messages=messages,
max_tokens=max_tokens,
temperature=0.2,
response_format={"type": "json_object"}
)
return json.loads(response.choices[0].message.content)
except Exception as e:
if is_final_answer:
return {"title": "Error", "content": f"Failed to generate final answer. Error: {str(e)}"}
else:
return {"title": "Error", "content": f"Failed to generate step. Error: {str(e)}", "next_action": "final_answer"}
def generate_response(api_key: str, prompt: str) -> Tuple[List[Tuple[str, str, float]], float]:
"""
Generate a response to the given prompt using a step-by-step reasoning approach.
"""
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."""
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt},
{"role": "assistant", "content": "Thank you! I will now think step by step following my instructions, starting at the beginning after decomposing the problem."}
]
steps = []
step_count = 1
total_thinking_time = 0
while True:
start_time = time.time()
step_data = make_api_call(api_key, messages, 300)
thinking_time = time.time() - start_time
total_thinking_time += thinking_time
steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
messages.append({"role": "assistant", "content": json.dumps(step_data)})
if step_data['next_action'] == 'final_answer':
break
step_count += 1
messages.append({"role": "user", "content": "Please provide the final answer based on your reasoning above."})
start_time = time.time()
final_data = make_api_call(api_key, messages, 200, is_final_answer=True)
thinking_time = time.time() - start_time
total_thinking_time += thinking_time
steps.append(("Final Answer", final_data['content'], thinking_time))
return steps, total_thinking_time
def generate_ui(api_key: str, prompt: str) -> str:
"""
Generate the UI output based on the response to the given prompt.
"""
steps, total_time = generate_response(api_key, prompt)
result = "\n\n".join([
f"{'### ' if title.startswith('Final Answer') else '**'}{title}{'**' if not title.startswith('Final Answer') else ''}\n\n{content}"
for title, content, _ in steps
])
result += f"\n\n**Total thinking time:** {total_time:.2f} seconds"
return result
# Gradio Interface with an API key input box
iface = gr.Interface(
fn=generate_ui,
inputs=[gr.Textbox(label="API Key", type="password", placeholder="Enter your Cerebras API key"),
gr.Textbox(lines=2, label="Query", placeholder="Enter your query here...")],
outputs="markdown",
title="o1-like chain of thought - llama-3.1 70b on Cerebras",
description="""
Implement Chain of Thought with prompting to improve output accuracy.
It is powered by Cerebras, ensuring fast reasoning steps.
"""
)
if __name__ == "__main__":
iface.launch()