kimhyunwoo commited on
Commit
667d6ee
·
verified ·
1 Parent(s): 14f1277

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -57
app.py CHANGED
@@ -6,104 +6,153 @@ import json
6
  import re
7
  import time
8
 
9
- # --- 1. 환경 설정 및 API 호출 함수 ---
10
- API_KEY = os.environ.get("MISTRAL_API_KEY")
 
11
  CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1/chat/completions"
12
- HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
13
 
14
- if not API_KEY:
15
- print("FATAL: MISTRAL_API_KEY is not set in Space Secrets.")
16
-
17
- def call_mistral_api(messages):
18
- if not API_KEY: return "Error: MISTRAL_API_KEY is not configured."
 
 
 
 
 
 
 
19
  data = {"model": "codestral-latest", "messages": messages}
 
20
  try:
21
- response = requests.post(CODESTRAL_ENDPOINT, headers=HEADERS, data=json.dumps(data), timeout=45)
22
  response.raise_for_status()
23
  return response.json()["choices"][0]["message"]["content"]
24
  except requests.exceptions.RequestException as e:
25
  return f"API Call Error: {e}"
26
 
27
- # --- 2. 백엔드 핵심 기능 (파서 포함) ---
28
  def parse_code_from_response(response_text: str) -> str | None:
29
- match = re.search(r'```c\n(.*?)\n```', response_text, re.DOTALL)
 
 
 
 
30
  if match:
31
  return match.group(1).strip()
 
 
 
32
  return None
33
 
34
- # --- MCP 탭과 에이전트가 모두 사용할 전역 함수로 정의 ---
35
  def generate_c_code(description: str) -> str:
36
- prompt = f"Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code, without markdown or explanations."
37
- return call_mistral_api([{"role": "user", "content": prompt}])
 
 
38
 
39
  def compile_and_run_c_code(code: str) -> str:
 
 
 
40
  try:
41
  with open("main.c", "w", encoding='utf-8') as f: f.write(code)
 
 
42
  compile_proc = subprocess.run(["gcc", "main.c", "-o", "main.out", "-lm", "-w"], capture_output=True, text=True, timeout=15)
43
- if compile_proc.returncode != 0: return f"--- COMPILATION FAILED ---\n{compile_proc.stderr}"
 
 
44
  run_proc = subprocess.run(["./main.out"], capture_output=True, text=True, timeout=15)
45
- if run_proc.returncode != 0: return f"--- RUNTIME ERROR ---\n{run_proc.stderr}"
 
 
46
  output = run_proc.stdout
47
  return f"--- EXECUTION SUCCEEDED ---\n{output}" if output.strip() else "--- EXECUTION SUCCEEDED ---\n(No output was produced)"
48
- except Exception as e: return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
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
- tasks = [task.strip() for task in re.split(r'\s+and\s+|\s*,\s*then\s*|\s*그리고\s*', full_instruction, flags=re.IGNORECASE)]
 
61
 
62
  current_code = initial_code
63
  output_log = []
64
- step = 1
65
 
66
- for task in tasks:
67
- lower_task = task.lower()
68
- output_log.append(f"▶ Step {step}: Executing '{task}'...")
69
- yield current_code, "\n".join(output_log)
70
- time.sleep(0.5)
 
 
71
 
72
- if "generate" in lower_task or "create" in lower_task or "만들어줘" in lower_task:
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
- if not current_code:
80
- output_log.append("❌ Error: Code is empty. Cannot compile.")
81
- yield current_code, "\n".join(output_log)
82
- break
83
- result = compile_and_run_c_code(current_code)
84
- output_log.append(result)
85
- yield current_code, "\n".join(output_log)
 
 
 
 
86
 
 
 
 
87
  else:
88
- if not current_code:
89
- output_log.append("❌ Error: Code is empty. Cannot analyze.")
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
- output_log.append(f"✅ Code refactored and updated in the editor.")
98
- output_log.append(f"🔎 Analysis Result:\n{analysis_result}")
99
- yield current_code, "\n".join(output_log)
 
100
 
101
- step += 1
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("# 💻 The True C-Codestral IDE Agent")
109
 
@@ -131,7 +180,11 @@ with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="b
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"), "text"], outputs=gr.Markdown())
135
 
136
  if __name__ == "__main__":
 
 
 
 
137
  demo.queue().launch()
 
6
  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=45)
30
  response.raise_for_status()
31
  return response.json()["choices"][0]["message"]["content"]
32
  except requests.exceptions.RequestException as e:
33
  return f"API Call Error: {e}"
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
  return match.group(1).strip()
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. Your task is to generate complete, compilable C code based on the user's request. Output ONLY the raw C code within a ```c block, without any additional explanations."
52
+ user_prompt = f"Generate C code for the following request: '{description}'"
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
+ """C 코드를 컴파일하고 실행하는 함수. 오류 메시지를 더 명확하게 개선."""
58
+ if not code or not isinstance(code, str) or not code.strip():
59
+ return "--- SYSTEM ERROR ---\nCode is empty or invalid. Cannot process."
60
  try:
61
  with open("main.c", "w", encoding='utf-8') as f: f.write(code)
62
+
63
+ # -lm(수학 라이브러리), -w(경고 무시) 옵션 추가
64
  compile_proc = subprocess.run(["gcc", "main.c", "-o", "main.out", "-lm", "-w"], capture_output=True, text=True, timeout=15)
65
+ if compile_proc.returncode != 0:
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 and refactoring expert. Analyze the user-provided C code based on their instruction. If you refactor or change the code, YOU MUST provide the complete, new C code in a ```c block. Otherwise, provide your analysis as plain text."
79
+ user_prompt = f"Instruction: '{instruction}'\n\nC Code to Analyze:\n```c\n{code}\n```"
80
+ return call_mistral_api(system_prompt, user_prompt)
81
 
82
+ # --- 3. 진짜 '지능형' 에이전트 로직 (개선된 버전) ---
83
  def intelligent_agent_ide(initial_code: str, full_instruction: str):
84
+ if not full_instruction.strip():
85
+ yield initial_code, "Error: Instruction cannot be empty."
86
  return
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
  output_log = []
 
93
 
94
+ # ⭐️ Step 1: 실행 계획 수립 및 제시
95
+ plan_log = ["📝 Agent's Plan:"]
96
+ for i, task in enumerate(tasks):
97
+ plan_log.append(f"{i+1}. {task}")
98
+ output_log.extend(plan_log)
99
+ yield current_code, "\n".join(output_log)
100
+ time.sleep(1)
101
 
102
+ # ⭐️ Step 2: 계획에 따라 작업 순차 실행
103
+ for i, task in enumerate(tasks):
104
+ lower_task = task.lower()
 
 
105
 
106
+ # ⭐️ 에이전트의 '생각' 과정을 명시적으로 보여줌
107
+ thought = ""
108
+ action_func = None
109
+ action_arg = task
110
+
111
+ if "generate" in lower_task or "create" in lower_task or "만들어" in lower_task or "작성" in lower_task:
112
+ thought = f"The user wants to generate new code. Using 'generate_c_code' tool."
113
+ action_func = generate_c_code
114
  elif "compile" in lower_task or "run" in lower_task or "실행" in lower_task:
115
+ thought = f"The user wants to compile and run the code. Using 'compile_and_run_c_code' tool."
116
+ action_func = compile_and_run_c_code
117
+ action_arg = current_code # 실행은 현재 코드를 인자로 받음
118
+ else: # 그 외 모든 경우는 분석/리팩토링으로 간주
119
+ thought = f"The user wants to analyze or refactor the code. Using 'analyze_and_refactor_code' tool."
120
+ action_func = analyze_and_refactor_code
121
+ action_arg = (current_code, task) # 분석은 코드와 지시를 인자로 받음
122
+
123
+ output_log.append(f"\n▶ Step {i+1}: {task}\n🧠 Thought: {thought}")
124
+ yield current_code, "\n".join(output_log)
125
+ time.sleep(1)
126
 
127
+ # 액션 실행
128
+ if isinstance(action_arg, tuple):
129
+ result = action_func(*action_arg)
130
  else:
131
+ result = action_func(action_arg)
132
+
133
+ # 결과 처리
134
+ if action_func == generate_c_code:
135
+ if result and not result.startswith("//"):
136
+ current_code = result
137
+ output_log.append("✅ Code generated and updated in the editor.")
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
+ output_log.append("✅ Code refactored and updated in the editor.")
147
+ output_log.append(f"🔎 Analysis Result:\n{result}")
148
+
149
+ yield current_code, "\n".join(output_log)
150
 
151
+ output_log.append("\n\n--- All tasks complete. ---")
 
 
152
  yield current_code, "\n".join(output_log)
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("# 💻 The True C-Codestral IDE Agent")
158
 
 
180
  with gr.Accordion("Tool: Compile & Run C Code", open=False):
181
  gr.Interface(fn=compile_and_run_c_code, inputs=gr.Code(language="c"), outputs=gr.Textbox(label="Output"))
182
  with gr.Accordion("Tool: Analyze & Refactor C Code", open=False):
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()