from fastapi import FastAPI, Form, Request,Response
from fastapi.responses import HTMLResponse
from jinja2 import Template
import markdown
import time
from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from agents import DeepResearchAgent, get_llms
import threading
import logging
from queue import Queue
import uuid
lock = threading.Lock()
app = FastAPI()
# 每日最大回复次数
MAX_REPLIES_PER_DAY = 100
# 当日回复次数计数器
reply_count = 0
# 启动时设置计数器重置
last_reset_time = datetime.now()
# HTML模板
html_template = """
CoI Agent online demo 😊
CoI Agent: Revolutionizing Research in Novel Idea Development with LLM Agents
If this demo pleases you, please give us a star ⭐ on Github or 💖 on this space.
We only provide a simplified version here, and the number of replies is limited daily.
At the same time, due to the instability of PDF downloads, the waiting time may be longer, thank you for your patience.
If you want to experience the full version, please go to our github repository
https://github.com/DAMO-NLP-SG/CoI-Agent
Time Taken: {{ time_taken }} seconds
Today's Replies: {{ reply_count }}/100
{{ idea | safe }}
Example:
{{ loading_text }}
{% if error %}
Error
{{ error }}
{% endif %}
"""
# 重置每日计数器
def reset_counter():
global reply_count
reply_count = 0
# 设置定时任务每天0点重置计数器
scheduler = BackgroundScheduler()
scheduler.add_job(reset_counter, 'cron', hour=0, minute=0)
scheduler.start()
def fix_markdown(text):
lines = text.split('\n')
# Initialize the result list
result = []
# Iterate through the lines
for i, line in enumerate(lines):
# Check if the current line starts with a numbered list item
numbers = ['1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.', '10.', '11.', '12.', '13.', '14.', '15.', '16.', '17.', '18.', '19.', '20.','21.','22.','23.','24.','25.','26.','27.','28.','29.','30.']
if line.lstrip().startswith(tuple(numbers)):
# If it's not the first line and the previous line is not blank, add a blank line
if i > 0 and lines[i - 1].strip():
result.append('')
# Append the current line to the result
result.append(line)
# Join the result list into a single string with newline characters
return ' '.join(result)
script_template = """
function setstate() {{
document.getElementById("user_id").value = "{user_id}";
document.getElementById("state").value = "{state}";
let userId = document.getElementById("user_id").value;
let state = document.getElementById("state").value;
console.log(`1 User ID: ${{userId}}, State: ${{state}}`);
}}
window.onload = setstate;
"""
queue = Queue()
@app.get("/", response_class=HTMLResponse)
def form_get():
script = script_template.format(user_id=str(uuid.uuid4()), state="generate")
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 3-4 minutes, please wait...",script=script)
@app.post("/", response_class=HTMLResponse)
def form_post(topic: str = Form(...), user_id: str = Form(...), state: str = Form(...)):
global reply_count
start_time = time.time()
if user_id == "":
user_id = str(uuid.uuid4())
if state == "":
state = "generate"
script = script_template.format(user_id=user_id, state=state)
print(f"current0 user_id={user_id}, state={state}")
loading_text = "Generating content, Usually takes 3-4 minutes, please wait..."
if state == "generate":
if not queue.empty():
queue_len = queue.qsize()
if queue_len + reply_count >= MAX_REPLIES_PER_DAY:
error_message = "Today's maximum number of replies has been reached. Please try again tomorrow."
return Template(html_template).render(idea="", error=error_message, reply_count=reply_count, button_text="Generate",loading_text=loading_text,script=script)
error_message = "There are currently {} requests being processed. If you want to queue, please write your original topic and click the Continue button and you will enter the queue.".format(queue_len)
new_state = "continue"
new_button_text = "Continue"
script = f"""
function setstate() {{
document.getElementById("user_id").value = "{user_id}";
document.getElementById("state").value = "{new_state}";
let userId = document.getElementById("user_id").value;
let state = document.getElementById("state").value;
console.log(`1 User ID: ${{userId}}, State: ${{state}}`);
document.getElementById("topic").value = "{topic}";
}}
window.onload = setstate;
"""
print(f"current1 user_id={user_id}, state={new_state}")
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+1)*3}-{(queue_len+1)*4} minutes, please wait...",script=script)
queue.put([user_id,topic])
new_state = "generate"
new_button_text = "Generate"
queue_len = queue.qsize()
script = script_template.format(user_id=user_id, state=new_state)
print(f"current2 user_id={user_id}, state={new_state}")
# 判断当前是否轮到该用户,如果没轮到则一直等待到轮到为止
print(queue.queue[0], [user_id,topic])
while queue.queue[0] != [user_id,topic]:
time.sleep(10)
continue
try:
with lock:
logging.info(f"Processing request for topic: {topic}")
start_time = time.time()
error_message = None
idea = ""
time_taken = 0
# 检查是否超过每日最大回复次数
if reply_count >= MAX_REPLIES_PER_DAY:
error_message = "Today's maximum number of replies has been reached. Please try again tomorrow."
logging.info(f"Today's maximum number of replies has been reached. Please try again tomorrow.")
try:
main_llm, cheap_llm = get_llms()
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)
print(f"begin to generate idea of topic {topic}")
idea, related_experiments, entities, idea_chain, ideas, trend, future, human, year = deep_research_agent.generate_idea_with_chain(topic)
idea = fix_markdown(idea)
idea = markdown.markdown(idea)
# 更新每日回复次数
reply_count += 1
end_time = time.time()
time_taken = round(end_time - start_time, 2)
logging.info(f"Successfully generated idea for topic: {topic}")
except Exception as e:
end_time = time.time()
time_taken = round(end_time - start_time, 2)
logging.error(f"Failed to generate idea for topic: {topic}, Error: {str(e)}")
error_message = str(e)
# 从队列中移除当前用户
finished = queue.get()
print(f"finished: {finished}, still in queue: {queue.qsize()}")
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,script=script)
except Exception as e:
error_message = str(e)
queue.get()
return Template(html_template).render(idea="", error=error_message, reply_count=reply_count, button_text="Generate",loading_text=loading_text,script=script)