jianghuyihei commited on
Commit
97a5f88
1 Parent(s): 760970b
Files changed (2) hide show
  1. __pycache__/app.cpython-310.pyc +0 -0
  2. app.py +101 -33
__pycache__/app.cpython-310.pyc CHANGED
Binary files a/__pycache__/app.cpython-310.pyc and b/__pycache__/app.cpython-310.pyc differ
 
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, Form
2
  from fastapi.responses import HTMLResponse
3
  from jinja2 import Template
4
  import markdown
@@ -8,6 +8,8 @@ from apscheduler.schedulers.background import BackgroundScheduler
8
  from agents import DeepResearchAgent, get_llms
9
  import threading
10
  import logging
 
 
11
 
12
  lock = threading.Lock()
13
  app = FastAPI()
@@ -19,8 +21,6 @@ reply_count = 0
19
  # 启动时设置计数器重置
20
  last_reset_time = datetime.now()
21
 
22
- is_processing = False
23
-
24
  # HTML模板
25
  html_template = """
26
  <!DOCTYPE html>
@@ -267,33 +267,33 @@ html_template = """
267
  <h1>CoI Agent online demo 😊</h1>
268
  <div class="time-counter-container">
269
  <div id="time-taken" class="time-box">Time Taken: {{ time_taken }} seconds</div>
270
- <div class="counter-box">Today's Replies: {{ reply_count }}</div>
271
  </div>
272
- <div class="example-container">
273
- <div class="example-label">Example Input:</div>
274
- <div class="example-topics">
275
- <button onclick="fillTopic('Realistic Image Synthesis in Medical Imaging')">Realistic Image Synthesis in Medical Imaging</button>
276
- <button onclick="fillTopic('Using diffusion to generate road layout')">Using diffusion to generate road layout</button>
277
- <button onclick="fillTopic('Using LLM-based agent to generate idea')">Using LLM-based agent to generate idea</button>
 
278
  </div>
279
  </div>
280
  <form action="/" method="post" onsubmit="showLoading()">
281
  <div class="form-group">
282
  <label for="topic">Topic:</label>
283
  <input type="text" id="topic" name="topic">
284
- <button type="submit" id="submit-btn">Generate</button>
285
  </div>
286
  </form>
287
- <div id="loading" class="loading">Generating content, Usually takes 3-4 minutes, please wait...</div>
288
- <div class="progress-bar-container">
289
- <div id="progress-bar" class="progress-bar"></div>
290
- </div>
291
- <div class="result">
292
- <div class="box">
293
- <h2>Idea</h2>
294
- <div>{{ idea | safe }}</div>
295
  </div>
296
  </div>
 
297
  {% if error %}
298
  <div class="error">
299
  <div class="box">
@@ -305,6 +305,20 @@ html_template = """
305
  </div>
306
  <script>
307
  hideLoading();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  </script>
309
  </body>
310
  </html>
@@ -320,30 +334,84 @@ scheduler = BackgroundScheduler()
320
  scheduler.add_job(reset_counter, 'cron', hour=0, minute=0)
321
  scheduler.start()
322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  @app.get("/", response_class=HTMLResponse)
324
  def form_get():
325
- return Template(html_template).render(idea= "This is a example of the idea geneartion", error=None, reply_count=reply_count)
326
 
327
  @app.post("/", response_class=HTMLResponse)
328
- def form_post(topic: str = Form(...)):
329
  global reply_count
330
- global is_processing
331
  start_time = time.time()
332
 
333
- if is_processing:
334
- error = "The server is processing another request. Please try again later(We only process one instruction at a time, please forgive me.)."
335
- return Template(html_template).render(idea="", error=error, reply_count=reply_count)
336
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  with lock:
338
- is_processing = True
339
  logging.info(f"Processing request for topic: {topic}")
340
  start_time = time.time()
 
 
 
341
  # 检查是否超过每日最大回复次数
342
  if reply_count >= MAX_REPLIES_PER_DAY:
343
  error_message = "Today's maximum number of replies has been reached. Please try again tomorrow."
344
  logging.info(f"Today's maximum number of replies has been reached. Please try again tomorrow.")
345
- is_processing = False
346
- return Template(html_template).render(idea="", error=error_message, reply_count=reply_count)
347
  try:
348
  main_llm, cheap_llm = get_llms()
349
  deep_research_agent = DeepResearchAgent(llm=main_llm, cheap_llm=cheap_llm, improve_cnt=1, max_chain_length=5, min_chain_length=3, max_chain_numbers=1)
@@ -357,11 +425,11 @@ def form_post(topic: str = Form(...)):
357
  end_time = time.time()
358
  time_taken = round(end_time - start_time, 2)
359
  logging.info(f"Successfully generated idea for topic: {topic}")
360
- is_processing = False
361
- return Template(html_template).render(idea=idea_md, error=None, reply_count=reply_count, time_taken=time_taken)
362
  except Exception as e:
363
  end_time = time.time()
364
  time_taken = round(end_time - start_time, 2)
365
  logging.error(f"Failed to generate idea for topic: {topic}, Error: {str(e)}")
366
- is_processing = False
367
- return Template(html_template).render(idea="", error=str(e), reply_count=reply_count, time_taken=time_taken)
 
 
 
1
+ from fastapi import FastAPI, Form, Request,Response
2
  from fastapi.responses import HTMLResponse
3
  from jinja2 import Template
4
  import markdown
 
8
  from agents import DeepResearchAgent, get_llms
9
  import threading
10
  import logging
11
+ from queue import Queue
12
+ import uuid
13
 
14
  lock = threading.Lock()
15
  app = FastAPI()
 
21
  # 启动时设置计数器重置
22
  last_reset_time = datetime.now()
23
 
 
 
24
  # HTML模板
25
  html_template = """
26
  <!DOCTYPE html>
 
267
  <h1>CoI Agent online demo 😊</h1>
268
  <div class="time-counter-container">
269
  <div id="time-taken" class="time-box">Time Taken: {{ time_taken }} seconds</div>
270
+ <div class="counter-box">Today's Replies: {{ reply_count }}/100 </div>
271
  </div>
272
+ <div class="progress-bar-container">
273
+ <div id="progress-bar" class="progress-bar"></div>
274
+ </div>
275
+ <div class="result">
276
+ <div class="box">
277
+ <h2>Idea</h2>
278
+ <div>{{ idea | safe }}</div>
279
  </div>
280
  </div>
281
  <form action="/" method="post" onsubmit="showLoading()">
282
  <div class="form-group">
283
  <label for="topic">Topic:</label>
284
  <input type="text" id="topic" name="topic">
285
+ <button type="submit" id="submit-btn">{{ button_text }}</button>
286
  </div>
287
  </form>
288
+ <div class="example-container">
289
+ <div class="example-label">Example Input:</div>
290
+ <div class="example-topics">
291
+ <button onclick="fillTopic('Realistic Image Synthesis in Medical Imaging')">Realistic Image Synthesis in Medical Imaging</button>
292
+ <button onclick="fillTopic('Using diffusion to generate road layout')">Using diffusion to generate road layout</button>
293
+ <button onclick="fillTopic('Using LLM-based agent to generate idea')">Using LLM-based agent to generate idea</button>
 
 
294
  </div>
295
  </div>
296
+ <div id="loading" class="loading">{{ loading_text }}</div>
297
  {% if error %}
298
  <div class="error">
299
  <div class="box">
 
305
  </div>
306
  <script>
307
  hideLoading();
308
+ <script>
309
+ async function getUserId() {
310
+ // 清除 sessionStorage 中的 user_id
311
+ sessionStorage.removeItem("user_id");
312
+
313
+ // 请求新的 user_id
314
+ const response = await fetch("/user_id");
315
+ const data = await response.json();
316
+ const userId = data.user_id;
317
+ sessionStorage.setItem("user_id", userId);
318
+ console.log("User ID:", userId);
319
+ }
320
+
321
+ window.onload = getUserId;
322
  </script>
323
  </body>
324
  </html>
 
334
  scheduler.add_job(reset_counter, 'cron', hour=0, minute=0)
335
  scheduler.start()
336
 
337
+ queue = Queue()
338
+
339
+
340
+ @app.middleware("http")
341
+ async def add_user_id_and_state_cookie(request: Request, call_next):
342
+ user_id = request.cookies.get("user_id")
343
+ state = request.cookies.get("state")
344
+
345
+ if not user_id:
346
+ user_id = str(uuid.uuid4())
347
+ state = "generate"
348
+ response = await call_next(request)
349
+ response.set_cookie(key="user_id", value=user_id)
350
+ response.set_cookie(key="state", value=state)
351
+ elif not state:
352
+ state = "generate"
353
+ response = await call_next(request)
354
+ response.set_cookie(key="state", value=state)
355
+ else:
356
+ response = await call_next(request)
357
+
358
+ return response
359
+
360
+ @app.get("/user_id")
361
+ async def get_user_id():
362
+ user_id = str(uuid.uuid4())
363
+ return {"user_id": user_id}
364
+
365
  @app.get("/", response_class=HTMLResponse)
366
  def form_get():
367
+ return Template(html_template).render(idea= "This is a example of the idea geneartion", error=None, reply_count=reply_count,button_text="Generate",loading_text="Generating content, Usually takes 2-3 minutes, please wait...")
368
 
369
  @app.post("/", response_class=HTMLResponse)
370
+ def form_post(request: Request,response: Response,topic: str = Form(...)):
371
  global reply_count
 
372
  start_time = time.time()
373
 
374
+ # 获得每个网页的user_id
375
+ user_id = request.cookies.get("user_id")
376
+ state = request.cookies.get("state", "generate")
377
+
378
+ print(user_id,state)
379
+ loading_text = "Generating content, Usually takes 2-3 minutes, please wait..."
380
+ if state == "generate":
381
+ if not queue.empty():
382
+ queue_len = queue.qsize()
383
+ if queue_len + reply_count >= MAX_REPLIES_PER_DAY:
384
+ error_message = "Today's maximum number of replies has been reached. Please try again tomorrow."
385
+ return Template(html_template).render(idea="", error=error_message, reply_count=reply_count, button_text="Generate",loading_text=loading_text)
386
+ error_message = "There are currently {} requests being processed. If you want to queue, please click the Continue button and you will enter the queue.".format(queue_len)
387
+ new_state = "continue"
388
+ new_button_text = "Continue"
389
+ response.set_cookie(key="state", value=new_state)
390
+ return Template(html_template).render(idea="", error=error_message, reply_count=reply_count, button_text=new_button_text,loading_text=f"Generating content, Usually takes {queue_len*2}-{queue_len*3} minutes, please wait...")
391
+ else:
392
+ queue.put(user_id)
393
+ elif state == "continue":
394
+ queue.put(user_id)
395
+
396
+ new_state = "generate"
397
+ new_button_text = "Generate"
398
+ response.set_cookie(key="state", value=new_state)
399
+ queue_len = queue.qsize()
400
+
401
+ # 判断当前是否轮到该用户,如果没轮到则一直等待到轮到为止
402
+ while queue.queue[0] != user_id:
403
+ continue
404
+
405
  with lock:
 
406
  logging.info(f"Processing request for topic: {topic}")
407
  start_time = time.time()
408
+ error_message = None
409
+ idea = ""
410
+ time_taken = 0
411
  # 检查是否超过每日最大回复次数
412
  if reply_count >= MAX_REPLIES_PER_DAY:
413
  error_message = "Today's maximum number of replies has been reached. Please try again tomorrow."
414
  logging.info(f"Today's maximum number of replies has been reached. Please try again tomorrow.")
 
 
415
  try:
416
  main_llm, cheap_llm = get_llms()
417
  deep_research_agent = DeepResearchAgent(llm=main_llm, cheap_llm=cheap_llm, improve_cnt=1, max_chain_length=5, min_chain_length=3, max_chain_numbers=1)
 
425
  end_time = time.time()
426
  time_taken = round(end_time - start_time, 2)
427
  logging.info(f"Successfully generated idea for topic: {topic}")
 
 
428
  except Exception as e:
429
  end_time = time.time()
430
  time_taken = round(end_time - start_time, 2)
431
  logging.error(f"Failed to generate idea for topic: {topic}, Error: {str(e)}")
432
+ error_message = str(e)
433
+ # 从队列中移除当前用户
434
+ queue.get()
435
+ return Template(html_template).render(idea=idea, error=error_message, reply_count=reply_count, time_taken=time_taken,button_text=new_button_text,loading_text=loading_text)