You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

db_manager.py 14 kB

Add Token Streaming in AGS , Support Env variables (#5659) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> This PR has 3 main improvements. - Token streaming - Adds support for environment variables in the app settings - Updates AGS to persist Gallery entry in db. ## Adds Token Streaming in AGS. Agentchat now supports streaming of tokens via `ModelClientStreamingChunkEvent `. This PR is to track progress on supporting that in the AutoGen Studio UI. If `model_client_stream` is enabled in an assitant agent, then token will be streamed in UI. ```python streaming_assistant = AssistantAgent( name="assistant", model_client=model_client, system_message="You are a helpful assistant.", model_client_stream=True, # Enable streaming tokens. ) ``` https://github.com/user-attachments/assets/74d43d78-6359-40c3-a78e-c84dcb5e02a1 ## Env Variables Also adds support for env variables in AGS Settings You can set env variables that are loaded just before a team is run. Handy to set variable to be used by tools etc. <img width="1291" alt="image" src="https://github.com/user-attachments/assets/437b9d90-ccee-42f7-be5d-94ab191afd67" /> > Note: the set variables are available to the server process. <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> Closes #5627 Closes #5662 Closes #5619 ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed.
1 year ago
Add Token Streaming in AGS , Support Env variables (#5659) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> This PR has 3 main improvements. - Token streaming - Adds support for environment variables in the app settings - Updates AGS to persist Gallery entry in db. ## Adds Token Streaming in AGS. Agentchat now supports streaming of tokens via `ModelClientStreamingChunkEvent `. This PR is to track progress on supporting that in the AutoGen Studio UI. If `model_client_stream` is enabled in an assitant agent, then token will be streamed in UI. ```python streaming_assistant = AssistantAgent( name="assistant", model_client=model_client, system_message="You are a helpful assistant.", model_client_stream=True, # Enable streaming tokens. ) ``` https://github.com/user-attachments/assets/74d43d78-6359-40c3-a78e-c84dcb5e02a1 ## Env Variables Also adds support for env variables in AGS Settings You can set env variables that are loaded just before a team is run. Handy to set variable to be used by tools etc. <img width="1291" alt="image" src="https://github.com/user-attachments/assets/437b9d90-ccee-42f7-be5d-94ab191afd67" /> > Note: the set variables are available to the server process. <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> Closes #5627 Closes #5662 Closes #5619 ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed.
1 year ago
Add Token Streaming in AGS , Support Env variables (#5659) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> This PR has 3 main improvements. - Token streaming - Adds support for environment variables in the app settings - Updates AGS to persist Gallery entry in db. ## Adds Token Streaming in AGS. Agentchat now supports streaming of tokens via `ModelClientStreamingChunkEvent `. This PR is to track progress on supporting that in the AutoGen Studio UI. If `model_client_stream` is enabled in an assitant agent, then token will be streamed in UI. ```python streaming_assistant = AssistantAgent( name="assistant", model_client=model_client, system_message="You are a helpful assistant.", model_client_stream=True, # Enable streaming tokens. ) ``` https://github.com/user-attachments/assets/74d43d78-6359-40c3-a78e-c84dcb5e02a1 ## Env Variables Also adds support for env variables in AGS Settings You can set env variables that are loaded just before a team is run. Handy to set variable to be used by tools etc. <img width="1291" alt="image" src="https://github.com/user-attachments/assets/437b9d90-ccee-42f7-be5d-94ab191afd67" /> > Note: the set variables are available to the server process. <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> Closes #5627 Closes #5662 Closes #5619 ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed.
1 year ago
Add Token Streaming in AGS , Support Env variables (#5659) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> This PR has 3 main improvements. - Token streaming - Adds support for environment variables in the app settings - Updates AGS to persist Gallery entry in db. ## Adds Token Streaming in AGS. Agentchat now supports streaming of tokens via `ModelClientStreamingChunkEvent `. This PR is to track progress on supporting that in the AutoGen Studio UI. If `model_client_stream` is enabled in an assitant agent, then token will be streamed in UI. ```python streaming_assistant = AssistantAgent( name="assistant", model_client=model_client, system_message="You are a helpful assistant.", model_client_stream=True, # Enable streaming tokens. ) ``` https://github.com/user-attachments/assets/74d43d78-6359-40c3-a78e-c84dcb5e02a1 ## Env Variables Also adds support for env variables in AGS Settings You can set env variables that are loaded just before a team is run. Handy to set variable to be used by tools etc. <img width="1291" alt="image" src="https://github.com/user-attachments/assets/437b9d90-ccee-42f7-be5d-94ab191afd67" /> > Note: the set variables are available to the server process. <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> Closes #5627 Closes #5662 Closes #5619 ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed.
1 year ago
Add Token Streaming in AGS , Support Env variables (#5659) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> This PR has 3 main improvements. - Token streaming - Adds support for environment variables in the app settings - Updates AGS to persist Gallery entry in db. ## Adds Token Streaming in AGS. Agentchat now supports streaming of tokens via `ModelClientStreamingChunkEvent `. This PR is to track progress on supporting that in the AutoGen Studio UI. If `model_client_stream` is enabled in an assitant agent, then token will be streamed in UI. ```python streaming_assistant = AssistantAgent( name="assistant", model_client=model_client, system_message="You are a helpful assistant.", model_client_stream=True, # Enable streaming tokens. ) ``` https://github.com/user-attachments/assets/74d43d78-6359-40c3-a78e-c84dcb5e02a1 ## Env Variables Also adds support for env variables in AGS Settings You can set env variables that are loaded just before a team is run. Handy to set variable to be used by tools etc. <img width="1291" alt="image" src="https://github.com/user-attachments/assets/437b9d90-ccee-42f7-be5d-94ab191afd67" /> > Note: the set variables are available to the server process. <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> Closes #5627 Closes #5662 Closes #5619 ## Checks - [ ] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [ ] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [ ] I've made sure all auto checks have passed.
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import threading
  2. from datetime import datetime
  3. from pathlib import Path
  4. from typing import Optional, Union
  5. from loguru import logger
  6. from sqlalchemy import exc, inspect, text
  7. from sqlmodel import Session, SQLModel, and_, create_engine, select
  8. from ..datamodel import Response, Team
  9. from ..teammanager import TeamManager
  10. from .schema_manager import SchemaManager
  11. class DatabaseManager:
  12. _init_lock = threading.Lock()
  13. def __init__(self, engine_uri: str, base_dir: Optional[Path] = None):
  14. """
  15. Initialize DatabaseManager with database connection settings.
  16. Does not perform any database operations.
  17. Args:
  18. engine_uri: Database connection URI (e.g. sqlite:///db.sqlite3)
  19. base_dir: Base directory for migration files. If None, uses current directory
  20. """
  21. connection_args = {"check_same_thread": True} if "sqlite" in engine_uri else {}
  22. self.engine = create_engine(engine_uri, connect_args=connection_args)
  23. self.schema_manager = SchemaManager(
  24. engine=self.engine,
  25. base_dir=base_dir,
  26. )
  27. def _should_auto_upgrade(self) -> bool:
  28. """
  29. Check if auto upgrade should run based on schema differences
  30. """
  31. needs_upgrade, _ = self.schema_manager.check_schema_status()
  32. return needs_upgrade
  33. def initialize_database(self, auto_upgrade: bool = False, force_init_alembic: bool = True) -> Response:
  34. """
  35. Initialize database and migrations in the correct order.
  36. Args:
  37. auto_upgrade: If True, automatically generate and apply migrations for schema changes
  38. force_init_alembic: If True, reinitialize alembic configuration even if it exists
  39. """
  40. if not self._init_lock.acquire(blocking=False):
  41. return Response(message="Database initialization already in progress", status=False)
  42. try:
  43. # Enable foreign key constraints for SQLite
  44. if "sqlite" in str(self.engine.url):
  45. with self.engine.connect() as conn:
  46. conn.execute(text("PRAGMA foreign_keys=ON"))
  47. inspector = inspect(self.engine)
  48. tables_exist = inspector.get_table_names()
  49. if not tables_exist:
  50. logger.info("Creating database tables...")
  51. SQLModel.metadata.create_all(self.engine)
  52. if self.schema_manager.initialize_migrations(force=force_init_alembic):
  53. return Response(message="Database initialized successfully", status=True)
  54. return Response(message="Failed to initialize migrations", status=False)
  55. # Handle existing database
  56. if auto_upgrade or self._should_auto_upgrade():
  57. logger.info("Checking database schema...")
  58. if self.schema_manager.ensure_schema_up_to_date():
  59. return Response(message="Database schema is up to date", status=True)
  60. return Response(message="Database upgrade failed", status=False)
  61. return Response(message="Database is ready", status=True)
  62. except Exception as e:
  63. error_msg = f"Database initialization failed: {str(e)}"
  64. logger.error(error_msg)
  65. return Response(message=error_msg, status=False)
  66. finally:
  67. self._init_lock.release()
  68. def reset_db(self, recreate_tables: bool = True):
  69. """
  70. Reset the database by dropping all tables and optionally recreating them.
  71. Args:
  72. recreate_tables (bool): If True, recreates the tables after dropping them.
  73. Set to False if you want to call create_db_and_tables() separately.
  74. """
  75. if not self._init_lock.acquire(blocking=False):
  76. logger.warning("Database reset already in progress")
  77. return Response(message="Database reset already in progress", status=False, data=None)
  78. try:
  79. # Dispose existing connections
  80. self.engine.dispose()
  81. with Session(self.engine) as session:
  82. try:
  83. # Disable foreign key checks for SQLite
  84. if "sqlite" in str(self.engine.url):
  85. session.exec(text("PRAGMA foreign_keys=OFF"))
  86. # Drop all tables
  87. SQLModel.metadata.drop_all(self.engine)
  88. logger.info("All tables dropped successfully")
  89. # Re-enable foreign key checks for SQLite
  90. if "sqlite" in str(self.engine.url):
  91. session.exec(text("PRAGMA foreign_keys=ON"))
  92. session.commit()
  93. except Exception as e:
  94. session.rollback()
  95. raise e
  96. finally:
  97. session.close()
  98. self._init_lock.release()
  99. if recreate_tables:
  100. logger.info("Recreating tables...")
  101. self.initialize_database(auto_upgrade=False, force_init_alembic=True)
  102. return Response(
  103. message="Database reset successfully" if recreate_tables else "Database tables dropped successfully",
  104. status=True,
  105. data=None,
  106. )
  107. except Exception as e:
  108. error_msg = f"Error while resetting database: {str(e)}"
  109. logger.error(error_msg)
  110. return Response(message=error_msg, status=False, data=None)
  111. finally:
  112. if self._init_lock.locked():
  113. self._init_lock.release()
  114. logger.info("Database reset lock released")
  115. def upsert(self, model: SQLModel, return_json: bool = True) -> Response:
  116. """Create or update an entity
  117. Args:
  118. model (SQLModel): The model instance to create or update
  119. return_json (bool, optional): If True, returns the model as a dictionary.
  120. If False, returns the SQLModel instance. Defaults to True.
  121. Returns:
  122. Response: Contains status, message and data (either dict or SQLModel based on return_json)
  123. """
  124. status = True
  125. model_class = type(model)
  126. existing_model = None
  127. with Session(self.engine) as session:
  128. try:
  129. existing_model = session.exec(select(model_class).where(model_class.id == model.id)).first()
  130. if existing_model:
  131. model.updated_at = datetime.now()
  132. for key, value in model.model_dump().items():
  133. setattr(existing_model, key, value)
  134. model = existing_model # Use the updated existing model
  135. session.add(model)
  136. else:
  137. session.add(model)
  138. session.commit()
  139. session.refresh(model)
  140. except Exception as e:
  141. session.rollback()
  142. logger.error("Error while updating/creating " + str(model_class.__name__) + ": " + str(e))
  143. status = False
  144. return Response(
  145. message=(
  146. f"{model_class.__name__} Updated Successfully"
  147. if existing_model
  148. else f"{model_class.__name__} Created Successfully"
  149. ),
  150. status=status,
  151. data=model.model_dump() if return_json else model,
  152. )
  153. def _model_to_dict(self, model_obj):
  154. return {col.name: getattr(model_obj, col.name) for col in model_obj.__table__.columns}
  155. def get(
  156. self,
  157. model_class: SQLModel,
  158. filters: dict = None,
  159. return_json: bool = False,
  160. order: str = "desc",
  161. ):
  162. """List entities"""
  163. with Session(self.engine) as session:
  164. result = []
  165. status = True
  166. status_message = ""
  167. try:
  168. statement = select(model_class)
  169. if filters:
  170. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  171. statement = statement.where(and_(*conditions))
  172. if hasattr(model_class, "created_at") and order:
  173. order_by_clause = getattr(model_class.created_at, order)() # Dynamically apply asc/desc
  174. statement = statement.order_by(order_by_clause)
  175. items = session.exec(statement).all()
  176. result = [self._model_to_dict(item) if return_json else item for item in items]
  177. status_message = f"{model_class.__name__} Retrieved Successfully"
  178. except Exception as e:
  179. session.rollback()
  180. status = False
  181. status_message = f"Error while fetching {model_class.__name__}"
  182. logger.error("Error while getting items: " + str(model_class.__name__) + " " + str(e))
  183. return Response(message=status_message, status=status, data=result)
  184. def delete(self, model_class: SQLModel, filters: dict = None) -> Response:
  185. """Delete an entity"""
  186. status_message = ""
  187. status = True
  188. with Session(self.engine) as session:
  189. try:
  190. if "sqlite" in str(self.engine.url):
  191. session.exec(text("PRAGMA foreign_keys=ON"))
  192. statement = select(model_class)
  193. if filters:
  194. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  195. statement = statement.where(and_(*conditions))
  196. rows = session.exec(statement).all()
  197. if rows:
  198. for row in rows:
  199. session.delete(row)
  200. session.commit()
  201. status_message = f"{model_class.__name__} Deleted Successfully"
  202. else:
  203. status_message = "Row not found"
  204. logger.info(f"Row with filters {filters} not found")
  205. except exc.IntegrityError as e:
  206. session.rollback()
  207. status = False
  208. status_message = f"Integrity error: The {model_class.__name__} is linked to another entity and cannot be deleted. {e}"
  209. # Log the specific integrity error
  210. logger.error(status_message)
  211. except Exception as e:
  212. session.rollback()
  213. status = False
  214. status_message = f"Error while deleting: {e}"
  215. logger.error(status_message)
  216. return Response(message=status_message, status=status, data=None)
  217. async def import_team(
  218. self, team_config: Union[str, Path, dict], user_id: str, check_exists: bool = False
  219. ) -> Response:
  220. try:
  221. # Load config if path provided
  222. if isinstance(team_config, (str, Path)):
  223. config = await TeamManager.load_from_file(team_config)
  224. else:
  225. config = team_config
  226. # Check existence if requested
  227. if check_exists:
  228. existing = await self._check_team_exists(config, user_id)
  229. if existing:
  230. return Response(
  231. message="Identical team configuration already exists", status=True, data={"id": existing.id}
  232. )
  233. # Store in database
  234. team_db = Team(user_id=user_id, component=config)
  235. result = self.upsert(team_db)
  236. return result
  237. except Exception as e:
  238. logger.error(f"Failed to import team: {str(e)}")
  239. return Response(message=str(e), status=False)
  240. async def import_teams_from_directory(
  241. self, directory: Union[str, Path], user_id: str, check_exists: bool = False
  242. ) -> Response:
  243. """
  244. Import all team configurations from a directory.
  245. Args:
  246. directory: Path to directory containing team configs
  247. user_id: User ID to associate with imported teams
  248. check_exists: Whether to check for existing teams
  249. Returns:
  250. Response containing import results for all files
  251. """
  252. try:
  253. # Load all configs from directory
  254. configs = await TeamManager.load_from_directory(directory)
  255. results = []
  256. for config in configs:
  257. try:
  258. result = await self.import_team(team_config=config, user_id=user_id, check_exists=check_exists)
  259. # Add result info
  260. results.append(
  261. {
  262. "status": result.status,
  263. "message": result.message,
  264. "id": result.data.get("id") if result.status else None,
  265. }
  266. )
  267. except Exception as e:
  268. logger.error(f"Failed to import team config: {str(e)}")
  269. results.append({"status": False, "message": str(e), "id": None})
  270. return Response(message="Directory import complete", status=True, data=results)
  271. except Exception as e:
  272. logger.error(f"Failed to import directory: {str(e)}")
  273. return Response(message=str(e), status=False)
  274. async def _check_team_exists(self, config: dict, user_id: str) -> Optional[Team]:
  275. """Check if identical team config already exists"""
  276. teams = self.get(Team, {"user_id": user_id}).data
  277. for team in teams:
  278. if team.component == config:
  279. return team
  280. return None
  281. async def close(self):
  282. """Close database connections and cleanup resources"""
  283. logger.info("Closing database connections...")
  284. try:
  285. # Dispose of the SQLAlchemy engine
  286. self.engine.dispose()
  287. logger.info("Database connections closed successfully")
  288. except Exception as e:
  289. logger.error(f"Error closing database connections: {str(e)}")
  290. raise