Download app/runs.py from simonu5/TriChat: direct link, hf CLI and curl.
- Browser
- Download file 3.24 kB
-
https://huggingface.co/spaces/simonu5/TriChat/resolve/main/app/runs.py
- Command line
-
hf download hf://spaces/simonu5/TriChat/app/runs.py
-
curl -L -o runs.py https://huggingface.co/spaces/simonu5/TriChat/resolve/main/app/runs.py
3.24 kB
| """背景執行:agent 在伺服器上跑,和瀏覽器連線脫鉤。 | |
| 關掉頁面、斷網、重新整理都不會中斷;重新打開對話時從頭重播這次執行的事件並接著看。 | |
| 只有按「停止」(POST /api/conversations/{id}/stop)才會中止。 | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| log = logging.getLogger("runs") | |
| KEEP_FINISHED = 600 # 結束後保留事件 10 分鐘,讓晚回來的頁面也能看到結尾 | |
| PING_EVERY = 15 # 串流保活,避免代理斷開閒置連線 | |
| class Run: | |
| def __init__(self, cid: str, user_text: str, base_count: int): | |
| self.cid, self.user_text, self.base_count = cid, user_text, base_count | |
| self.events: list[dict] = [] | |
| self.done = False | |
| self.started = time.time() | |
| self.cond = asyncio.Condition() | |
| self.task: asyncio.Task | None = None | |
| async def push(self, ev: dict): | |
| async with self.cond: | |
| self.events.append(ev) | |
| self.cond.notify_all() | |
| async def finish(self): | |
| async with self.cond: | |
| self.done = True | |
| self.cond.notify_all() | |
| async def follow(self, start: int = 0): | |
| """逐一 yield 事件;沒有新事件時每 PING_EVERY 秒 yield None 當保活。""" | |
| i = max(0, start) | |
| while True: | |
| async with self.cond: | |
| if i >= len(self.events) and not self.done: | |
| try: | |
| await asyncio.wait_for(self.cond.wait(), PING_EVERY) | |
| except asyncio.TimeoutError: | |
| pass | |
| batch, finished = self.events[i:], self.done | |
| if not batch and not finished: | |
| yield None | |
| continue | |
| for ev in batch: | |
| yield ev | |
| i += len(batch) | |
| if finished and i >= len(self.events): | |
| return | |
| runs: dict[str, Run] = {} | |
| def active(cid: str) -> Run | None: | |
| r = runs.get(cid) | |
| return r if r and not r.done else None | |
| def start(cid: str, user_text: str, base_count: int, agen_factory) -> Run: | |
| run = Run(cid, user_text, base_count) | |
| runs[cid] = run | |
| async def main(): | |
| agen = agen_factory() | |
| try: | |
| async for ev in agen: | |
| await run.push(ev) | |
| except asyncio.CancelledError: | |
| try: | |
| await agen.aclose() # 讓 agent 有機會把已生成的內容存起來 | |
| except Exception: # noqa: BLE001 | |
| pass | |
| await run.push({"type": "stopped"}) | |
| except Exception as e: # noqa: BLE001 | |
| log.exception("agent error") | |
| await run.push({"type": "error", "message": f"{type(e).__name__}: {e}"}) | |
| finally: | |
| await run.finish() | |
| asyncio.get_running_loop().call_later( | |
| KEEP_FINISHED, lambda: runs.pop(cid, None) if runs.get(cid) is run else None) | |
| run.task = asyncio.create_task(main()) | |
| return run | |
| def stop(cid: str) -> bool: | |
| r = active(cid) | |
| if r and r.task: | |
| r.task.cancel() | |
| return True | |
| return False | |
| async def stop_all(): | |
| for r in list(runs.values()): | |
| if r.task and not r.done: | |
| r.task.cancel() | |