Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,9 @@ from http import HTTPStatus
|
|
5 |
from typing import Dict, List, Optional, Tuple
|
6 |
import base64
|
7 |
import anthropic
|
|
|
|
|
|
|
8 |
from functools import partial
|
9 |
|
10 |
import gradio as gr
|
@@ -54,8 +57,141 @@ def get_image_base64(image_path):
|
|
54 |
encoded_string = base64.b64encode(image_file.read()).decode()
|
55 |
return encoded_string
|
56 |
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
class Role:
|
61 |
SYSTEM = "system"
|
@@ -108,69 +244,7 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
|
|
108 |
"system": SystemPrompt,
|
109 |
})
|
110 |
|
111 |
-
|
112 |
-
if not query or query.strip() == '':
|
113 |
-
query = random.choice(DEMO_LIST)['description'] # 빈 쿼리일 경우 랜덤 예제 사용
|
114 |
-
|
115 |
-
if _history is None:
|
116 |
-
_history = []
|
117 |
-
|
118 |
-
messages = history_to_messages(_history, _setting['system'])
|
119 |
-
system_message = messages[0]['content']
|
120 |
-
|
121 |
-
claude_messages = [
|
122 |
-
{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
|
123 |
-
for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
|
124 |
-
if msg["content"].strip() != '' # 빈 메시지 필터링
|
125 |
-
]
|
126 |
-
|
127 |
-
try:
|
128 |
-
yield [
|
129 |
-
"Generating code...",
|
130 |
-
_history,
|
131 |
-
None,
|
132 |
-
gr.update(active_key="loading"),
|
133 |
-
gr.update(open=True)
|
134 |
-
]
|
135 |
-
|
136 |
-
with client.messages.stream(
|
137 |
-
model="claude-3-5-sonnet-20241022",
|
138 |
-
max_tokens=7800,
|
139 |
-
system=system_message,
|
140 |
-
messages=claude_messages
|
141 |
-
) as stream:
|
142 |
-
collected_content = ""
|
143 |
-
for chunk in stream:
|
144 |
-
if chunk.type == "content_block_delta":
|
145 |
-
delta = chunk.delta.text
|
146 |
-
collected_content += delta
|
147 |
-
|
148 |
-
yield [
|
149 |
-
collected_content,
|
150 |
-
_history,
|
151 |
-
None,
|
152 |
-
gr.update(active_key="loading"),
|
153 |
-
gr.update(open=True)
|
154 |
-
]
|
155 |
-
|
156 |
-
_history = messages_to_history([
|
157 |
-
{'role': Role.SYSTEM, 'content': system_message}
|
158 |
-
] + claude_messages + [{
|
159 |
-
'role': Role.ASSISTANT,
|
160 |
-
'content': collected_content
|
161 |
-
}])
|
162 |
-
|
163 |
-
yield [
|
164 |
-
collected_content,
|
165 |
-
_history,
|
166 |
-
send_to_sandbox(remove_code_block(collected_content)),
|
167 |
-
gr.update(active_key="render"),
|
168 |
-
gr.update(open=True)
|
169 |
-
]
|
170 |
-
|
171 |
-
except Exception as e:
|
172 |
-
print(f"Error details: {str(e)}") # 디버깅을 위한 에러 출력
|
173 |
-
raise ValueError(f'Error calling Claude API: {str(e)}')
|
174 |
|
175 |
with ms.Application() as app:
|
176 |
with antd.ConfigProvider():
|
@@ -361,11 +435,13 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
|
|
361 |
open=False), inputs=[], outputs=[history_drawer])
|
362 |
|
363 |
btn.click(
|
364 |
-
generation_code,
|
365 |
inputs=[input, setting, history],
|
366 |
outputs=[code_output, history, sandbox, state_tab, code_drawer]
|
367 |
)
|
368 |
|
|
|
|
|
369 |
clear_btn.click(clear_history, inputs=[], outputs=[history])
|
370 |
|
371 |
if __name__ == "__main__":
|
|
|
5 |
from typing import Dict, List, Optional, Tuple
|
6 |
import base64
|
7 |
import anthropic
|
8 |
+
import openai
|
9 |
+
import asyncio
|
10 |
+
import time
|
11 |
from functools import partial
|
12 |
|
13 |
import gradio as gr
|
|
|
57 |
encoded_string = base64.b64encode(image_file.read()).decode()
|
58 |
return encoded_string
|
59 |
|
60 |
+
# API 클라이언트 초기화
|
61 |
+
YOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY')
|
62 |
+
YOUR_OPENAI_TOKEN = os.getenv('OPENAI_API_KEY')
|
63 |
+
|
64 |
+
claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)
|
65 |
+
openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
async def try_claude_api(system_message, claude_messages, timeout=5):
|
70 |
+
try:
|
71 |
+
start_time = time.time()
|
72 |
+
with claude_client.messages.stream(
|
73 |
+
model="claude-3-5-sonnet-20241022",
|
74 |
+
max_tokens=7800,
|
75 |
+
system=system_message,
|
76 |
+
messages=claude_messages
|
77 |
+
) as stream:
|
78 |
+
collected_content = ""
|
79 |
+
for chunk in stream:
|
80 |
+
if time.time() - start_time > timeout:
|
81 |
+
raise TimeoutError("Claude API timeout")
|
82 |
+
if chunk.type == "content_block_delta":
|
83 |
+
collected_content += chunk.delta.text
|
84 |
+
yield collected_content
|
85 |
+
except Exception as e:
|
86 |
+
print(f"Claude API error: {str(e)}")
|
87 |
+
raise e
|
88 |
+
|
89 |
+
|
90 |
+
|
91 |
+
async def try_openai_api(openai_messages):
|
92 |
+
try:
|
93 |
+
stream = openai_client.chat.completions.create(
|
94 |
+
model="gpt-4o",
|
95 |
+
messages=openai_messages,
|
96 |
+
stream=True,
|
97 |
+
max_tokens=4096,
|
98 |
+
temperature=0.7
|
99 |
+
)
|
100 |
+
|
101 |
+
collected_content = ""
|
102 |
+
for chunk in stream:
|
103 |
+
if chunk.choices[0].delta.content is not None:
|
104 |
+
collected_content += chunk.choices[0].delta.content
|
105 |
+
yield collected_content
|
106 |
+
|
107 |
+
except Exception as e:
|
108 |
+
print(f"OpenAI API error: {str(e)}")
|
109 |
+
raise e
|
110 |
+
|
111 |
+
async def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
|
112 |
+
if not query or query.strip() == '':
|
113 |
+
query = random.choice(DEMO_LIST)['description']
|
114 |
+
|
115 |
+
if _history is None:
|
116 |
+
_history = []
|
117 |
+
|
118 |
+
messages = history_to_messages(_history, _setting['system'])
|
119 |
+
system_message = messages[0]['content']
|
120 |
+
|
121 |
+
# Claude 메시지 포맷
|
122 |
+
claude_messages = [
|
123 |
+
{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
|
124 |
+
for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
|
125 |
+
if msg["content"].strip() != ''
|
126 |
+
]
|
127 |
+
|
128 |
+
# OpenAI 메시지 포맷
|
129 |
+
openai_messages = [{"role": "system", "content": system_message}]
|
130 |
+
for msg in messages[1:]:
|
131 |
+
openai_messages.append({
|
132 |
+
"role": msg["role"],
|
133 |
+
"content": msg["content"]
|
134 |
+
})
|
135 |
+
openai_messages.append({"role": "user", "content": query})
|
136 |
+
|
137 |
+
try:
|
138 |
+
yield [
|
139 |
+
"Generating code...",
|
140 |
+
_history,
|
141 |
+
None,
|
142 |
+
gr.update(active_key="loading"),
|
143 |
+
gr.update(open=True)
|
144 |
+
]
|
145 |
+
|
146 |
+
collected_content = None
|
147 |
+
# Claude API 시도
|
148 |
+
try:
|
149 |
+
async for content in try_claude_api(system_message, claude_messages):
|
150 |
+
yield [
|
151 |
+
content,
|
152 |
+
_history,
|
153 |
+
None,
|
154 |
+
gr.update(active_key="loading"),
|
155 |
+
gr.update(open=True)
|
156 |
+
]
|
157 |
+
collected_content = content
|
158 |
+
|
159 |
+
except Exception as claude_error:
|
160 |
+
print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")
|
161 |
+
|
162 |
+
# OpenAI API로 폴백
|
163 |
+
async for content in try_openai_api(openai_messages):
|
164 |
+
yield [
|
165 |
+
content,
|
166 |
+
_history,
|
167 |
+
None,
|
168 |
+
gr.update(active_key="loading"),
|
169 |
+
gr.update(open=True)
|
170 |
+
]
|
171 |
+
collected_content = content
|
172 |
+
|
173 |
+
if collected_content:
|
174 |
+
_history = messages_to_history([
|
175 |
+
{'role': Role.SYSTEM, 'content': system_message}
|
176 |
+
] + claude_messages + [{
|
177 |
+
'role': Role.ASSISTANT,
|
178 |
+
'content': collected_content
|
179 |
+
}])
|
180 |
+
|
181 |
+
yield [
|
182 |
+
collected_content,
|
183 |
+
_history,
|
184 |
+
send_to_sandbox(remove_code_block(collected_content)),
|
185 |
+
gr.update(active_key="render"),
|
186 |
+
gr.update(open=True)
|
187 |
+
]
|
188 |
+
else:
|
189 |
+
raise ValueError("No content was generated from either API")
|
190 |
+
|
191 |
+
except Exception as e:
|
192 |
+
print(f"Error details: {str(e)}")
|
193 |
+
raise ValueError(f'Error calling APIs: {str(e)}')
|
194 |
+
|
195 |
|
196 |
class Role:
|
197 |
SYSTEM = "system"
|
|
|
244 |
"system": SystemPrompt,
|
245 |
})
|
246 |
|
247 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
248 |
|
249 |
with ms.Application() as app:
|
250 |
with antd.ConfigProvider():
|
|
|
435 |
open=False), inputs=[], outputs=[history_drawer])
|
436 |
|
437 |
btn.click(
|
438 |
+
lambda: asyncio.create_task(generation_code(input.value, setting.value, history.value)),
|
439 |
inputs=[input, setting, history],
|
440 |
outputs=[code_output, history, sandbox, state_tab, code_drawer]
|
441 |
)
|
442 |
|
443 |
+
|
444 |
+
|
445 |
clear_btn.click(clear_history, inputs=[], outputs=[history])
|
446 |
|
447 |
if __name__ == "__main__":
|