Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -7,154 +7,163 @@ import re
|
|
7 |
import time
|
8 |
|
9 |
# --- 1. 환경 설정 및 강화된 API 호출 함수 ---
|
10 |
-
# MISTRAL_API_KEY를 Space Secrets에 설정해야 합니다.
|
11 |
MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY")
|
12 |
CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions"
|
13 |
|
14 |
-
# 시스템 프롬프트를 활용하기 위해 API 호출 함수 수정
|
15 |
def call_mistral_api(system_prompt: str, user_prompt: str):
|
16 |
-
"""향상된 Mistral API 호출
|
17 |
if not MISTRAL_API_KEY:
|
18 |
-
# UI에 직접 에러를 표시하는 것이 더 나은 사용자 경험을 제공합니다.
|
19 |
raise gr.Error("MISTRAL_API_KEY is not set. Please add it to your Space Secrets.")
|
20 |
|
21 |
headers = {"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"}
|
22 |
-
messages = [
|
23 |
-
{"role": "system", "content": system_prompt},
|
24 |
-
{"role": "user", "content": user_prompt}
|
25 |
-
]
|
26 |
data = {"model": "codestral-latest", "messages": messages}
|
27 |
|
28 |
try:
|
29 |
-
response = requests.post(CODESTRAL_ENDPOINT, headers=headers, data=json.dumps(data), timeout=
|
30 |
response.raise_for_status()
|
31 |
return response.json()["choices"][0]["message"]["content"]
|
32 |
except requests.exceptions.RequestException as e:
|
33 |
-
|
34 |
|
35 |
# --- 2. 백엔드 핵심 기능 (안정성 강화) ---
|
36 |
def parse_code_from_response(response_text: str) -> str | None:
|
37 |
-
"""
|
38 |
-
모델의 응답에서 C 코드 블록을 파싱합니다.
|
39 |
-
안정성을 위해 ```c 태그가 없는 경우에도 대비합니다.
|
40 |
-
"""
|
41 |
match = re.search(r'```(?:c)?\n(.*?)\n```', response_text, re.DOTALL)
|
42 |
-
if match:
|
43 |
-
|
44 |
-
#
|
45 |
-
elif response_text.strip().startswith("#include") and response_text.strip().endswith("}"):
|
46 |
return response_text.strip()
|
47 |
return None
|
48 |
|
49 |
-
# --- MCP 탭과 에이전트가 모두 사용할 전역 함수 (프롬프트 최적화) ---
|
50 |
def generate_c_code(description: str) -> str:
|
51 |
-
system_prompt = "You are an expert C code generator
|
52 |
-
user_prompt = f"Generate C code for
|
53 |
response = call_mistral_api(system_prompt, user_prompt)
|
54 |
return parse_code_from_response(response) or f"// Failed to parse code from response:\n{response}"
|
55 |
|
56 |
def compile_and_run_c_code(code: str) -> str:
|
57 |
-
"""
|
58 |
-
if not code
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
return f"--- COMPILATION FAILED ---\n{compile_proc.stderr}"
|
67 |
-
|
68 |
-
run_proc = subprocess.run(["./main.out"], capture_output=True, text=True, timeout=15)
|
69 |
-
if run_proc.returncode != 0:
|
70 |
-
return f"--- RUNTIME ERROR ---\n{run_proc.stderr}"
|
71 |
-
|
72 |
-
output = run_proc.stdout
|
73 |
-
return f"--- EXECUTION SUCCEEDED ---\n{output}" if output.strip() else "--- EXECUTION SUCCEEDED ---\n(No output was produced)"
|
74 |
-
except Exception as e:
|
75 |
-
return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
|
76 |
|
77 |
def analyze_and_refactor_code(code: str, instruction: str) -> str:
|
78 |
-
system_prompt = "You are a world-class C code reviewer
|
79 |
-
user_prompt = f"Instruction: '{instruction}'\n\nC Code
|
80 |
return call_mistral_api(system_prompt, user_prompt)
|
81 |
|
82 |
-
#
|
83 |
-
def
|
84 |
-
|
85 |
-
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
-
|
|
|
89 |
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()]
|
90 |
-
|
91 |
current_code = initial_code
|
92 |
-
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
for i, task in enumerate(tasks)
|
97 |
-
|
98 |
-
|
99 |
-
yield current_code, "\n".join(output_log)
|
100 |
time.sleep(1)
|
101 |
|
102 |
-
#
|
103 |
for i, task in enumerate(tasks):
|
|
|
|
|
|
|
|
|
104 |
lower_task = task.lower()
|
105 |
|
106 |
-
# ⭐️ 에이전트의 '생각'
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
|
|
|
|
|
|
114 |
elif "compile" in lower_task or "run" in lower_task or "실행" in lower_task:
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
else:
|
139 |
-
output_log.append(f"❌ Generation failed: {result}")
|
140 |
-
elif action_func == compile_and_run_c_code:
|
141 |
-
output_log.append(f"💻 Result:\n{result}")
|
142 |
-
elif action_func == analyze_and_refactor_code:
|
143 |
-
refactored_code = parse_code_from_response(result)
|
144 |
if refactored_code:
|
145 |
current_code = refactored_code
|
146 |
-
|
147 |
-
|
148 |
|
149 |
-
|
|
|
150 |
|
151 |
-
|
152 |
-
yield current_code, "\n".join(
|
153 |
|
154 |
-
|
155 |
-
# --- 4. 통합된 Gradio UI (변경 없음) ---
|
156 |
with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
|
157 |
-
gr.Markdown("#
|
158 |
|
159 |
with gr.Tabs():
|
160 |
with gr.TabItem("👨💻 IDE Agent"):
|
@@ -163,17 +172,19 @@ with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="b
|
|
163 |
code_editor = gr.Code(label="C Code Editor", language="c", lines=28, interactive=True, value='#include <stdio.h>\n\nint main() {\n printf("Hello, World!\\n");\n return 0;\n}')
|
164 |
|
165 |
with gr.Column(scale=1):
|
166 |
-
instruction_box = gr.Textbox(label="Instruction", placeholder="e.g., 'Refactor this code
|
167 |
execute_btn = gr.Button("Execute", variant="primary", size="lg")
|
168 |
-
|
|
|
169 |
|
170 |
execute_btn.click(
|
171 |
-
fn=
|
172 |
inputs=[code_editor, instruction_box],
|
173 |
outputs=[code_editor, output_box]
|
174 |
)
|
175 |
|
176 |
with gr.TabItem("🛠️ MCP Tools API"):
|
|
|
177 |
gr.Markdown("## Available MCP Tools for other Agents\nThese APIs are the building blocks of our IDE agent.")
|
178 |
with gr.Accordion("Tool: Generate C Code", open=False):
|
179 |
gr.Interface(fn=generate_c_code, inputs="text", outputs=gr.Code(language="c", label="Generated C Code"))
|
@@ -183,8 +194,4 @@ with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="b
|
|
183 |
gr.Interface(fn=analyze_and_refactor_code, inputs=[gr.Code(language="c", label="Code to Analyze"), gr.Textbox(label="Instruction")], outputs=gr.Markdown())
|
184 |
|
185 |
if __name__ == "__main__":
|
186 |
-
if not MISTRAL_API_KEY:
|
187 |
-
print("WARNING: MISTRAL_API_KEY is not set. The application will not work correctly.")
|
188 |
-
# 로컬 실행 시에는 키가 없어도 UI는 띄울 수 있도록 처리
|
189 |
-
# demo.launch()가 실패하지 않도록 API 키 확인은 함수 내부에서 gr.Error로 처리
|
190 |
demo.queue().launch()
|
|
|
7 |
import time
|
8 |
|
9 |
# --- 1. 환경 설정 및 강화된 API 호출 함수 ---
|
|
|
10 |
MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY")
|
11 |
CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions"
|
12 |
|
|
|
13 |
def call_mistral_api(system_prompt: str, user_prompt: str):
|
14 |
+
"""향상된 Mistral API 호출 함수"""
|
15 |
if not MISTRAL_API_KEY:
|
|
|
16 |
raise gr.Error("MISTRAL_API_KEY is not set. Please add it to your Space Secrets.")
|
17 |
|
18 |
headers = {"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"}
|
19 |
+
messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}]
|
|
|
|
|
|
|
20 |
data = {"model": "codestral-latest", "messages": messages}
|
21 |
|
22 |
try:
|
23 |
+
response = requests.post(CODESTRAL_ENDPOINT, headers=headers, data=json.dumps(data), timeout=60)
|
24 |
response.raise_for_status()
|
25 |
return response.json()["choices"][0]["message"]["content"]
|
26 |
except requests.exceptions.RequestException as e:
|
27 |
+
raise gr.Error(f"API Call Error: {e}")
|
28 |
|
29 |
# --- 2. 백엔드 핵심 기능 (안정성 강화) ---
|
30 |
def parse_code_from_response(response_text: str) -> str | None:
|
31 |
+
"""C 코드 블록을 파싱하는 안정적인 함수"""
|
|
|
|
|
|
|
32 |
match = re.search(r'```(?:c)?\n(.*?)\n```', response_text, re.DOTALL)
|
33 |
+
if match: return match.group(1).strip()
|
34 |
+
# 비상시 순수 코드 응답 처리
|
35 |
+
if response_text.strip().startswith("#include") and response_text.strip().endswith("}"):
|
|
|
36 |
return response_text.strip()
|
37 |
return None
|
38 |
|
|
|
39 |
def generate_c_code(description: str) -> str:
|
40 |
+
system_prompt = "You are an expert C code generator..." # (이전과 동일)
|
41 |
+
user_prompt = f"Generate C code for: '{description}'"
|
42 |
response = call_mistral_api(system_prompt, user_prompt)
|
43 |
return parse_code_from_response(response) or f"// Failed to parse code from response:\n{response}"
|
44 |
|
45 |
def compile_and_run_c_code(code: str) -> str:
|
46 |
+
"""컴파일 및 실행 함수"""
|
47 |
+
if not code.strip(): return "--- SYSTEM ERROR ---\nCode is empty."
|
48 |
+
with open("main.c", "w", encoding='utf-8') as f: f.write(code)
|
49 |
+
compile_proc = subprocess.run(["gcc", "main.c", "-o", "main.out", "-lm", "-w"], capture_output=True, text=True, timeout=15)
|
50 |
+
if compile_proc.returncode != 0: return f"--- COMPILATION FAILED ---\n{compile_proc.stderr}"
|
51 |
+
run_proc = subprocess.run(["./main.out"], capture_output=True, text=True, timeout=15)
|
52 |
+
if run_proc.returncode != 0: return f"--- RUNTIME ERROR ---\n{run_proc.stderr}"
|
53 |
+
output = run_proc.stdout
|
54 |
+
return f"--- EXECUTION SUCCEEDED ---\n{output}" if output.strip() else "--- EXECUTION SUCCEEDED ---\n(No output)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
def analyze_and_refactor_code(code: str, instruction: str) -> str:
|
57 |
+
system_prompt = "You are a world-class C code reviewer..." # (이전과 동일)
|
58 |
+
user_prompt = f"Instruction: '{instruction}'\n\nC Code:\n```c\n{code}\n```"
|
59 |
return call_mistral_api(system_prompt, user_prompt)
|
60 |
|
61 |
+
# ⭐️ 새로운 기능: 외부 MCP 툴을 사용하는 클라이언트 함수
|
62 |
+
def call_external_mcp_tool(tool_url: str, code: str, instruction: str) -> str:
|
63 |
+
"""다른 Gradio Space MCP 툴을 API로 호출하는 함수"""
|
64 |
+
# Gradio 클라이언트를 사용하여 외부 API 호출 (gradio_client 설치 필요)
|
65 |
+
from gradio_client import Client
|
66 |
+
try:
|
67 |
+
client = Client(tool_url)
|
68 |
+
# 외부 툴의 API 엔드포인트와 파라미터 이름에 맞춰야 함
|
69 |
+
# 예시: predict(code_to_analyze=code, user_instruction=instruction)
|
70 |
+
result = client.predict(code, instruction, api_name="/predict") # api_name은 외부 툴에 따라 다름
|
71 |
+
return f"--- EXTERNAL TOOL SUCCEEDED ---\n{result}"
|
72 |
+
except Exception as e:
|
73 |
+
return f"--- EXTERNAL TOOL FAILED ---\nCould not call tool at {tool_url}. Error: {e}"
|
74 |
|
75 |
+
# --- 3. 1등을 위한 지능형 에이전트 로직 (최종 버전) ---
|
76 |
+
def ultimate_agent_ide(initial_code: str, full_instruction: str):
|
77 |
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()]
|
|
|
78 |
current_code = initial_code
|
79 |
+
log = []
|
80 |
|
81 |
+
# Step 1: 계획 수립
|
82 |
+
log.append("### 📝 Agent's Plan")
|
83 |
+
plan = "".join([f"\n{i+1}. {task}" for i, task in enumerate(tasks)])
|
84 |
+
log.append(plan)
|
85 |
+
yield current_code, "\n".join(log)
|
|
|
86 |
time.sleep(1)
|
87 |
|
88 |
+
# Step 2: 계획 실행
|
89 |
for i, task in enumerate(tasks):
|
90 |
+
log.append(f"\n<details><summary><b>▶ Step {i+1}: {task}</b></summary>\n")
|
91 |
+
yield current_code, "\n".join(log)
|
92 |
+
time.sleep(0.5)
|
93 |
+
|
94 |
lower_task = task.lower()
|
95 |
|
96 |
+
# ⭐️ 에이전트의 '생각'과 '행동'
|
97 |
+
if "generate" in lower_task or "create" in lower_task or "만들어" in lower_task:
|
98 |
+
log.append("🧠 **Thought:** The user wants new code. Using `generate_c_code` tool.")
|
99 |
+
yield current_code, "\n".join(log)
|
100 |
+
new_code = generate_c_code(task)
|
101 |
+
if new_code and not new_code.startswith("//"):
|
102 |
+
current_code = new_code
|
103 |
+
log.append("\n✅ **Action Result:** Code generated and updated in the editor.")
|
104 |
+
else:
|
105 |
+
log.append(f"\n❌ **Action Result:** Generation failed. {new_code}")
|
106 |
+
|
107 |
elif "compile" in lower_task or "run" in lower_task or "실행" in lower_task:
|
108 |
+
log.append("🧠 **Thought:** The user wants to compile and run. Using `compile_and_run_c_code` tool.")
|
109 |
+
yield current_code, "\n".join(log)
|
110 |
+
result = compile_and_run_c_code(current_code)
|
111 |
+
log.append(f"\n💻 **Action Result:**\n```\n{result}\n```")
|
112 |
+
|
113 |
+
# ⭐️⭐️ 자가 수정 (SELF-CORRECTION) 로직 ⭐️⭐️
|
114 |
+
if "COMPILATION FAILED" in result:
|
115 |
+
log.append("\n\n🧠 **Thought:** Compilation failed. I will try to fix the code myself.")
|
116 |
+
yield current_code, "\n".join(log)
|
117 |
+
time.sleep(1)
|
118 |
+
|
119 |
+
error_message = result.split("--- COMPILATION FAILED ---")[1]
|
120 |
+
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."
|
121 |
+
|
122 |
+
log.append("\n🛠️ **Self-Correction:** Asking the LLM to fix the error...")
|
123 |
+
yield current_code, "\n".join(log)
|
124 |
+
|
125 |
+
fixed_code_response = analyze_and_refactor_code(current_code, fix_instruction)
|
126 |
+
fixed_code = parse_code_from_response(fixed_code_response)
|
127 |
+
|
128 |
+
if fixed_code:
|
129 |
+
current_code = fixed_code
|
130 |
+
log.append("\n✅ **Self-Correction Result:** A potential fix has been applied to the code editor. Please try compiling again.")
|
131 |
+
else:
|
132 |
+
log.append("\n❌ **Self-Correction Result:** Failed to automatically fix the code.")
|
133 |
+
|
134 |
+
# ⭐️⭐️ 외부 MCP 툴 사용 예시 ⭐️⭐️
|
135 |
+
elif "security" in lower_task or "보안" in lower_task:
|
136 |
+
log.append("🧠 **Thought:** The user wants a security analysis. I will use an external MCP tool for this.")
|
137 |
+
yield current_code, "\n".join(log)
|
138 |
+
# 이 URL은 예시이며, 실제 작동하는 보안 분석 MCP Space가 있다면 그 주소를 넣어야 합니다.
|
139 |
+
# 해커톤 제출 시, 직접 간단한 보안분석 툴을 하나 더 만들거나, 다른 참가자의 툴을 사용하는 모습을 보여주면 최고입니다.
|
140 |
+
external_tool_url = "user-provided-security-tool-space-url"
|
141 |
+
log.append(f"\n🔌 **Action:** Calling external tool at `{external_tool_url}`...")
|
142 |
+
yield current_code, "\n".join(log)
|
143 |
+
|
144 |
+
# 실제로는 instruction에서 URL을 파싱해야 하지만, 여기서는 하드코딩으로 예시를 보여줍니다.
|
145 |
+
security_result = call_external_mcp_tool(external_tool_url, current_code, task)
|
146 |
+
log.append(f"\n🛡️ **Action Result:**\n```\n{security_result}\n```")
|
147 |
|
148 |
+
else:
|
149 |
+
log.append("🧠 **Thought:** The user wants to analyze or refactor. Using `analyze_and_refactor_code` tool.")
|
150 |
+
yield current_code, "\n".join(log)
|
151 |
+
analysis_result = analyze_and_refactor_code(current_code, task)
|
152 |
+
refactored_code = parse_code_from_response(analysis_result)
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
if refactored_code:
|
154 |
current_code = refactored_code
|
155 |
+
log.append("\n✅ **Action Result:** Code refactored and updated in the editor.")
|
156 |
+
log.append(f"\n🔎 **Analysis Result:**\n{analysis_result}")
|
157 |
|
158 |
+
log.append("</details>")
|
159 |
+
yield current_code, "\n".join(log)
|
160 |
|
161 |
+
log.append("\n\n--- All tasks complete. ---")
|
162 |
+
yield current_code, "\n".join(log)
|
163 |
|
164 |
+
# --- 4. 통합된 Gradio UI (출력 컴포넌트를 Markdown으로 변경) ---
|
|
|
165 |
with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
|
166 |
+
gr.Markdown("# 🏆 The Ultimate C-Codestral IDE Agent 🏆")
|
167 |
|
168 |
with gr.Tabs():
|
169 |
with gr.TabItem("👨💻 IDE Agent"):
|
|
|
172 |
code_editor = gr.Code(label="C Code Editor", language="c", lines=28, interactive=True, value='#include <stdio.h>\n\nint main() {\n printf("Hello, World!\\n");\n return 0;\n}')
|
173 |
|
174 |
with gr.Column(scale=1):
|
175 |
+
instruction_box = gr.Textbox(label="Instruction", placeholder="e.g., 'Refactor this code, then compile it, then check security'", lines=4)
|
176 |
execute_btn = gr.Button("Execute", variant="primary", size="lg")
|
177 |
+
# 출력을 Markdown으로 변경하여 풍부한 UI를 제공
|
178 |
+
output_box = gr.Markdown(label="Console / Output")
|
179 |
|
180 |
execute_btn.click(
|
181 |
+
fn=ultimate_agent_ide,
|
182 |
inputs=[code_editor, instruction_box],
|
183 |
outputs=[code_editor, output_box]
|
184 |
)
|
185 |
|
186 |
with gr.TabItem("🛠️ MCP Tools API"):
|
187 |
+
# MCP 탭은 이전과 동일하게 유지
|
188 |
gr.Markdown("## Available MCP Tools for other Agents\nThese APIs are the building blocks of our IDE agent.")
|
189 |
with gr.Accordion("Tool: Generate C Code", open=False):
|
190 |
gr.Interface(fn=generate_c_code, inputs="text", outputs=gr.Code(language="c", label="Generated C Code"))
|
|
|
194 |
gr.Interface(fn=analyze_and_refactor_code, inputs=[gr.Code(language="c", label="Code to Analyze"), gr.Textbox(label="Instruction")], outputs=gr.Markdown())
|
195 |
|
196 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
197 |
demo.queue().launch()
|