from urllib.parse import urljoin
import requests
import time 
from argparse import Namespace

import asyncio
from openai import OpenAI



def debug_code_function(code, error, api_key="your_api_key"):

    API_BASE_URL = api_key
    MODEL_NAME = "Qwen2.5-72B-Instruct"
    client = OpenAI(
        api_key="empty",
        base_url=API_BASE_URL,
    )

    prompt = f"""You are a code expert. I need you to debug the following code. Below are the code originally generated by the model and the error information that occurred during code execution. Please output ONLY the corrected Python code, without any explanation or markdown formatting:

    **Inputs:**

    **Original Code:**
    {code}

    **Execution Error:**
    {error}

    Output the corrected Python code only, without any explanation or markdown formatting:
    """

    chat_response = client.chat.completions.create(
        model=MODEL_NAME,
        messages=[
            {
                "role": "user",
                "content": prompt,
            }
        ],
    )
    
    response_text = chat_response.choices[0].message.content
    
    if "```python" in response_text and "```" in response_text:
        code_start = response_text.find("```python") + 9
        code_end = response_text.find("```", code_start)
        extracted_code = response_text[code_start:code_end].strip()
    else:
        extracted_code = response_text.strip()
    print("提取的代码:", extracted_code)
    return extracted_code






if __name__ == "__main__":

    code = """
x, y = symbols('x y')

eq1 = x**2 + y**2 = 25
eq2 = 2*x + y = 10

solution = solve((eq1, eq2), (x, y))
print(f"Solution: {solution}")
    """
    
    error = "SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '=' ?"
    
    debug_code_function(code, error)
    