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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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, obj):
  14. if hasattr(obj, "get_secret_value") and callable(obj.get_secret_value):
  15. return obj.get_secret_value()
  16. return super().default(obj)
  17. class DatabaseManager:
  18. _init_lock = threading.Lock()
  19. def __init__(self, engine_uri: str, base_dir: Optional[Union[str, Path]] = None) -> None:
  20. """
  21. Initialize DatabaseManager with database connection settings.
  22. Does not perform any database operations.
  23. Args:
  24. engine_uri: Database connection URI (e.g. sqlite:///db.sqlite3)
  25. base_dir: Base directory for migration files. If None, uses current directory
  26. """
  27. connection_args = {"check_same_thread": True} if "sqlite" in engine_uri else {}
  28. if base_dir is not None and isinstance(base_dir, str):
  29. base_dir = Path(base_dir)
  30. self.engine = create_engine(
  31. engine_uri, connect_args=connection_args, json_serializer=lambda obj: json.dumps(obj, cls=CustomJSONEncoder)
  32. )
  33. self.schema_manager = SchemaManager(
  34. engine=self.engine,
  35. base_dir=base_dir,
  36. )
  37. def _should_auto_upgrade(self) -> bool:
  38. """
  39. Check if auto upgrade should run based on schema differences
  40. """
  41. needs_upgrade, _ = self.schema_manager.check_schema_status()
  42. return needs_upgrade
  43. def initialize_database(self, auto_upgrade: bool = False, force_init_alembic: bool = True) -> Response:
  44. """
  45. Initialize database and migrations in the correct order.
  46. Args:
  47. auto_upgrade: If True, automatically generate and apply migrations for schema changes
  48. force_init_alembic: If True, reinitialize alembic configuration even if it exists
  49. """
  50. if not self._init_lock.acquire(blocking=False):
  51. return Response(message="Database initialization already in progress", status=False)
  52. try:
  53. # Enable foreign key constraints for SQLite
  54. if "sqlite" in str(self.engine.url):
  55. with self.engine.connect() as conn:
  56. conn.execute(text("PRAGMA foreign_keys=ON"))
  57. inspector = inspect(self.engine)
  58. tables_exist = inspector.get_table_names()
  59. if not tables_exist:
  60. logger.info("Creating database tables...")
  61. SQLModel.metadata.create_all(self.engine)
  62. if self.schema_manager.initialize_migrations(force=force_init_alembic):
  63. return Response(message="Database initialized successfully", status=True)
  64. return Response(message="Failed to initialize migrations", status=False)
  65. # Handle existing database
  66. if auto_upgrade or self._should_auto_upgrade():
  67. logger.info("Checking database schema...")
  68. if self.schema_manager.ensure_schema_up_to_date():
  69. return Response(message="Database schema is up to date", status=True)
  70. return Response(message="Database upgrade failed", status=False)
  71. return Response(message="Database is ready", status=True)
  72. except Exception as e:
  73. error_msg = f"Database initialization failed: {str(e)}"
  74. logger.error(error_msg)
  75. return Response(message=error_msg, status=False)
  76. finally:
  77. self._init_lock.release()
  78. def reset_db(self, recreate_tables: bool = True) -> Response:
  79. """
  80. Reset the database by dropping all tables and optionally recreating them.
  81. Args:
  82. recreate_tables (bool): If True, recreates the tables after dropping them.
  83. Set to False if you want to call create_db_and_tables() separately.
  84. """
  85. if not self._init_lock.acquire(blocking=False):
  86. logger.warning("Database reset already in progress")
  87. return Response(message="Database reset already in progress", status=False, data=None)
  88. try:
  89. # Dispose existing connections
  90. self.engine.dispose()
  91. with Session(self.engine) as session:
  92. try:
  93. # Disable foreign key checks for SQLite
  94. if "sqlite" in str(self.engine.url):
  95. session.exec(text("PRAGMA foreign_keys=OFF")) # type: ignore
  96. # Drop all tables
  97. SQLModel.metadata.drop_all(self.engine)
  98. logger.info("All tables dropped successfully")
  99. # Re-enable foreign key checks for SQLite
  100. if "sqlite" in str(self.engine.url):
  101. session.exec(text("PRAGMA foreign_keys=ON")) # type: ignore
  102. session.commit()
  103. except Exception as e:
  104. session.rollback()
  105. raise e
  106. finally:
  107. session.close()
  108. self._init_lock.release()
  109. if recreate_tables:
  110. logger.info("Recreating tables...")
  111. self.initialize_database(auto_upgrade=False, force_init_alembic=True)
  112. return Response(
  113. message="Database reset successfully" if recreate_tables else "Database tables dropped successfully",
  114. status=True,
  115. data=None,
  116. )
  117. except Exception as e:
  118. error_msg = f"Error while resetting database: {str(e)}"
  119. logger.error(error_msg)
  120. return Response(message=error_msg, status=False, data=None)
  121. finally:
  122. if self._init_lock.locked():
  123. self._init_lock.release()
  124. logger.info("Database reset lock released")
  125. def upsert(self, model: BaseDBModel, return_json: bool = True) -> Response:
  126. """Create or update an entity
  127. Args:
  128. model (SQLModel): The model instance to create or update
  129. return_json (bool, optional): If True, returns the model as a dictionary.
  130. If False, returns the SQLModel instance. Defaults to True.
  131. Returns:
  132. Response: Contains status, message and data (either dict or SQLModel based on return_json)
  133. """
  134. status = True
  135. model_class = type(model)
  136. existing_model = None
  137. with Session(self.engine) as session:
  138. try:
  139. existing_model = session.exec(select(model_class).where(model_class.id == model.id)).first()
  140. if existing_model:
  141. model.updated_at = datetime.now()
  142. for key, value in model.model_dump().items():
  143. setattr(existing_model, key, value)
  144. model = existing_model
  145. session.add(model)
  146. else:
  147. session.add(model)
  148. session.commit()
  149. session.refresh(model)
  150. except Exception as e:
  151. session.rollback()
  152. logger.error("Error while updating/creating " + str(model_class.__name__) + ": " + str(e))
  153. status = False
  154. return Response(
  155. message=(
  156. f"{model_class.__name__} Updated Successfully"
  157. if existing_model
  158. else f"{model_class.__name__} Created Successfully"
  159. ),
  160. status=status,
  161. data=model.model_dump() if return_json else model,
  162. )
  163. def _model_to_dict(self, model_obj):
  164. return {col.name: getattr(model_obj, col.name) for col in model_obj.__table__.columns}
  165. def get(
  166. self,
  167. model_class: type[BaseDBModel],
  168. filters: dict | None = None,
  169. return_json: bool = False,
  170. order: str = "desc",
  171. ):
  172. """List entities"""
  173. with Session(self.engine) as session:
  174. result = []
  175. status = True
  176. status_message = ""
  177. try:
  178. statement = select(model_class) # type: ignore
  179. if filters:
  180. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  181. statement = statement.where(and_(*conditions))
  182. if hasattr(model_class, "created_at") and order:
  183. order_by_clause = getattr(model_class.created_at, order)() # Dynamically apply asc/desc
  184. statement = statement.order_by(order_by_clause)
  185. items = session.exec(statement).all()
  186. result = [self._model_to_dict(item) if return_json else item for item in items]
  187. status_message = f"{model_class.__name__} Retrieved Successfully"
  188. except Exception as e:
  189. session.rollback()
  190. status = False
  191. status_message = f"Error while fetching {model_class.__name__}"
  192. logger.error("Error while getting items: " + str(model_class.__name__) + " " + str(e))
  193. return Response(message=status_message, status=status, data=result)
  194. def delete(self, model_class: type[BaseDBModel], filters: dict | None = None) -> Response:
  195. """Delete an entity"""
  196. status_message = ""
  197. status = True
  198. with Session(self.engine) as session:
  199. try:
  200. if "sqlite" in str(self.engine.url):
  201. session.exec(text("PRAGMA foreign_keys=ON")) # type: ignore
  202. statement = select(model_class) # type: ignore
  203. if filters:
  204. conditions = [getattr(model_class, col) == value for col, value in filters.items()]
  205. statement = statement.where(and_(*conditions))
  206. rows = session.exec(statement).all()
  207. if rows:
  208. for row in rows:
  209. session.delete(row)
  210. session.commit()
  211. status_message = f"{model_class.__name__} Deleted Successfully"
  212. else:
  213. status_message = "Row not found"
  214. logger.info(f"Row with filters {filters} not found")
  215. except exc.IntegrityError as e:
  216. session.rollback()
  217. status = False
  218. status_message = f"Integrity error: The {model_class.__name__} is linked to another entity and cannot be deleted. {e}"
  219. # Log the specific integrity error
  220. logger.error(status_message)
  221. except Exception as e:
  222. session.rollback()
  223. status = False
  224. status_message = f"Error while deleting: {e}"
  225. logger.error(status_message)
  226. return Response(message=status_message, status=status, data=None)
  227. async def import_team(
  228. self, team_config: Union[str, Path, dict], user_id: str, check_exists: bool = False
  229. ) -> Response:
  230. try:
  231. # Load config if path provided
  232. if isinstance(team_config, (str, Path)):
  233. config = await TeamManager.load_from_file(team_config)
  234. else:
  235. config = team_config
  236. # Check existence if requested
  237. if check_exists:
  238. existing = await self._check_team_exists(config, user_id)
  239. if existing:
  240. return Response(
  241. message="Identical team configuration already exists", status=True, data={"id": existing.id}
  242. )
  243. # Store in database
  244. team_db = Team(user_id=user_id, component=config)
  245. result = self.upsert(team_db)
  246. return result
  247. except Exception as e:
  248. logger.error(f"Failed to import team: {str(e)}")
  249. return Response(message=str(e), status=False)
  250. async def import_teams_from_directory(
  251. self, directory: Union[str, Path], user_id: str, check_exists: bool = False
  252. ) -> Response:
  253. """
  254. Import all team configurations from a directory.
  255. Args:
  256. directory: Path to directory containing team configs
  257. user_id: User ID to associate with imported teams
  258. check_exists: Whether to check for existing teams
  259. Returns:
  260. Response containing import results for all files
  261. """
  262. try:
  263. # Load all configs from directory
  264. configs = await TeamManager.load_from_directory(directory)
  265. results = []
  266. for config in configs:
  267. try:
  268. result = await self.import_team(team_config=config, user_id=user_id, check_exists=check_exists)
  269. # Add result info
  270. results.append(
  271. {
  272. "status": result.status,
  273. "message": result.message,
  274. "id": result.data.get("id") if result.data and result.data is not None else None,
  275. }
  276. )
  277. except Exception as e:
  278. logger.error(f"Failed to import team config: {str(e)}")
  279. results.append({"status": False, "message": str(e), "id": None})
  280. return Response(message="Directory import complete", status=True, data=results)
  281. except Exception as e:
  282. logger.error(f"Failed to import directory: {str(e)}")
  283. return Response(message=str(e), status=False)
  284. async def _check_team_exists(self, config: dict, user_id: str) -> Optional[Team]:
  285. """Check if identical team config already exists"""
  286. response = self.get(Team, {"user_id": user_id})
  287. teams = response.data if response.status and response.data is not None else []
  288. for team in teams:
  289. if team.component == config:
  290. return team
  291. return None
  292. async def close(self):
  293. """Close database connections and cleanup resources"""
  294. logger.info("Closing database connections...")
  295. try:
  296. # Dispose of the SQLAlchemy engine
  297. self.engine.dispose()
  298. logger.info("Database connections closed successfully")
  299. except Exception as e:
  300. logger.error(f"Error closing database connections: {str(e)}")
  301. raise