Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,106 +6,164 @@ import json
|
|
6 |
import re
|
7 |
import time
|
8 |
|
9 |
-
# --- 1. 환경 설정 및 API 호출 함수 ---
|
10 |
-
|
11 |
CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions"
|
12 |
-
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
19 |
data = {"model": "codestral-latest", "messages": messages}
|
|
|
20 |
try:
|
21 |
-
response = requests.post(CODESTRAL_ENDPOINT, headers=
|
22 |
response.raise_for_status()
|
23 |
return response.json()["choices"][0]["message"]["content"]
|
24 |
except requests.exceptions.RequestException as e:
|
25 |
-
|
26 |
|
27 |
-
# --- 2. 백엔드 핵심 기능 (
|
28 |
def parse_code_from_response(response_text: str) -> str | None:
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
|
|
|
|
32 |
return None
|
33 |
|
34 |
-
# --- MCP 탭과 에이전트가 모두 사용할 전역 함수로 정의 ---
|
35 |
def generate_c_code(description: str) -> str:
|
36 |
-
|
37 |
-
|
|
|
|
|
38 |
|
39 |
def compile_and_run_c_code(code: str) -> str:
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
def analyze_and_refactor_code(code: str, instruction: str) -> str:
|
51 |
-
prompt = f"You are a senior C code reviewer. Fulfill this instruction: '{instruction}'. If you refactor or change the code, YOU MUST provide the complete, new code in a ```c code block. \n\nC Code to Analyze:\n```c\n{code}\n```"
|
52 |
-
return call_mistral_api([{"role": "user", "content": prompt}])
|
53 |
-
|
54 |
-
# --- 3. 진짜 '지능형' 에이전트 로직 ---
|
55 |
-
def intelligent_agent_ide(initial_code: str, full_instruction: str):
|
56 |
-
if not full_instruction:
|
57 |
-
yield initial_code, "Error: Instruction cannot be empty."
|
58 |
-
return
|
59 |
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
current_code = initial_code
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
time.sleep(0.5)
|
71 |
|
72 |
-
|
73 |
-
new_code = generate_c_code(task)
|
74 |
-
current_code = new_code if new_code and "Error" not in new_code else current_code
|
75 |
-
output_log.append(f"✅ Code generated and updated in the editor.")
|
76 |
-
yield current_code, "\n".join(output_log)
|
77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
elif "compile" in lower_task or "run" in lower_task or "실행" in lower_task:
|
79 |
-
|
80 |
-
|
81 |
-
yield current_code, "\n".join(output_log)
|
82 |
-
break
|
83 |
result = compile_and_run_c_code(current_code)
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
else:
|
88 |
-
|
89 |
-
|
90 |
-
yield current_code, "\n".join(output_log)
|
91 |
-
break
|
92 |
analysis_result = analyze_and_refactor_code(current_code, task)
|
93 |
-
|
94 |
refactored_code = parse_code_from_response(analysis_result)
|
95 |
if refactored_code:
|
96 |
current_code = refactored_code
|
97 |
-
|
98 |
-
|
99 |
-
|
|
|
|
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
output_log.append("\n--- All tasks complete. ---")
|
104 |
-
yield current_code, "\n".join(output_log)
|
105 |
|
106 |
-
# --- 4. 통합된 Gradio UI ---
|
107 |
with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
|
108 |
-
gr.Markdown("#
|
109 |
|
110 |
with gr.Tabs():
|
111 |
with gr.TabItem("👨💻 IDE Agent"):
|
@@ -114,24 +172,26 @@ with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="b
|
|
114 |
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}')
|
115 |
|
116 |
with gr.Column(scale=1):
|
117 |
-
instruction_box = gr.Textbox(label="Instruction", placeholder="e.g., 'Refactor this code
|
118 |
execute_btn = gr.Button("Execute", variant="primary", size="lg")
|
119 |
-
|
|
|
120 |
|
121 |
execute_btn.click(
|
122 |
-
fn=
|
123 |
inputs=[code_editor, instruction_box],
|
124 |
outputs=[code_editor, output_box]
|
125 |
)
|
126 |
|
127 |
with gr.TabItem("🛠️ MCP Tools API"):
|
|
|
128 |
gr.Markdown("## Available MCP Tools for other Agents\nThese APIs are the building blocks of our IDE agent.")
|
129 |
with gr.Accordion("Tool: Generate C Code", open=False):
|
130 |
gr.Interface(fn=generate_c_code, inputs="text", outputs=gr.Code(language="c", label="Generated C Code"))
|
131 |
with gr.Accordion("Tool: Compile & Run C Code", open=False):
|
132 |
gr.Interface(fn=compile_and_run_c_code, inputs=gr.Code(language="c"), outputs=gr.Textbox(label="Output"))
|
133 |
with gr.Accordion("Tool: Analyze & Refactor C Code", open=False):
|
134 |
-
gr.Interface(fn=analyze_and_refactor_code, inputs=[gr.Code(language="c"), "
|
135 |
|
136 |
if __name__ == "__main__":
|
137 |
demo.queue().launch()
|
|
|
6 |
import re
|
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"))
|
191 |
with gr.Accordion("Tool: Compile & Run C Code", open=False):
|
192 |
gr.Interface(fn=compile_and_run_c_code, inputs=gr.Code(language="c"), outputs=gr.Textbox(label="Output"))
|
193 |
with gr.Accordion("Tool: Analyze & Refactor C Code", open=False):
|
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()
|