Manager class to handle business logic related to Sources.
| 12 | |
| 13 | |
| 14 | class SourceManager: |
| 15 | """Manager class to handle business logic related to Sources.""" |
| 16 | |
| 17 | def __init__(self): |
| 18 | from letta.server.db import db_context |
| 19 | |
| 20 | self.session_maker = db_context |
| 21 | |
| 22 | @enforce_types |
| 23 | def create_source(self, source: PydanticSource, actor: PydanticUser) -> PydanticSource: |
| 24 | """Create a new source based on the PydanticSource schema.""" |
| 25 | # Try getting the source first by id |
| 26 | db_source = self.get_source_by_id(source.id, actor=actor) |
| 27 | if db_source: |
| 28 | return db_source |
| 29 | else: |
| 30 | with self.session_maker() as session: |
| 31 | # Provide default embedding config if not given |
| 32 | source.organization_id = actor.organization_id |
| 33 | source = SourceModel(**source.model_dump(to_orm=True, exclude_none=True)) |
| 34 | source.create(session, actor=actor) |
| 35 | return source.to_pydantic() |
| 36 | |
| 37 | @enforce_types |
| 38 | def update_source(self, source_id: str, source_update: SourceUpdate, actor: PydanticUser) -> PydanticSource: |
| 39 | """Update a source by its ID with the given SourceUpdate object.""" |
| 40 | with self.session_maker() as session: |
| 41 | source = SourceModel.read(db_session=session, identifier=source_id, actor=actor) |
| 42 | |
| 43 | # get update dictionary |
| 44 | update_data = source_update.model_dump(to_orm=True, exclude_unset=True, exclude_none=True) |
| 45 | # Remove redundant update fields |
| 46 | update_data = {key: value for key, value in update_data.items() if getattr(source, key) != value} |
| 47 | |
| 48 | if update_data: |
| 49 | for key, value in update_data.items(): |
| 50 | setattr(source, key, value) |
| 51 | source.update(db_session=session, actor=actor) |
| 52 | else: |
| 53 | printd( |
| 54 | f"`update_source` was called with user_id={actor.id}, organization_id={actor.organization_id}, name={source.name}, but found existing source with nothing to update." |
| 55 | ) |
| 56 | |
| 57 | return source.to_pydantic() |
| 58 | |
| 59 | @enforce_types |
| 60 | def delete_source(self, source_id: str, actor: PydanticUser) -> PydanticSource: |
| 61 | """Delete a source by its ID.""" |
| 62 | with self.session_maker() as session: |
| 63 | source = SourceModel.read(db_session=session, identifier=source_id) |
| 64 | source.hard_delete(db_session=session, actor=actor) |
| 65 | return source.to_pydantic() |
| 66 | |
| 67 | @enforce_types |
| 68 | def list_sources(self, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50, **kwargs) -> List[PydanticSource]: |
| 69 | """List all sources with optional pagination.""" |
| 70 | with self.session_maker() as session: |
| 71 | sources = SourceModel.list( |