import gradio as gr import os import subprocess import requests import json import re import time # --- 1. 환경 설정 및 강화된 API 호출 함수 --- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY") CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions" def call_mistral_api(system_prompt: str, user_prompt: str): """향상된 Mistral API 호출 함수""" if not MISTRAL_API_KEY: raise gr.Error("MISTRAL_API_KEY is not set. Please add it to your Space Secrets.") headers = {"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"} messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}] data = {"model": "codestral-latest", "messages": messages} try: response = requests.post(CODESTRAL_ENDPOINT, headers=headers, data=json.dumps(data), timeout=60) response.raise_for_status() return response.json()["choices"][0]["message"]["content"] except requests.exceptions.RequestException as e: raise gr.Error(f"API Call Error: {e}") # --- 2. 백엔드 핵심 기능 (안정성 강화) --- def parse_code_from_response(response_text: str) -> str | None: """C 코드 블록을 파싱하는 안정적인 함수""" match = re.search(r'```(?:c)?\n(.*?)\n```', response_text, re.DOTALL) if match: return match.group(1).strip() # 비상시 순수 코드 응답 처리 if response_text.strip().startswith("#include") and response_text.strip().endswith("}"): return response_text.strip() return None def generate_c_code(description: str) -> str: system_prompt = "You are an expert C code generator..." # (이전과 동일) user_prompt = f"Generate C code for: '{description}'" response = call_mistral_api(system_prompt, user_prompt) return parse_code_from_response(response) or f"// Failed to parse code from response:\n{response}" def compile_and_run_c_code(code: str) -> str: """컴파일 및 실행 함수""" if not code.strip(): return "--- SYSTEM ERROR ---\nCode is empty." with open("main.c", "w", encoding='utf-8') as f: f.write(code) compile_proc = subprocess.run(["gcc", "main.c", "-o", "main.out", "-lm", "-w"], capture_output=True, text=True, timeout=15) if compile_proc.returncode != 0: return f"--- COMPILATION FAILED ---\n{compile_proc.stderr}" run_proc = subprocess.run(["./main.out"], capture_output=True, text=True, timeout=15) if run_proc.returncode != 0: return f"--- RUNTIME ERROR ---\n{run_proc.stderr}" output = run_proc.stdout return f"--- EXECUTION SUCCEEDED ---\n{output}" if output.strip() else "--- EXECUTION SUCCEEDED ---\n(No output)" def analyze_and_refactor_code(code: str, instruction: str) -> str: system_prompt = "You are a world-class C code reviewer..." # (이전과 동일) user_prompt = f"Instruction: '{instruction}'\n\nC Code:\n```c\n{code}\n```" return call_mistral_api(system_prompt, user_prompt) # ⭐️ 새로운 기능: 외부 MCP 툴을 사용하는 클라이언트 함수 def call_external_mcp_tool(tool_url: str, code: str, instruction: str) -> str: """다른 Gradio Space MCP 툴을 API로 호출하는 함수""" # Gradio 클라이언트를 사용하여 외부 API 호출 (gradio_client 설치 필요) from gradio_client import Client try: client = Client(tool_url) # 외부 툴의 API 엔드포인트와 파라미터 이름에 맞춰야 함 # 예시: predict(code_to_analyze=code, user_instruction=instruction) result = client.predict(code, instruction, api_name="/predict") # api_name은 외부 툴에 따라 다름 return f"--- EXTERNAL TOOL SUCCEEDED ---\n{result}" except Exception as e: return f"--- EXTERNAL TOOL FAILED ---\nCould not call tool at {tool_url}. Error: {e}" # --- 3. 1등을 위한 지능형 에이전트 로직 (최종 버전) --- def ultimate_agent_ide(initial_code: str, full_instruction: str): tasks = [task.strip() for task in re.split(r'\s+and then\s+|\s+and\s+|,\s*then\s*|\s*그리고\s+|\s*후에\s*', full_instruction, flags=re.IGNORECASE) if task.strip()] current_code = initial_code log = [] # Step 1: 계획 수립 log.append("### 📝 Agent's Plan") plan = "".join([f"\n{i+1}. {task}" for i, task in enumerate(tasks)]) log.append(plan) yield current_code, "\n".join(log) time.sleep(1) # Step 2: 계획 실행 for i, task in enumerate(tasks): log.append(f"\n
▶ Step {i+1}: {task}\n") yield current_code, "\n".join(log) time.sleep(0.5) lower_task = task.lower() # ⭐️ 에이전트의 '생각'과 '행동' if "generate" in lower_task or "create" in lower_task or "만들어" in lower_task: log.append("🧠 **Thought:** The user wants new code. Using `generate_c_code` tool.") yield current_code, "\n".join(log) new_code = generate_c_code(task) if new_code and not new_code.startswith("//"): current_code = new_code log.append("\n✅ **Action Result:** Code generated and updated in the editor.") else: log.append(f"\n❌ **Action Result:** Generation failed. {new_code}") elif "compile" in lower_task or "run" in lower_task or "실행" in lower_task: log.append("🧠 **Thought:** The user wants to compile and run. Using `compile_and_run_c_code` tool.") yield current_code, "\n".join(log) result = compile_and_run_c_code(current_code) log.append(f"\n💻 **Action Result:**\n```\n{result}\n```") # ⭐️⭐️ 자가 수정 (SELF-CORRECTION) 로직 ⭐️⭐️ if "COMPILATION FAILED" in result: log.append("\n\n🧠 **Thought:** Compilation failed. I will try to fix the code myself.") yield current_code, "\n".join(log) time.sleep(1) error_message = result.split("--- COMPILATION FAILED ---")[1] fix_instruction = f"The following C code failed to compile with this error:\n\n**Error:**\n```\n{error_message}\n```\n\nPlease fix the code so it compiles successfully. Provide only the complete, corrected C code." log.append("\n🛠️ **Self-Correction:** Asking the LLM to fix the error...") yield current_code, "\n".join(log) fixed_code_response = analyze_and_refactor_code(current_code, fix_instruction) fixed_code = parse_code_from_response(fixed_code_response) if fixed_code: current_code = fixed_code log.append("\n✅ **Self-Correction Result:** A potential fix has been applied to the code editor. Please try compiling again.") else: log.append("\n❌ **Self-Correction Result:** Failed to automatically fix the code.") # ⭐️⭐️ 외부 MCP 툴 사용 예시 ⭐️⭐️ elif "security" in lower_task or "보안" in lower_task: log.append("🧠 **Thought:** The user wants a security analysis. I will use an external MCP tool for this.") yield current_code, "\n".join(log) # 이 URL은 예시이며, 실제 작동하는 보안 분석 MCP Space가 있다면 그 주소를 넣어야 합니다. # 해커톤 제출 시, 직접 간단한 보안분석 툴을 하나 더 만들거나, 다른 참가자의 툴을 사용하는 모습을 보여주면 최고입니다. external_tool_url = "user-provided-security-tool-space-url" log.append(f"\n🔌 **Action:** Calling external tool at `{external_tool_url}`...") yield current_code, "\n".join(log) # 실제로는 instruction에서 URL을 파싱해야 하지만, 여기서는 하드코딩으로 예시를 보여줍니다. security_result = call_external_mcp_tool(external_tool_url, current_code, task) log.append(f"\n🛡️ **Action Result:**\n```\n{security_result}\n```") else: log.append("🧠 **Thought:** The user wants to analyze or refactor. Using `analyze_and_refactor_code` tool.") yield current_code, "\n".join(log) analysis_result = analyze_and_refactor_code(current_code, task) refactored_code = parse_code_from_response(analysis_result) if refactored_code: current_code = refactored_code log.append("\n✅ **Action Result:** Code refactored and updated in the editor.") log.append(f"\n🔎 **Analysis Result:**\n{analysis_result}") log.append("
") yield current_code, "\n".join(log) log.append("\n\n--- All tasks complete. ---") yield current_code, "\n".join(log) # --- 4. 통합된 Gradio UI (출력 컴포넌트를 Markdown으로 변경) --- with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo: gr.Markdown("# 🏆 The Ultimate C-Codestral IDE Agent 🏆") with gr.Tabs(): with gr.TabItem("👨‍💻 IDE Agent"): with gr.Row(equal_height=True): with gr.Column(scale=2): code_editor = gr.Code(label="C Code Editor", language="c", lines=28, interactive=True, value='#include \n\nint main() {\n printf("Hello, World!\\n");\n return 0;\n}') with gr.Column(scale=1): instruction_box = gr.Textbox(label="Instruction", placeholder="e.g., 'Refactor this code, then compile it, then check security'", lines=4) execute_btn = gr.Button("Execute", variant="primary", size="lg") # 출력을 Markdown으로 변경하여 풍부한 UI를 제공 output_box = gr.Markdown(label="Console / Output") execute_btn.click( fn=ultimate_agent_ide, inputs=[code_editor, instruction_box], outputs=[code_editor, output_box] ) with gr.TabItem("🛠️ MCP Tools API"): # MCP 탭은 이전과 동일하게 유지 gr.Markdown("## Available MCP Tools for other Agents\nThese APIs are the building blocks of our IDE agent.") with gr.Accordion("Tool: Generate C Code", open=False): gr.Interface(fn=generate_c_code, inputs="text", outputs=gr.Code(language="c", label="Generated C Code")) with gr.Accordion("Tool: Compile & Run C Code", open=False): gr.Interface(fn=compile_and_run_c_code, inputs=gr.Code(language="c"), outputs=gr.Textbox(label="Output")) with gr.Accordion("Tool: Analyze & Refactor C Code", open=False): gr.Interface(fn=analyze_and_refactor_code, inputs=[gr.Code(language="c", label="Code to Analyze"), gr.Textbox(label="Instruction")], outputs=gr.Markdown()) if __name__ == "__main__": demo.queue().launch()