assistant.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from sqlmodel import select
  2. from sqlalchemy.ext.asyncio import AsyncSession
  3. from app.exceptions.exception import ResourceNotFoundError
  4. from app.models.assistant import Assistant, AssistantUpdate, AssistantCreate
  5. from app.models.token_relation import RelationType
  6. from app.providers.auth_provider import auth_policy
  7. from app.schemas.common import DeleteResponse
  8. from app.utils import revise_tool_names
  9. class AssistantService:
  10. @staticmethod
  11. async def create_assistant(*, session: AsyncSession, body: AssistantCreate, token_id: str = None) -> Assistant:
  12. revise_tool_names(body.tools)
  13. db_assistant = Assistant.model_validate(body.model_dump(by_alias=True))
  14. session.add(db_assistant)
  15. auth_policy.insert_token_rel(
  16. session=session, token_id=token_id, relation_type=RelationType.Assistant, relation_id=db_assistant.id
  17. )
  18. await session.commit()
  19. await session.refresh(db_assistant)
  20. return db_assistant
  21. @staticmethod
  22. async def modify_assistant(*, session: AsyncSession, assistant_id: str, body: AssistantUpdate) -> Assistant:
  23. revise_tool_names(body.tools)
  24. db_assistant = await AssistantService.get_assistant(session=session, assistant_id=assistant_id)
  25. update_data = body.dict(exclude_unset=True)
  26. for key, value in update_data.items():
  27. setattr(db_assistant, key, value)
  28. session.add(db_assistant)
  29. await session.commit()
  30. await session.refresh(db_assistant)
  31. return db_assistant
  32. @staticmethod
  33. async def delete_assistant(
  34. *,
  35. session: AsyncSession,
  36. assistant_id: str,
  37. ) -> DeleteResponse:
  38. db_ass = await AssistantService.get_assistant(session=session, assistant_id=assistant_id)
  39. await session.delete(db_ass)
  40. await auth_policy.delete_token_rel(
  41. session=session, relation_type=RelationType.Assistant, relation_id=assistant_id
  42. )
  43. await session.commit()
  44. return DeleteResponse(id=assistant_id, object="assistant.deleted", deleted=True)
  45. @staticmethod
  46. async def get_assistant(*, session: AsyncSession, assistant_id: str) -> Assistant:
  47. statement = select(Assistant).where(Assistant.id == assistant_id)
  48. result = await session.execute(statement)
  49. assistant = result.scalars().one_or_none()
  50. if assistant is None:
  51. raise ResourceNotFoundError(message="Assistant not found")
  52. return assistant
  53. @staticmethod
  54. def get_assistant_sync(*, session: AsyncSession, assistant_id: str) -> Assistant:
  55. statement = select(Assistant).where(Assistant.id == assistant_id)
  56. result = session.execute(statement)
  57. assistant = result.scalars().one_or_none()
  58. if assistant is None:
  59. raise ResourceNotFoundError(message="Assistant not found")
  60. return assistant