Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,46 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import subprocess
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
# --- 1. 환경 설정 ---
|
| 7 |
API_KEY = os.environ.get("MISTRAL_API_KEY")
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
if API_KEY:
|
| 12 |
-
try:
|
| 13 |
-
CLIENT = MistralClient(api_key=API_KEY, endpoint=CODESTRAL_ENDPOINT)
|
| 14 |
-
print("Mistral API Client for Codestral initialized successfully.")
|
| 15 |
-
except Exception as e:
|
| 16 |
-
print(f"Error initializing Mistral Client: {e}")
|
| 17 |
-
else:
|
| 18 |
print("FATAL: MISTRAL_API_KEY is not set in Space Secrets.")
|
| 19 |
|
| 20 |
-
# --- 2. 백엔드 핵심 기능 함수 ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def generate_c_code(description: str) -> str:
|
| 22 |
-
if not CLIENT: return "Error: Mistral API key not configured."
|
| 23 |
prompt = f"You are a C programming expert. Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code, without any markdown formatting or explanations."
|
| 24 |
messages = [{"role": "user", "content": prompt}]
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def compile_and_run_c_code(code: str) -> str:
|
| 29 |
try:
|
|
@@ -37,7 +54,6 @@ def compile_and_run_c_code(code: str) -> str:
|
|
| 37 |
except Exception as e: return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
|
| 38 |
|
| 39 |
def analyze_and_refactor_code(code: str, instruction: str) -> str:
|
| 40 |
-
if not CLIENT: return "Error: Mistral API key not configured."
|
| 41 |
prompt = f"""You are a senior C code reviewer. Analyze the following C code based on the user's instruction.
|
| 42 |
Provide a clear, concise response. If refactoring, provide the complete improved code in a C code block.
|
| 43 |
|
|
@@ -48,8 +64,7 @@ C Code to Analyze:
|
|
| 48 |
{code}
|
| 49 |
```"""
|
| 50 |
messages = [{"role": "user", "content": prompt}]
|
| 51 |
-
|
| 52 |
-
return response.choices[0].message.content
|
| 53 |
|
| 54 |
# --- 3. 메인 이벤트 핸들러 ---
|
| 55 |
def handle_instruction(code: str, instruction: str):
|
|
@@ -58,14 +73,12 @@ def handle_instruction(code: str, instruction: str):
|
|
| 58 |
|
| 59 |
lower_instruction = instruction.lower()
|
| 60 |
|
| 61 |
-
# 'generate' 또는 'create'가 포함된 경우, 코드 에디터가 비어있어도 무조건 생성
|
| 62 |
if "generate" in lower_instruction or "create" in lower_instruction or "만들어줘" in lower_instruction:
|
| 63 |
yield code, "Generating new code..."
|
| 64 |
new_code = generate_c_code(instruction)
|
| 65 |
yield new_code, "Code generation successful. New code is in the editor."
|
| 66 |
return
|
| 67 |
|
| 68 |
-
# 그 외의 경우, 코드 에디터가 비어있으면 에러
|
| 69 |
if not code:
|
| 70 |
yield code, "Error: Code editor is empty. Please provide code to work with, or ask to 'generate' new code."
|
| 71 |
return
|
|
@@ -75,14 +88,14 @@ def handle_instruction(code: str, instruction: str):
|
|
| 75 |
result = compile_and_run_c_code(code)
|
| 76 |
yield code, result
|
| 77 |
|
| 78 |
-
else:
|
| 79 |
yield code, f"Analyzing code with instruction: '{instruction}'..."
|
| 80 |
analysis_result = analyze_and_refactor_code(code, instruction)
|
| 81 |
yield code, analysis_result
|
| 82 |
|
| 83 |
-
# --- 4. Gradio UI 구성
|
| 84 |
with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
|
| 85 |
-
gr.Markdown("# 💻 The C-Codestral IDE Agent")
|
| 86 |
|
| 87 |
with gr.Tabs():
|
| 88 |
with gr.TabItem("👨💻 IDE"):
|
|
@@ -90,19 +103,11 @@ with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="b
|
|
| 90 |
with gr.Column(scale=2):
|
| 91 |
code_editor = gr.Code(label="C Code Editor", language="c", lines=25, interactive=True)
|
| 92 |
with gr.Column(scale=1):
|
| 93 |
-
instruction_box = gr.Textbox(
|
| 94 |
-
label="Instruction",
|
| 95 |
-
placeholder="e.g., 'Compile and run', 'Find bugs', 'Generate a factorial function'...",
|
| 96 |
-
lines=3
|
| 97 |
-
)
|
| 98 |
execute_btn = gr.Button("Execute Instruction", variant="primary")
|
| 99 |
output_box = gr.Textbox(label="Output / Console", lines=15, interactive=False, show_copy_button=True)
|
| 100 |
|
| 101 |
-
execute_btn.click(
|
| 102 |
-
fn=handle_instruction,
|
| 103 |
-
inputs=[code_editor, instruction_box],
|
| 104 |
-
outputs=[code_editor, output_box]
|
| 105 |
-
)
|
| 106 |
|
| 107 |
with gr.TabItem("🛠️ MCP Tools API"):
|
| 108 |
gr.Markdown("## Available MCP Tools\nThese APIs can be used by any MCP-compliant client.")
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import subprocess
|
| 4 |
+
import requests # mistralai 대신 requests 사용
|
| 5 |
+
import json
|
| 6 |
|
| 7 |
# --- 1. 환경 설정 ---
|
| 8 |
API_KEY = os.environ.get("MISTRAL_API_KEY")
|
| 9 |
+
CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions" # 직접 호출할 엔드포인트
|
| 10 |
+
HEADERS = {
|
| 11 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 12 |
+
"Content-Type": "application/json"
|
| 13 |
+
}
|
| 14 |
|
| 15 |
+
if not API_KEY:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
print("FATAL: MISTRAL_API_KEY is not set in Space Secrets.")
|
| 17 |
|
| 18 |
+
# --- 2. 백엔드 핵심 기능 함수 (requests 사용) ---
|
| 19 |
+
def call_mistral_api(messages):
|
| 20 |
+
if not API_KEY: return "Error: MISTRAL_API_KEY is not configured."
|
| 21 |
+
|
| 22 |
+
data = {
|
| 23 |
+
"model": "codestral-latest",
|
| 24 |
+
"messages": messages
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
response = requests.post(CODESTRAL_ENDPOINT, headers=HEADERS, data=json.dumps(data), timeout=30)
|
| 29 |
+
response.raise_for_status() # 2xx가 아닌 상태 코드에 대해 에러 발생
|
| 30 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 31 |
+
except requests.exceptions.RequestException as e:
|
| 32 |
+
return f"API Call Error: {e}"
|
| 33 |
+
|
| 34 |
def generate_c_code(description: str) -> str:
|
|
|
|
| 35 |
prompt = f"You are a C programming expert. Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code, without any markdown formatting or explanations."
|
| 36 |
messages = [{"role": "user", "content": prompt}]
|
| 37 |
+
code = call_mistral_api(messages)
|
| 38 |
+
|
| 39 |
+
if "```c" in code:
|
| 40 |
+
code = code.split("```c")[1].split("```")[0].strip()
|
| 41 |
+
elif "```" in code:
|
| 42 |
+
code = code.split("```")[1].split("```")[0].strip()
|
| 43 |
+
return code
|
| 44 |
|
| 45 |
def compile_and_run_c_code(code: str) -> str:
|
| 46 |
try:
|
|
|
|
| 54 |
except Exception as e: return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
|
| 55 |
|
| 56 |
def analyze_and_refactor_code(code: str, instruction: str) -> str:
|
|
|
|
| 57 |
prompt = f"""You are a senior C code reviewer. Analyze the following C code based on the user's instruction.
|
| 58 |
Provide a clear, concise response. If refactoring, provide the complete improved code in a C code block.
|
| 59 |
|
|
|
|
| 64 |
{code}
|
| 65 |
```"""
|
| 66 |
messages = [{"role": "user", "content": prompt}]
|
| 67 |
+
return call_mistral_api(messages)
|
|
|
|
| 68 |
|
| 69 |
# --- 3. 메인 이벤트 핸들러 ---
|
| 70 |
def handle_instruction(code: str, instruction: str):
|
|
|
|
| 73 |
|
| 74 |
lower_instruction = instruction.lower()
|
| 75 |
|
|
|
|
| 76 |
if "generate" in lower_instruction or "create" in lower_instruction or "만들어줘" in lower_instruction:
|
| 77 |
yield code, "Generating new code..."
|
| 78 |
new_code = generate_c_code(instruction)
|
| 79 |
yield new_code, "Code generation successful. New code is in the editor."
|
| 80 |
return
|
| 81 |
|
|
|
|
| 82 |
if not code:
|
| 83 |
yield code, "Error: Code editor is empty. Please provide code to work with, or ask to 'generate' new code."
|
| 84 |
return
|
|
|
|
| 88 |
result = compile_and_run_c_code(code)
|
| 89 |
yield code, result
|
| 90 |
|
| 91 |
+
else:
|
| 92 |
yield code, f"Analyzing code with instruction: '{instruction}'..."
|
| 93 |
analysis_result = analyze_and_refactor_code(code, instruction)
|
| 94 |
yield code, analysis_result
|
| 95 |
|
| 96 |
+
# --- 4. Gradio UI 구성 ---
|
| 97 |
with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
|
| 98 |
+
gr.Markdown("# 💻 The C-Codestral IDE Agent (Library-Free)")
|
| 99 |
|
| 100 |
with gr.Tabs():
|
| 101 |
with gr.TabItem("👨💻 IDE"):
|
|
|
|
| 103 |
with gr.Column(scale=2):
|
| 104 |
code_editor = gr.Code(label="C Code Editor", language="c", lines=25, interactive=True)
|
| 105 |
with gr.Column(scale=1):
|
| 106 |
+
instruction_box = gr.Textbox(label="Instruction", placeholder="e.g., 'Compile and run', 'Find bugs', 'Generate a factorial function'...", lines=3)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
execute_btn = gr.Button("Execute Instruction", variant="primary")
|
| 108 |
output_box = gr.Textbox(label="Output / Console", lines=15, interactive=False, show_copy_button=True)
|
| 109 |
|
| 110 |
+
execute_btn.click(fn=handle_instruction, inputs=[code_editor, instruction_box], outputs=[code_editor, output_box])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
with gr.TabItem("🛠️ MCP Tools API"):
|
| 113 |
gr.Markdown("## Available MCP Tools\nThese APIs can be used by any MCP-compliant client.")
|