Spaces:
Build error
Build error
Update app.py
Browse files8 unmodified lines910111213141516171819202122232425262722 unmodified lines505152535455561 unmodified line5859606162636465666768693 unmodified lines73747576777879808182833 unmodified lines878889909192939495969798991008 unmodified linesmodel_name = "Qwen/Qwen2.5-72B-Instruct"client = InferenceClient(model_name)def llm_inference(user_sample):eos_token = "<|endoftext|>"output = client.chat.completions.create(messages=[{"role": "system","content": "You are a Python language guide. Write code on the user topic. If the input is code, correct it for mistakes."},{"role": "user","content": f"Write only python code without any explanation: {user_sample}"},],stream=False,temperature=0.7,top_p=0.1,22 unmodified linesSimple heuristic to determine if the user input is a math task.This can be enhanced with more sophisticated methods or NLP techniques."""math_keywords = ['calculate', 'compute', 'solve', 'integrate', 'differentiate', 'derivative', 'integral', 'factorial', 'sum', 'product']operators = ['+', '-', '*', '/', '^', '**', 'sqrt', 'sin', 'cos', 'tan', 'log', 'exp']user_input_lower = user_input.lower()return any(keyword in user_input_lower for keyword in math_keywords) or any(op in user_input for op in operators)1 unmodified linedef chat(user_input, history):"""Handles the chat interaction. If the user input is detected as a math task,it generates Python code to solve it, strips any code tags, executes the code,and returns the result."""if is_math_task(user_input):# Generate Python code for the math taskgenerated_code = llm_inference(f"Create a Python program to solve the following math problem:\n{user_input}")# Strip code tags using regex# This regex removes ```python and ``` or any other markdown code fences3 unmodified lines# Execute the cleaned codeexecution_result = execute_code(cleaned_code)# Prepare the responsesassistant_response = f"**Generated Python Code:**\n```python\n{cleaned_code}\n```\n\n**Execution Result:**\n```\n{execution_result}\n```"else:# For regular chat messages, use the AI's responseassistant_response = llm_inference(user_input)# Append to chat historyhistory.append((user_input, assistant_response))3 unmodified linesgr.Markdown("# 🐍 Python Helper Chatbot")with gr.Tab("Chat"):chatbot = gr.Chatbot()msg = gr.Textbox(placeholder="Type your message here...")msg.submit(chat, inputs=[msg, chatbot], outputs=[chatbot, chatbot])with gr.Tab("Interpreter"):gr.Markdown("### 🖥️ Test Your Code")code_input = gr.Code(language="python")run_button = gr.Button("Run Code")code_output = gr.Textbox(label="Output")run_button.click(execute_code, inputs=code_input, outputs=code_output)with gr.Tab("Logs"):8 unmodified lines910111213141516171822 unmodified lines4142434445464748495051521 unmodified line54555657585960616263646566676869707172737475767778798081828384858687888990913 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181193 unmodified lines1231241251261271281291301311321331341351368 unmodified linesmodel_name = "Qwen/Qwen2.5-72B-Instruct"client = InferenceClient(model_name)def llm_inference(messages):eos_token = "<|endoftext|>"output = client.chat.completions.create(messages=messages,stream=False,temperature=0.7,top_p=0.1,22 unmodified linesSimple heuristic to determine if the user input is a math task.This can be enhanced with more sophisticated methods or NLP techniques."""math_keywords = ['calculate', 'compute', 'solve', 'integrate', 'differentiate','derivative', 'integral', 'factorial', 'sum', 'product','average', 'mean', 'median', 'mode', 'variance', 'standard deviation','limit', 'matrix', 'determinant', 'equation', 'expression']operators = ['+', '-', '*', '/', '^', '**', 'sqrt', 'sin', 'cos', 'tan', 'log', 'exp']user_input_lower = user_input.lower()return any(keyword in user_input_lower for keyword in math_keywords) or any(op in user_input for op in operators)1 unmodified linedef chat(user_input, history):"""Handles the chat interaction. If the user input is detected as a math task,it performs a two-step process:1. Generates an explanation of how to solve the task.2. Generates Python code based on the explanation and executes it."""if is_math_task(user_input):# Step 1: Generate Explanationexplanation_messages = [{"role": "system","content": "You are a Python language guide. Provide a concise explanation on how to approach the following mathematical task without calculating the answer."},{"role": "user","content": f"Provide a short explanation on how to solve the following mathematical problem: {user_input}"},]explanation = llm_inference(explanation_messages)# Step 2: Generate Python Code using Explanation and User Promptcode_prompt = f"Based on the following explanation, write a Python program to solve the mathematical task. Ensure that the program includes a print statement to output the answer.\n\nExplanation: {explanation}\n\nTask: {user_input}"code_messages = [{"role": "system","content": "You are a Python developer. Write Python code based on the provided explanation and task."},{"role": "user","content": f"{code_prompt}"},]generated_code = llm_inference(code_messages)# Strip code tags using regex# This regex removes ```python and ``` or any other markdown code fences3 unmodified lines# Execute the cleaned codeexecution_result = execute_code(cleaned_code)# Prepare the assistant responseassistant_response = (f"**Explanation:**\n{explanation}\n\n"f"**Generated Python Code:**\n```python\n{cleaned_code}\n```\n\n"f"**Execution Result:**\n```\n{execution_result}\n```")else:# For regular chat messages, use the AI's responsemessages = [{"role": "system","content": "You are a helpful assistant."},{"role": "user","content": user_input},]assistant_response = llm_inference(messages)# Append to chat historyhistory.append((user_input, assistant_response))3 unmodified linesgr.Markdown("# 🐍 Python Helper Chatbot")with gr.Tab("Chat"):chatbot = gr.Chatbot()msg = gr.Textbox(placeholder="Type your message here...", label="Your Message")msg.submit(chat, inputs=[msg, chatbot], outputs=[chatbot, chatbot])with gr.Tab("Interpreter"):gr.Markdown("### 🖥️ Test Your Code")code_input = gr.Code(language="python", label="Python Code Input")run_button = gr.Button("Run Code")code_output = gr.Textbox(label="Output", lines=10)run_button.click(execute_code, inputs=code_input, outputs=code_output)with gr.Tab("Logs"):
app.py+58-22