kimhyunwoo commited on
Commit
fbae41a
·
verified ·
1 Parent(s): c760be6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -33
app.py CHANGED
@@ -3,20 +3,22 @@ import os
3
  import subprocess
4
  from mistralai.client import MistralClient
5
 
6
- # --- 1. 환경 설정 ---
7
  API_KEY = os.environ.get("MISTRAL_API_KEY")
8
  CLIENT = None
 
 
9
  if API_KEY:
10
  try:
11
- # requirements.txt에 mistralai==0.4.2 버전을 명시하여 경고를 제거합니다.
12
- CLIENT = MistralClient(api_key=API_KEY)
13
- print("Mistral API Client initialized successfully.")
14
  except Exception as e:
15
  print(f"Error initializing Mistral Client: {e}")
16
  else:
17
  print("FATAL: MISTRAL_API_KEY is not set in Space Secrets.")
18
 
19
- # --- 2. 백엔드 핵심 기능 ---
20
  def generate_c_code(description: str) -> str:
21
  if not CLIENT: return "Error: Mistral API key not configured."
22
  prompt = f"Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code within a single ```c code block."
@@ -51,22 +53,25 @@ def compile_and_run_c_code(code: str) -> str:
51
  except Exception as e:
52
  return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
53
 
54
- # --- 3. Gradio 챗봇 로직 (type='messages' 완벽 호환) ---
55
- def agent_chat(message: str, history: list[dict[str, str]]):
56
- # 사용자 메시지를 history에 추가
57
- history.append({"role": "user", "content": message})
58
-
 
 
 
 
 
 
59
  lower_message = message.lower()
60
  bot_response = ""
61
 
62
- if not CLIENT:
63
- bot_response = "MISTRAL_API_KEY가 Space Secrets에 설정되지 않았습니다."
64
- elif "compile" in lower_message or "run" in lower_message or "실행" in lower_message:
65
  code_to_run = ""
66
- # history (list of dicts)에서 코드 찾기
67
- for item in reversed(history):
68
- if item.get("role") == "assistant" and "```c" in item.get("content", ""):
69
- code_to_run = item["content"].split("```c")[1].split("```")[0].strip()
70
  break
71
  if not code_to_run:
72
  bot_response = "컴파일할 코드를 찾을 수 없습니다. 먼저 코드를 생성해주세요."
@@ -78,36 +83,32 @@ def agent_chat(message: str, history: list[dict[str, str]]):
78
  bot_response = f"코드가 생성되었습니다.\n\n```c\n{generated_code}\n```"
79
 
80
  else:
81
- # Mistral API에는 전체 대화 기록을 전달
82
- response = CLIENT.chat(model="codestral-latest", messages=history)
83
  bot_response = response.choices[0].message.content
84
 
85
- # 봇 응답을 history 추가
86
- history.append({"role": "assistant", "content": bot_response})
87
-
88
- # 최종 업데이트된 history를 반환
89
  return history
90
 
91
- # --- 4. Gradio UI 구성 (type='messages' 명시) ---
92
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="gray"), css="footer {visibility: hidden}") as demo:
93
  gr.Markdown("# 🚀 C-Codestral Agent")
94
 
95
  with gr.Tabs():
96
  with gr.TabItem("🤖 Agent Chat"):
97
- # 에러의 원인이었던 type을 'messages'로 명시적으로 지정
98
- chatbot = gr.Chatbot(label="C-Agent", height=600, render_markdown=True, type="messages")
99
-
100
  with gr.Row():
101
  msg = gr.Textbox(placeholder="Ask me to generate or run C code...", show_label=False, container=False, scale=10)
102
  btn = gr.Button("Send", variant="primary", scale=1)
103
 
104
- # 이벤트 리스너: 함수가 업데이트된 history 전체를 반환하고, 챗봇이 이를 받음
105
- def handle_submit(message, history):
106
- new_history = agent_chat(message, history)
107
- return new_history, "" # 업데이트된 history와 빈 문��열을 반환하여 입력창 초기화
108
 
109
- btn.click(handle_submit, [msg, chatbot], [chatbot, msg])
110
- msg.submit(handle_submit, [msg, chatbot], [chatbot, msg])
 
 
 
 
111
 
112
  with gr.TabItem("🛠️ MCP Tools API"):
113
  gr.Markdown("## Available MCP Tools\nThese APIs can be used by any MCP-compliant client.")
 
3
  import subprocess
4
  from mistralai.client import MistralClient
5
 
6
+ # --- 1. 환경 설정 (Codestral 전용 엔드포인트 지정) ---
7
  API_KEY = os.environ.get("MISTRAL_API_KEY")
8
  CLIENT = None
9
+ CODESTRAL_ENDPOINT = "https://codestral.mistral.ai/v1" # <--- 이 부분이 핵심입니다.
10
+
11
  if API_KEY:
12
  try:
13
+ # Codestral 전용 엔드포인트를 명시적으로 지정합니다.
14
+ CLIENT = MistralClient(api_key=API_KEY, endpoint=CODESTRAL_ENDPOINT)
15
+ print("Mistral API Client for Codestral initialized successfully.")
16
  except Exception as e:
17
  print(f"Error initializing Mistral Client: {e}")
18
  else:
19
  print("FATAL: MISTRAL_API_KEY is not set in Space Secrets.")
20
 
21
+ # --- 2. 백엔드 핵심 기능 (변경 없음) ---
22
  def generate_c_code(description: str) -> str:
23
  if not CLIENT: return "Error: Mistral API key not configured."
24
  prompt = f"Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code within a single ```c code block."
 
53
  except Exception as e:
54
  return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
55
 
56
+ # --- 3. Gradio 챗봇 로직 (변경 없음) ---
57
+ def agent_chat(message: str, history: list[list[str | None]]):
58
+ if not CLIENT:
59
+ return "MISTRAL_API_KEY를 Space Secrets에 설정해주세요."
60
+
61
+ history_for_api = []
62
+ for human, assistant in history:
63
+ if human: history_for_api.append({"role": "user", "content": human})
64
+ if assistant: history_for_api.append({"role": "assistant", "content": assistant})
65
+ history_for_api.append({"role": "user", "content": message})
66
+
67
  lower_message = message.lower()
68
  bot_response = ""
69
 
70
+ if "compile" in lower_message or "run" in lower_message or "실행" in lower_message:
 
 
71
  code_to_run = ""
72
+ for h_user, h_ai in reversed(history):
73
+ if h_ai and "```c" in h_ai:
74
+ code_to_run = h_ai.split("```c")[1].split("```")[0].strip()
 
75
  break
76
  if not code_to_run:
77
  bot_response = "컴파일할 코드를 찾을 수 없습니다. 먼저 코드를 생성해주세요."
 
83
  bot_response = f"코드가 생성되었습니다.\n\n```c\n{generated_code}\n```"
84
 
85
  else:
86
+ response = CLIENT.chat(model="codestral-latest", messages=history_for_api)
 
87
  bot_response = response.choices[0].message.content
88
 
89
+ history.append([message, bot_response])
 
 
 
90
  return history
91
 
92
+ # --- 4. Gradio UI 구성 (변경 없음) ---
93
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="gray"), css="footer {visibility: hidden}") as demo:
94
  gr.Markdown("# 🚀 C-Codestral Agent")
95
 
96
  with gr.Tabs():
97
  with gr.TabItem("🤖 Agent Chat"):
98
+ chatbot = gr.Chatbot(label="C-Agent", height=600, render_markdown=True)
 
 
99
  with gr.Row():
100
  msg = gr.Textbox(placeholder="Ask me to generate or run C code...", show_label=False, container=False, scale=10)
101
  btn = gr.Button("Send", variant="primary", scale=1)
102
 
103
+ def user(user_message, history):
104
+ return "", history + [[user_message, None]]
 
 
105
 
106
+ btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(
107
+ agent_chat, chatbot, chatbot
108
+ )
109
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
110
+ agent_chat, chatbot, chatbot
111
+ )
112
 
113
  with gr.TabItem("🛠️ MCP Tools API"):
114
  gr.Markdown("## Available MCP Tools\nThese APIs can be used by any MCP-compliant client.")