363 lines
14 KiB
Python
Raw Normal View History

import json
import threading
from datetime import datetime
from pathlib import Path
from typing import Optional, Union
from loguru import logger
from sqlalchemy import exc, inspect, text
from sqlmodel import Session, SQLModel, and_, create_engine, select
from ..datamodel import Response, Team
from ..teammanager import TeamManager
from .schema_manager import SchemaManager
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, "get_secret_value") and callable(obj.get_secret_value):
return obj.get_secret_value()
return super().default(obj)
class DatabaseManager:
_init_lock = threading.Lock()
def __init__(self, engine_uri: str, base_dir: Optional[Union[str, Path]] = None) -> None:
"""
Initialize DatabaseManager with database connection settings.
Does not perform any database operations.
Args:
engine_uri: Database connection URI (e.g. sqlite:///db.sqlite3)
base_dir: Base directory for migration files. If None, uses current directory
"""
connection_args = {"check_same_thread": True} if "sqlite" in engine_uri else {}
if base_dir is not None and isinstance(base_dir, str):
base_dir = Path(base_dir)
self.engine = create_engine(
engine_uri, connect_args=connection_args, json_serializer=lambda obj: json.dumps(obj, cls=CustomJSONEncoder)
)
self.schema_manager = SchemaManager(
engine=self.engine,
base_dir=base_dir,
)
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.
2025-02-25 07:21:08 -08:00
def _should_auto_upgrade(self) -> bool:
"""
Check if auto upgrade should run based on schema differences
"""
needs_upgrade, _ = self.schema_manager.check_schema_status()
return needs_upgrade
def initialize_database(self, auto_upgrade: bool = False, force_init_alembic: bool = True) -> Response:
"""
Initialize database and migrations in the correct order.
Args:
auto_upgrade: If True, automatically generate and apply migrations for schema changes
force_init_alembic: If True, reinitialize alembic configuration even if it exists
"""
if not self._init_lock.acquire(blocking=False):
return Response(message="Database initialization already in progress", status=False)
try:
# Enable foreign key constraints for SQLite
if "sqlite" in str(self.engine.url):
with self.engine.connect() as conn:
conn.execute(text("PRAGMA foreign_keys=ON"))
inspector = inspect(self.engine)
tables_exist = inspector.get_table_names()
if not tables_exist:
logger.info("Creating database tables...")
SQLModel.metadata.create_all(self.engine)
if self.schema_manager.initialize_migrations(force=force_init_alembic):
return Response(message="Database initialized successfully", status=True)
return Response(message="Failed to initialize migrations", status=False)
# Handle existing database
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.
2025-02-25 07:21:08 -08:00
if auto_upgrade or self._should_auto_upgrade():
logger.info("Checking database schema...")
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.
2025-02-25 07:21:08 -08:00
if self.schema_manager.ensure_schema_up_to_date():
return Response(message="Database schema is up to date", status=True)
return Response(message="Database upgrade failed", status=False)
return Response(message="Database is ready", status=True)
except Exception as e:
error_msg = f"Database initialization failed: {str(e)}"
logger.error(error_msg)
return Response(message=error_msg, status=False)
finally:
self._init_lock.release()
def reset_db(self, recreate_tables: bool = True):
"""
Reset the database by dropping all tables and optionally recreating them.
Args:
recreate_tables (bool): If True, recreates the tables after dropping them.
Set to False if you want to call create_db_and_tables() separately.
"""
if not self._init_lock.acquire(blocking=False):
logger.warning("Database reset already in progress")
return Response(message="Database reset already in progress", status=False, data=None)
try:
# Dispose existing connections
self.engine.dispose()
with Session(self.engine) as session:
try:
# Disable foreign key checks for SQLite
if "sqlite" in str(self.engine.url):
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>
2025-03-14 15:02:05 -07:00
session.exec(text("PRAGMA foreign_keys=OFF")) # type: ignore
# Drop all tables
SQLModel.metadata.drop_all(self.engine)
logger.info("All tables dropped successfully")
# Re-enable foreign key checks for SQLite
if "sqlite" in str(self.engine.url):
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>
2025-03-14 15:02:05 -07:00
session.exec(text("PRAGMA foreign_keys=ON")) # type: ignore
session.commit()
except Exception as e:
session.rollback()
raise e
finally:
session.close()
self._init_lock.release()
if recreate_tables:
logger.info("Recreating tables...")
self.initialize_database(auto_upgrade=False, force_init_alembic=True)
return Response(
message="Database reset successfully" if recreate_tables else "Database tables dropped successfully",
status=True,
data=None,
)
except Exception as e:
error_msg = f"Error while resetting database: {str(e)}"
logger.error(error_msg)
return Response(message=error_msg, status=False, data=None)
finally:
if self._init_lock.locked():
self._init_lock.release()
logger.info("Database reset lock released")
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.
2025-02-25 07:21:08 -08:00
def upsert(self, model: SQLModel, return_json: bool = True) -> Response:
"""Create or update an entity
Args:
model (SQLModel): The model instance to create or update
return_json (bool, optional): If True, returns the model as a dictionary.
If False, returns the SQLModel instance. Defaults to True.
Returns:
Response: Contains status, message and data (either dict or SQLModel based on return_json)
"""
status = True
model_class = type(model)
existing_model = None
with Session(self.engine) as session:
try:
existing_model = session.exec(select(model_class).where(model_class.id == model.id)).first()
if existing_model:
model.updated_at = datetime.now()
for key, value in model.model_dump().items():
setattr(existing_model, key, value)
model = existing_model
session.add(model)
else:
session.add(model)
session.commit()
session.refresh(model)
except Exception as e:
session.rollback()
logger.error("Error while updating/creating " + str(model_class.__name__) + ": " + str(e))
status = False
return Response(
message=(
f"{model_class.__name__} Updated Successfully"
if existing_model
else f"{model_class.__name__} Created Successfully"
),
status=status,
data=model.model_dump() if return_json else model,
)
def _model_to_dict(self, model_obj):
return {col.name: getattr(model_obj, col.name) for col in model_obj.__table__.columns}
def get(
self,
model_class: SQLModel,
filters: dict | None = None,
return_json: bool = False,
order: str = "desc",
):
"""List entities"""
with Session(self.engine) as session:
result = []
status = True
status_message = ""
try:
statement = select(model_class)
if filters:
conditions = [getattr(model_class, col) == value for col, value in filters.items()]
statement = statement.where(and_(*conditions))
if hasattr(model_class, "created_at") and order:
order_by_clause = getattr(model_class.created_at, order)() # Dynamically apply asc/desc
statement = statement.order_by(order_by_clause)
items = session.exec(statement).all()
result = [self._model_to_dict(item) if return_json else item for item in items]
status_message = f"{model_class.__name__} Retrieved Successfully"
except Exception as e:
session.rollback()
status = False
status_message = f"Error while fetching {model_class.__name__}"
logger.error("Error while getting items: " + str(model_class.__name__) + " " + str(e))
return Response(message=status_message, status=status, data=result)
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.
2025-02-25 07:21:08 -08:00
def delete(self, model_class: SQLModel, filters: dict = None) -> Response:
"""Delete an entity"""
status_message = ""
status = True
with Session(self.engine) as session:
try:
if "sqlite" in str(self.engine.url):
session.exec(text("PRAGMA foreign_keys=ON"))
statement = select(model_class)
if filters:
conditions = [getattr(model_class, col) == value for col, value in filters.items()]
statement = statement.where(and_(*conditions))
rows = session.exec(statement).all()
if rows:
for row in rows:
session.delete(row)
session.commit()
status_message = f"{model_class.__name__} Deleted Successfully"
else:
status_message = "Row not found"
logger.info(f"Row with filters {filters} not found")
except exc.IntegrityError as e:
session.rollback()
status = False
status_message = f"Integrity error: The {model_class.__name__} is linked to another entity and cannot be deleted. {e}"
# Log the specific integrity error
logger.error(status_message)
except Exception as e:
session.rollback()
status = False
status_message = f"Error while deleting: {e}"
logger.error(status_message)
return Response(message=status_message, status=status, data=None)
async def import_team(
self, team_config: Union[str, Path, dict], user_id: str, check_exists: bool = False
) -> Response:
try:
# Load config if path provided
if isinstance(team_config, (str, Path)):
config = await TeamManager.load_from_file(team_config)
else:
config = team_config
# Check existence if requested
if check_exists:
existing = await self._check_team_exists(config, user_id)
if existing:
return Response(
message="Identical team configuration already exists", status=True, data={"id": existing.id}
)
# Store in database
team_db = Team(user_id=user_id, component=config)
result = self.upsert(team_db)
return result
except Exception as e:
logger.error(f"Failed to import team: {str(e)}")
return Response(message=str(e), status=False)
async def import_teams_from_directory(
self, directory: Union[str, Path], user_id: str, check_exists: bool = False
) -> Response:
"""
Import all team configurations from a directory.
Args:
directory: Path to directory containing team configs
user_id: User ID to associate with imported teams
check_exists: Whether to check for existing teams
Returns:
Response containing import results for all files
"""
try:
# Load all configs from directory
configs = await TeamManager.load_from_directory(directory)
results = []
for config in configs:
try:
result = await self.import_team(team_config=config, user_id=user_id, check_exists=check_exists)
# Add result info
results.append(
{
"status": result.status,
"message": result.message,
"id": result.data.get("id") if result.data else None,
}
)
except Exception as e:
logger.error(f"Failed to import team config: {str(e)}")
results.append({"status": False, "message": str(e), "id": None})
return Response(message="Directory import complete", status=True, data=results)
except Exception as e:
logger.error(f"Failed to import directory: {str(e)}")
return Response(message=str(e), status=False)
async def _check_team_exists(self, config: dict, user_id: str) -> Optional[Team]:
"""Check if identical team config already exists"""
teams = self.get(Team, {"user_id": user_id}).data
for team in teams:
if team.component == config:
return team
return None
async def close(self):
"""Close database connections and cleanup resources"""
logger.info("Closing database connections...")
try:
# Dispose of the SQLAlchemy engine
self.engine.dispose()
logger.info("Database connections closed successfully")
except Exception as e:
logger.error(f"Error closing database connections: {str(e)}")
raise