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 15 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
Enable Auth in AGS (#5928) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- 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? https://github.com/user-attachments/assets/b649053b-c377-40c7-aa51-ee64af766fc2 <img width="100%" alt="image" src="https://github.com/user-attachments/assets/03ba1df5-c9a2-4734-b6a2-0eb97ec0b0e0" /> ## Authentication This PR implements an experimental authentication feature to enable personalized experiences (multiple users). Currently, only GitHub authentication is supported. You can extend the base authentication class to add support for other authentication methods. By default authenticatio is disabled and only enabled when you pass in the `--auth-config` argument when running the application. ### Enable GitHub Authentication To enable GitHub authentication, create a `auth.yaml` file in your app directory: ```yaml type: github jwt_secret: "your-secret-key" token_expiry_minutes: 60 github: client_id: "your-github-client-id" client_secret: "your-github-client-secret" callback_url: "http://localhost:8081/api/auth/callback" scopes: ["user:email"] ``` Please see the documentation on [GitHub OAuth](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authenticating-to-the-rest-api-with-an-oauth-app) for more details on obtaining the `client_id` and `client_secret`. To pass in this configuration you can use the `--auth-config` argument when running the application: ```bash autogenstudio ui --auth-config /path/to/auth.yaml ``` Or set the environment variable: ```bash export AUTOGENSTUDIO_AUTH_CONFIG="/path/to/auth.yaml" ``` ```{note} - Authentication is currently experimental and may change in future releases - User data is stored in your configured database - When enabled, all API endpoints require authentication except for the authentication endpoints - WebSocket connections require the token to be passed as a query parameter (`?token=your-jwt-token`) ``` ## Related issue number <!-- For example: "Closes #1234" --> Closes #4350 ## 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. --------- Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 year ago
Enable Auth in AGS (#5928) <!-- Thank you for your contribution! Please review https://microsoft.github.io/autogen/docs/Contribute before opening a pull request. --> <!-- 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? https://github.com/user-attachments/assets/b649053b-c377-40c7-aa51-ee64af766fc2 <img width="100%" alt="image" src="https://github.com/user-attachments/assets/03ba1df5-c9a2-4734-b6a2-0eb97ec0b0e0" /> ## Authentication This PR implements an experimental authentication feature to enable personalized experiences (multiple users). Currently, only GitHub authentication is supported. You can extend the base authentication class to add support for other authentication methods. By default authenticatio is disabled and only enabled when you pass in the `--auth-config` argument when running the application. ### Enable GitHub Authentication To enable GitHub authentication, create a `auth.yaml` file in your app directory: ```yaml type: github jwt_secret: "your-secret-key" token_expiry_minutes: 60 github: client_id: "your-github-client-id" client_secret: "your-github-client-secret" callback_url: "http://localhost:8081/api/auth/callback" scopes: ["user:email"] ``` Please see the documentation on [GitHub OAuth](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authenticating-to-the-rest-api-with-an-oauth-app) for more details on obtaining the `client_id` and `client_secret`. To pass in this configuration you can use the `--auth-config` argument when running the application: ```bash autogenstudio ui --auth-config /path/to/auth.yaml ``` Or set the environment variable: ```bash export AUTOGENSTUDIO_AUTH_CONFIG="/path/to/auth.yaml" ``` ```{note} - Authentication is currently experimental and may change in future releases - User data is stored in your configured database - When enabled, all API endpoints require authentication except for the authentication endpoints - WebSocket connections require the token to be passed as a query parameter (`?token=your-jwt-token`) ``` ## Related issue number <!-- For example: "Closes #1234" --> Closes #4350 ## 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. --------- Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import json
  2. import threading
  3. from datetime import datetime
  4. from pathlib import Path
  5. from typing import Optional, Union
  6. from loguru import logger
  7. from sqlalchemy import exc, inspect, text
  8. from sqlmodel import Session, SQLModel, and_, create_engine, select
  9. from ..datamodel import BaseDBModel, Response, Team
  10. from ..teammanager import TeamManager
  11. from .schema_manager import SchemaManager
  12. class CustomJSONEncoder(json.JSONEncoder):
  13. def default(self, o):
  14. if hasattr(o, "get_secret_value") and callable(o.get_secret_value):
  15. return o.get_secret_value()
  16. # Handle datetime objects
  17. if isinstance(o, datetime):
  18. return o.isoformat()
  19. # Handle Enum objects
  20. import enum
  21. if isinstance(o, enum.Enum):
  22. return o.value
  23. return super().default(o)
  24. class DatabaseManager:
  25. _init_lock = threading.Lock()
  26. def __init__(self, engine_uri: str, base_dir: Optional[Union[str, Path]] = None) -> None:
  27. """
  28. Initialize DatabaseManager with database connection settings.
  29. Does not perform any database operations.
  30. Args:
  31. engine_uri: Database connection URI (e.g. sqlite:///db.sqlite3)
  32. base_dir: Base directory for migration files. If None, uses current directory
  33. """
  34. connection_args = {"check_same_thread": True} if "sqlite" in engine_uri else {}
  35. if base_dir is not None and isinstance(base_dir, str):
  36. base_dir = Path(base_dir)
  37. self.engine = create_engine(
  38. engine_uri, connect_args=connection_args, json_serializer=lambda obj: json.dumps(obj, cls=CustomJSONEncoder)
  39. )
  40. self.schema_manager = SchemaManager(
  41. engine=self.engine,
  42. base_dir=base_dir,
  43. )
  44. def _should_auto_upgrade(self) -> bool:
  45. """
  46. Check if auto upgrade should run based on schema differences
  47. """
  48. needs_upgrade, _ = self.schema_manager.check_schema_status()
  49. return needs_upgrade
  50. def initialize_database(self, auto_upgrade: bool = False, force_init_alembic: bool = True) -> Response:
  51. """
  52. Initialize database and migrations in the correct order.
  53. Args:
  54. auto_upgrade: If True, automatically generate and apply migrations for schema changes
  55. force_init_alembic: If True, reinitialize alembic configuration even if it exists
  56. """
  57. if not self._init_lock.acquire(blocking=False):
  58. return Response(message="Database initialization already in progress", status=False)
  59. try:
  60. # Enable foreign key constraints for SQLite
  61. if "sqlite" in str(self.engine.url):
  62. with self.engine.connect() as conn:
  63. conn.execute(text("PRAGMA foreign_keys=ON"))
  64. inspector = inspect(self.engine)
  65. tables_exist = inspector.get_table_names()
  66. if not tables_exist:
  67. logger.info("Creating database tables...")
  68. SQLModel.metadata.create_all(self.engine)
  69. if self.schema_manager.initialize_migrations(force=force_init_alembic):
  70. return Response(message="Database initialized successfully", status=True)
  71. return Response(message="Failed to initialize migrations", status=False)
  72. # Handle existing database
  73. if auto_upgrade:
  74. logger.info("Checking database schema...")
  75. if self.schema_manager.ensure_schema_up_to_date():
  76. return Response(message="Database schema is up to date", status=True)
  77. return Response(message="Database upgrade failed", status=False)
  78. elif self._should_auto_upgrade():
  79. logger.info("Schema changes detected, but auto_upgrade is disabled. Skipping migration check.")
  80. logger.info("To enable automatic migrations, set auto_upgrade=True")
  81. return Response(message="Database is ready", status=True)
  82. except Exception as e:
  83. error_msg = f"Database initialization failed: {str(e)}"
  84. logger.error(error_msg)
  85. return Response(message=error_msg, status=False)
  86. finally:
  87. self._init_lock.release()
  88. def reset_db(self, recreate_tables: bool = True) -> Response:
  89. """
  90. Reset the database by dropping all tables and optionally recreating them.
  91. Args:
  92. recreate_tables (bool): If True, recreates the tables after dropping them.
  93. Set to False if you want to call create_db_and_tables() separately.
  94. """
  95. if not self._init_lock.acquire(blocking=False):
  96. logger.warning("Database reset already in progress")
  97. return Response(message="Database reset already in progress", status=False, data=None)
  98. try:
  99. # Dispose existing connections
  100. self.engine.dispose()
  101. with Session(self.engine) as session:
  102. try:
  103. # Disable foreign key checks for SQLite
  104. if "sqlite" in str(self.engine.url):
  105. session.exec(text("PRAGMA foreign_keys=OFF")) # type: ignore
  106. # Drop all tables
  107. SQLModel.metadata.drop_all(self.engine)
  108. logger.info("All tables dropped successfully")
  109. # Re-enable foreign key checks for SQLite
  110. if "sqlite" in str(self.engine.url):
  111. session.exec(text("PRAGMA foreign_keys=ON")) # type: ignore
  112. session.commit()
  113. except Exception as e:
  114. session.rollback()
  115. raise e
  116. finally:
  117. session.close()
  118. self._init_lock.release()
  119. if recreate_tables:
  120. logger.info("Recreating tables...")
  121. self.initialize_database(auto_upgrade=False, force_init_alembic=True)
  122. return Response(
  123. message="Database reset successfully" if recreate_tables else "Database tables dropped successfully",
  124. status=True,
  125. data=None,
  126. )
  127. except Exception as e:
  128. error_msg = f"Error while resetting database: {str(e)}"
  129. logger.error(error_msg)
  130. return Response(message=error_msg, status=False, data=None)
  131. finally:
  132. if self._init_lock.locked():
  133. self._init_lock.release()
  134. logger.info("Database reset lock released")
  135. def upsert(self, model: BaseDBModel, return_json: bool = True) -> Response:
  136. """Create or update an entity
  137. Args:
  138. model (SQLModel): The model instance to create or update
  139. return_json (bool, optional): If True, returns the model as a dictionary.
  140. If False, returns the SQLModel instance. Defaults to True.
  141. Returns:
  142. Response: Contains status, message and data (either dict or SQLModel based on return_json)
  143. """
  144. status = True
  145. model_class = type(model)
  146. existing_model = None
  147. with Session(self.engine) as session:
  148. try:
  149. existing_model = session.exec(select(model_class).where(model_class.id == model.id)).first()
  150. if existing_model:
  151. model.updated_at = datetime.now()
  152. for key, value in model.model_dump().items():
  153. setattr(existing_model, key, value)
  154. model = existing_model
  155. session.add(model)
  156. else:
  157. session.add(model)
  158. session.commit()
  159. session.refresh(model)
  160. except Exception as e:
  161. session.rollback()
  162. logger.error("Error while updating/creating " + str(model_class.__name__) + ": " + str(e))
  163. status = False
  164. return Response(
  165. message=(
  166. f"{model_class.__name__} Updated Successfully"
  167. if existing_model
  168. else f"{model_class.__name__} Created Successfully"
  169. ),
  170. status=status,
  171. data=model.model_dump() if return_json else model,
  172. )
  173. def _model_to_dict(self, model_obj):
  174. return {col.name: getattr(model_obj, col.name) for col in model_obj.__table__.columns}
  175. def get(
  176. self,
  177. model_class: type[BaseDBModel],
  178. filters: dict | None = None,
  179. return_json: bool = False,
  180. order: str = "desc",
  181. ):
  182. """List entities"""
  183. with Session(self.engine) as session:
  184. result = []
  185. status = True
  186. status_message = ""
  187. try:
  188. statement = select(model_class) # type: ignore
  189. if filters:
  190. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  191. statement = statement.where(and_(*conditions))
  192. if hasattr(model_class, "created_at") and order:
  193. order_by_clause = getattr(model_class.created_at, order)() # Dynamically apply asc/desc
  194. statement = statement.order_by(order_by_clause)
  195. items = session.exec(statement).all()
  196. result = [self._model_to_dict(item) if return_json else item for item in items]
  197. status_message = f"{model_class.__name__} Retrieved Successfully"
  198. except Exception as e:
  199. session.rollback()
  200. status = False
  201. status_message = f"Error while fetching {model_class.__name__}"
  202. logger.error("Error while getting items: " + str(model_class.__name__) + " " + str(e))
  203. return Response(message=status_message, status=status, data=result)
  204. def delete(self, model_class: type[BaseDBModel], filters: dict | None = None) -> Response:
  205. """Delete an entity"""
  206. status_message = ""
  207. status = True
  208. with Session(self.engine) as session:
  209. try:
  210. if "sqlite" in str(self.engine.url):
  211. session.exec(text("PRAGMA foreign_keys=ON")) # type: ignore
  212. statement = select(model_class) # type: ignore
  213. if filters:
  214. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  215. statement = statement.where(and_(*conditions))
  216. rows = session.exec(statement).all()
  217. if rows:
  218. for row in rows:
  219. session.delete(row)
  220. session.commit()
  221. status_message = f"{model_class.__name__} Deleted Successfully"
  222. else:
  223. status_message = "Row not found"
  224. logger.info(f"Row with filters {filters} not found")
  225. except exc.IntegrityError as e:
  226. session.rollback()
  227. status = False
  228. status_message = f"Integrity error: The {model_class.__name__} is linked to another entity and cannot be deleted. {e}"
  229. # Log the specific integrity error
  230. logger.error(status_message)
  231. except Exception as e:
  232. session.rollback()
  233. status = False
  234. status_message = f"Error while deleting: {e}"
  235. logger.error(status_message)
  236. return Response(message=status_message, status=status, data=None)
  237. async def import_team(
  238. self, team_config: Union[str, Path, dict], user_id: str, check_exists: bool = False
  239. ) -> Response:
  240. try:
  241. # Load config if path provided
  242. if isinstance(team_config, (str, Path)):
  243. config = await TeamManager.load_from_file(team_config)
  244. else:
  245. config = team_config
  246. # Check existence if requested
  247. if check_exists:
  248. existing = await self._check_team_exists(config, user_id)
  249. if existing:
  250. return Response(
  251. message="Identical team configuration already exists", status=True, data={"id": existing.id}
  252. )
  253. # Store in database
  254. team_db = Team(user_id=user_id, component=config)
  255. result = self.upsert(team_db)
  256. return result
  257. except Exception as e:
  258. logger.error(f"Failed to import team: {str(e)}")
  259. return Response(message=str(e), status=False)
  260. async def import_teams_from_directory(
  261. self, directory: Union[str, Path], user_id: str, check_exists: bool = False
  262. ) -> Response:
  263. """
  264. Import all team configurations from a directory.
  265. Args:
  266. directory: Path to directory containing team configs
  267. user_id: User ID to associate with imported teams
  268. check_exists: Whether to check for existing teams
  269. Returns:
  270. Response containing import results for all files
  271. """
  272. try:
  273. # Load all configs from directory
  274. configs = await TeamManager.load_from_directory(directory)
  275. results = []
  276. for config in configs:
  277. try:
  278. result = await self.import_team(team_config=config, user_id=user_id, check_exists=check_exists)
  279. # Add result info
  280. results.append(
  281. {
  282. "status": result.status,
  283. "message": result.message,
  284. "id": result.data.get("id") if result.data and result.data is not None else None,
  285. }
  286. )
  287. except Exception as e:
  288. logger.error(f"Failed to import team config: {str(e)}")
  289. results.append({"status": False, "message": str(e), "id": None})
  290. return Response(message="Directory import complete", status=True, data=results)
  291. except Exception as e:
  292. logger.error(f"Failed to import directory: {str(e)}")
  293. return Response(message=str(e), status=False)
  294. async def _check_team_exists(self, config: dict, user_id: str) -> Optional[Team]:
  295. """Check if identical team config already exists"""
  296. response = self.get(Team, {"user_id": user_id})
  297. teams = response.data if response.status and response.data is not None else []
  298. for team in teams:
  299. if team.component == config:
  300. return team
  301. return None
  302. async def close(self):
  303. """Close database connections and cleanup resources"""
  304. logger.info("Closing database connections...")
  305. try:
  306. # Dispose of the SQLAlchemy engine
  307. self.engine.dispose()
  308. logger.info("Database connections closed successfully")
  309. except Exception as e:
  310. logger.error(f"Error closing database connections: {str(e)}")
  311. raise