openfree commited on
Commit
2851e29
Β·
verified Β·
1 Parent(s): 86b53be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -81
app.py CHANGED
@@ -120,45 +120,35 @@ except Exception as e:
120
 
121
  # try_claude_api ν•¨μˆ˜ μˆ˜μ •
122
  async def try_claude_api(system_message, claude_messages, timeout=15):
123
- if not claude_client:
124
- raise Exception("Claude client not initialized")
125
-
126
  try:
127
  start_time = time.time()
128
-
129
- # asyncio.timeout() λŒ€μ‹  asyncio.wait_for() μ‚¬μš©
130
- async def stream_content():
131
- with claude_client.messages.stream(
132
- model="claude-3-5-sonnet-20241022",
133
- max_tokens=7800,
134
- system=system_message,
135
- messages=claude_messages
136
- ) as stream:
137
- collected_content = ""
138
- async for chunk in stream:
139
- if chunk.type == "content_block_delta":
140
- collected_content += chunk.delta.text
141
- yield collected_content
142
- await asyncio.sleep(0)
 
 
 
143
 
144
- # asyncio.wait_for()둜 νƒ€μž„μ•„μ›ƒ μ„€μ •
145
- async for content in asyncio.wait_for(stream_content(), timeout):
146
- yield content
147
-
148
- except asyncio.TimeoutError:
149
- raise TimeoutError(f"Claude API timeout after {timeout} seconds")
150
  except Exception as e:
151
  print(f"Claude API error: {str(e)}")
152
- raise
153
 
154
- # try_openai_api ν•¨μˆ˜ μˆ˜μ •
155
  async def try_openai_api(openai_messages):
156
- if not openai_client:
157
- raise Exception("OpenAI client not initialized")
158
-
159
  try:
160
- response = await openai_client.chat.completions.create(
161
- model="gpt-4",
162
  messages=openai_messages,
163
  stream=True,
164
  max_tokens=4096,
@@ -166,14 +156,14 @@ async def try_openai_api(openai_messages):
166
  )
167
 
168
  collected_content = ""
169
- async for chunk in response:
170
- if chunk.choices[0].delta.content:
171
  collected_content += chunk.choices[0].delta.content
172
  yield collected_content
173
 
174
  except Exception as e:
175
  print(f"OpenAI API error: {str(e)}")
176
- raise
177
 
178
  class Demo:
179
  def __init__(self):
@@ -186,24 +176,24 @@ class Demo:
186
  if _history is None:
187
  _history = []
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  try:
190
- messages = history_to_messages(_history, _setting['system'])
191
- system_message = messages[0]['content']
192
-
193
- claude_messages = [
194
- {"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
195
- for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
196
- if msg["content"].strip() != ''
197
- ]
198
-
199
- openai_messages = [{"role": "system", "content": system_message}]
200
- for msg in messages[1:]:
201
- openai_messages.append({
202
- "role": msg["role"],
203
- "content": msg["content"]
204
- })
205
- openai_messages.append({"role": "user", "content": query})
206
-
207
  yield [
208
  "Generating code...",
209
  _history,
@@ -211,14 +201,11 @@ class Demo:
211
  gr.update(active_key="loading"),
212
  gr.update(open=True)
213
  ]
214
-
 
215
  collected_content = None
216
- error_message = None
217
-
218
- # Claude API μ‹œλ„
219
  try:
220
  async for content in try_claude_api(system_message, claude_messages):
221
- collected_content = content
222
  yield [
223
  content,
224
  _history,
@@ -226,25 +213,23 @@ class Demo:
226
  gr.update(active_key="loading"),
227
  gr.update(open=True)
228
  ]
 
 
 
229
  except Exception as claude_error:
230
- print(f"Claude API error: {str(claude_error)}")
231
- error_message = str(claude_error)
232
 
233
- # OpenAI API μ‹œλ„
234
- try:
235
- async for content in try_openai_api(openai_messages):
236
- collected_content = content
237
- yield [
238
- content,
239
- _history,
240
- None,
241
- gr.update(active_key="loading"),
242
- gr.update(open=True)
243
- ]
244
- except Exception as openai_error:
245
- print(f"OpenAI API error: {str(openai_error)}")
246
- error_message = f"Both APIs failed: Claude - {str(claude_error)}, OpenAI - {str(openai_error)}"
247
-
248
  if collected_content:
249
  _history = messages_to_history([
250
  {'role': Role.SYSTEM, 'content': system_message}
@@ -261,21 +246,16 @@ class Demo:
261
  gr.update(open=True)
262
  ]
263
  else:
264
- raise ValueError(error_message or "No content was generated")
265
 
266
  except Exception as e:
267
  print(f"Error details: {str(e)}")
268
- yield [
269
- f"Error: {str(e)}",
270
- _history,
271
- None,
272
- gr.update(active_key="empty"),
273
- gr.update(open=False)
274
- ]
275
 
276
  def clear_history(self):
277
  return []
278
 
 
279
  def remove_code_block(text):
280
  pattern = r'```html\n(.+?)\n```'
281
  match = re.search(pattern, text, re.DOTALL)
 
120
 
121
  # try_claude_api ν•¨μˆ˜ μˆ˜μ •
122
  async def try_claude_api(system_message, claude_messages, timeout=15):
 
 
 
123
  try:
124
  start_time = time.time()
125
+ with claude_client.messages.stream(
126
+ model="claude-3-5-sonnet-20241022",
127
+ max_tokens=7800,
128
+ system=system_message,
129
+ messages=claude_messages
130
+ ) as stream:
131
+ collected_content = ""
132
+ for chunk in stream:
133
+ current_time = time.time()
134
+ if current_time - start_time > timeout:
135
+ print(f"Claude API response time: {current_time - start_time:.2f} seconds")
136
+ raise TimeoutError("Claude API timeout")
137
+ if chunk.type == "content_block_delta":
138
+ collected_content += chunk.delta.text
139
+ yield collected_content
140
+ await asyncio.sleep(0)
141
+
142
+ start_time = current_time
143
 
 
 
 
 
 
 
144
  except Exception as e:
145
  print(f"Claude API error: {str(e)}")
146
+ raise e
147
 
 
148
  async def try_openai_api(openai_messages):
 
 
 
149
  try:
150
+ stream = openai_client.chat.completions.create(
151
+ model="gpt-4o",
152
  messages=openai_messages,
153
  stream=True,
154
  max_tokens=4096,
 
156
  )
157
 
158
  collected_content = ""
159
+ for chunk in stream:
160
+ if chunk.choices[0].delta.content is not None:
161
  collected_content += chunk.choices[0].delta.content
162
  yield collected_content
163
 
164
  except Exception as e:
165
  print(f"OpenAI API error: {str(e)}")
166
+ raise e
167
 
168
  class Demo:
169
  def __init__(self):
 
176
  if _history is None:
177
  _history = []
178
 
179
+ messages = history_to_messages(_history, _setting['system'])
180
+ system_message = messages[0]['content']
181
+
182
+ claude_messages = [
183
+ {"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
184
+ for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
185
+ if msg["content"].strip() != ''
186
+ ]
187
+
188
+ openai_messages = [{"role": "system", "content": system_message}]
189
+ for msg in messages[1:]:
190
+ openai_messages.append({
191
+ "role": msg["role"],
192
+ "content": msg["content"]
193
+ })
194
+ openai_messages.append({"role": "user", "content": query})
195
+
196
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  yield [
198
  "Generating code...",
199
  _history,
 
201
  gr.update(active_key="loading"),
202
  gr.update(open=True)
203
  ]
204
+ await asyncio.sleep(0)
205
+
206
  collected_content = None
 
 
 
207
  try:
208
  async for content in try_claude_api(system_message, claude_messages):
 
209
  yield [
210
  content,
211
  _history,
 
213
  gr.update(active_key="loading"),
214
  gr.update(open=True)
215
  ]
216
+ await asyncio.sleep(0)
217
+ collected_content = content
218
+
219
  except Exception as claude_error:
220
+ print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")
 
221
 
222
+ async for content in try_openai_api(openai_messages):
223
+ yield [
224
+ content,
225
+ _history,
226
+ None,
227
+ gr.update(active_key="loading"),
228
+ gr.update(open=True)
229
+ ]
230
+ await asyncio.sleep(0)
231
+ collected_content = content
232
+
 
 
 
 
233
  if collected_content:
234
  _history = messages_to_history([
235
  {'role': Role.SYSTEM, 'content': system_message}
 
246
  gr.update(open=True)
247
  ]
248
  else:
249
+ raise ValueError("No content was generated from either API")
250
 
251
  except Exception as e:
252
  print(f"Error details: {str(e)}")
253
+ raise ValueError(f'Error calling APIs: {str(e)}')
 
 
 
 
 
 
254
 
255
  def clear_history(self):
256
  return []
257
 
258
+
259
  def remove_code_block(text):
260
  pattern = r'```html\n(.+?)\n```'
261
  match = re.search(pattern, text, re.DOTALL)