execution.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """聊天、审批恢复和定时执行共用的准入与运行装配。"""
  2. import asyncio
  3. from dataclasses import dataclass
  4. from api import concurrency
  5. from billing import guard
  6. from db import chat_store
  7. @dataclass
  8. class Admission:
  9. session: concurrency.SessionLease
  10. slot: concurrency.TaskSlot
  11. def release(self):
  12. self.slot.release()
  13. self.session.release()
  14. async def admit(user_name: str, session_id: str) -> Admission:
  15. session = concurrency.acquire_session(session_id)
  16. slot = None
  17. try:
  18. slot = concurrency.acquire_task_slot(user_name)
  19. if not await asyncio.to_thread(chat_store.get_session_for_user, session_id, user_name):
  20. raise concurrency.SessionMissingError("会话不存在")
  21. await asyncio.to_thread(guard.precheck, user_name)
  22. return Admission(session, slot)
  23. except BaseException:
  24. if slot:
  25. slot.release()
  26. session.release()
  27. raise
  28. async def build_stream(admission: Admission, *, agent=None, **kwargs):
  29. from agents import agent_registry
  30. from api.sse_core import ChatStream, StreamRequest
  31. try:
  32. if agent is None:
  33. agent = await asyncio.to_thread(agent_registry.get_agent)
  34. graph_config = kwargs["config"]
  35. graph_config.setdefault("configurable", {}).update(
  36. workspace_user=kwargs["user_name"], workspace_session=kwargs["session_id"],
  37. )
  38. return ChatStream(StreamRequest(agent=agent, slot=admission.slot,
  39. session_lease=admission.session, **kwargs))
  40. except BaseException:
  41. admission.release()
  42. raise