Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

chore: removed agent_store, storage connectors (#2229)

mlong932307739ff328
diff --git a/alembic/env.py b/alembic/env.py
index 551a21f36..767b7bbdb 100644
--- a/alembic/env.py
+++ b/alembic/env.py
@@ -4,7 +4,6 @@ from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
-from letta.agent_store.db import attach_base
from letta.config import LettaConfig
from letta.orm import Base
from letta.settings import settings
@@ -31,7 +30,6 @@ if config.config_file_name is not None:
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
-attach_base()
target_metadata = Base.metadata
diff --git a/letta/agent.py b/letta/agent.py
index efb850e28..98e6f9ff1 100644
--- a/letta/agent.py
+++ b/letta/agent.py
@@ -8,7 +8,6 @@ from typing import List, Literal, Optional, Tuple, Union
from tqdm import tqdm
-from letta.agent_store.storage import StorageConnector
from letta.constants import (
BASE_TOOLS,
CLI_WARNING_PREFIX,
diff --git a/letta/agent_store/db.py b/letta/agent_store/db.py
deleted file mode 100644
index 095a0e82c..000000000
--- a/letta/agent_store/db.py
+++ /dev/null
@@ -1,467 +0,0 @@
-import base64
-import json
-import os
-from datetime import datetime
-from typing import Dict, List, Optional
-
-import numpy as np
-from sqlalchemy import (
- BINARY,
- Column,
- DateTime,
- Index,
- String,
- TypeDecorator,
- and_,
- asc,
- desc,
- or_,
- select,
- text,
-)
-from sqlalchemy.orm import mapped_column
-from sqlalchemy.orm.session import close_all_sessions
-from sqlalchemy.sql import func
-from sqlalchemy_json import MutableJson
-from tqdm import tqdm
-
-from letta.agent_store.storage import StorageConnector, TableType
-from letta.config import LettaConfig
-from letta.constants import MAX_EMBEDDING_DIM
-from letta.metadata import EmbeddingConfigColumn
-from letta.orm.base import Base
-from letta.orm.file import FileMetadata as FileMetadataModel
-
-# from letta.schemas.message import Message, Passage, Record, RecordType, ToolCall
-from letta.orm.passage import Passage as PassageModel
-from letta.settings import settings
-
-config = LettaConfig()
-
-
-class CommonVector(TypeDecorator):
- """Common type for representing vectors in SQLite"""
-
- impl = BINARY
- cache_ok = True
-
- def load_dialect_impl(self, dialect):
- return dialect.type_descriptor(BINARY())
-
- def process_bind_param(self, value, dialect):
- if value is None:
- return value
- # Ensure value is a numpy array
- if isinstance(value, list):
- value = np.array(value, dtype=np.float32)
- # Serialize numpy array to bytes, then encode to base64 for universal compatibility
- return base64.b64encode(value.tobytes())
-
- def process_result_value(self, value, dialect):
- if not value:
- return value
- # Check database type and deserialize accordingly
- if dialect.name == "sqlite":
- # Decode from base64 and convert back to numpy array
- value = base64.b64decode(value)
- # For PostgreSQL, value is already in bytes
- return np.frombuffer(value, dtype=np.float32)
-
-class SQLStorageConnector(StorageConnector):
- def __init__(self, table_type: str, config: LettaConfig, user_id, agent_id=None):
- super().__init__(table_type=table_type, config=config, user_id=user_id, agent_id=agent_id)
- self.config = config
-
- def get_filters(self, filters: Optional[Dict] = {}):
- if filters is not None:
- filter_conditions = {**self.filters, **filters}
- else:
- filter_conditions = self.filters
- all_filters = [getattr(self.db_model, key) == value for key, value in filter_conditions.items()]
- return all_filters
-
- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: Optional[int] = 1000, offset=0):
- filters = self.get_filters(filters)
- while True:
- # Retrieve a chunk of records with the given page_size
- with self.session_maker() as session:
- db_record_chunk = session.query(self.db_model).filter(*filters).offset(offset).limit(page_size).all()
-
- # If the chunk is empty, we've retrieved all records
- if not db_record_chunk:
- break
-
- # Yield a list of Record objects converted from the chunk
- yield [record.to_record() for record in db_record_chunk]
-
- # Increment the offset to get the next chunk in the next iteration
- offset += page_size
-
- def get_all_cursor(
- self,
- filters: Optional[Dict] = {},
- after: str = None,
- before: str = None,
- limit: Optional[int] = 1000,
- order_by: str = "created_at",
- reverse: bool = False,
- ):
- """Get all that returns a cursor (record.id) and records"""
- filters = self.get_filters(filters)
-
- # generate query
- with self.session_maker() as session:
- query = session.query(self.db_model).filter(*filters)
- # query = query.order_by(asc(self.db_model.id))
-
- # records are sorted by the order_by field first, and then by the ID if two fields are the same
- if reverse:
- query = query.order_by(desc(getattr(self.db_model, order_by)), asc(self.db_model.id))
- else:
- query = query.order_by(asc(getattr(self.db_model, order_by)), asc(self.db_model.id))
-
- # cursor logic: filter records based on before/after ID
- if after:
- after_value = getattr(self.get(id=after), order_by)
- sort_exp = getattr(self.db_model, order_by) > after_value
- query = query.filter(
- or_(sort_exp, and_(getattr(self.db_model, order_by) == after_value, self.db_model.id > after)) # tiebreaker case
- )
- if before:
- before_value = getattr(self.get(id=before), order_by)
- sort_exp = getattr(self.db_model, order_by) < before_value
- query = query.filter(or_(sort_exp, and_(getattr(self.db_model, order_by) == before_value, self.db_model.id < before)))
-
- # get records
- db_record_chunk = query.limit(limit).all()
- if not db_record_chunk:
- return (None, [])
- records = [record.to_record() for record in db_record_chunk]
- next_cursor = db_record_chunk[-1].id
- assert isinstance(next_cursor, str)
-
- # return (cursor, list[records])
- return (next_cursor, records)
-
- def get_all(self, filters: Optional[Dict] = {}, limit=None):
- filters = self.get_filters(filters)
- with self.session_maker() as session:
- if limit:
- db_records = session.query(self.db_model).filter(*filters).limit(limit).all()
- else:
- db_records = session.query(self.db_model).filter(*filters).all()
- return [record.to_record() for record in db_records]
-
- def get(self, id: str):
- with self.session_maker() as session:
- db_record = session.get(self.db_model, id)
- if db_record is None:
- return None
- return db_record.to_record()
-
- def size(self, filters: Optional[Dict] = {}) -> int:
- # return size of table
- filters = self.get_filters(filters)
- with self.session_maker() as session:
- return session.query(self.db_model).filter(*filters).count()
-
- def insert(self, record):
- raise NotImplementedError
-
- def insert_many(self, records, show_progress=False):
- raise NotImplementedError
-
- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}):
- raise NotImplementedError("Vector query not implemented for SQLStorageConnector")
-
- def save(self):
- return
-
- def list_data_sources(self):
- assert self.table_type == TableType.ARCHIVAL_MEMORY, f"list_data_sources only implemented for ARCHIVAL_MEMORY"
- with self.session_maker() as session:
- unique_data_sources = session.query(self.db_model.data_source).filter(*self.filters).distinct().all()
- return unique_data_sources
-
- def query_date(self, start_date, end_date, limit=None, offset=0):
- filters = self.get_filters({})
- with self.session_maker() as session:
- query = (
- session.query(self.db_model)
- .filter(*filters)
- .filter(self.db_model.created_at >= start_date)
- .filter(self.db_model.created_at <= end_date)
- .filter(self.db_model.role != "system")
- .filter(self.db_model.role != "tool")
- .offset(offset)
- )
- if limit:
- query = query.limit(limit)
- results = query.all()
- return [result.to_record() for result in results]
-
- def query_text(self, query, limit=None, offset=0):
- # todo: make fuzz https://stackoverflow.com/questions/42388956/create-a-full-text-search-index-with-sqlalchemy-on-postgresql/42390204#42390204
- filters = self.get_filters({})
- with self.session_maker() as session:
- query = (
- session.query(self.db_model)
- .filter(*filters)
- .filter(func.lower(self.db_model.text).contains(func.lower(query)))
- .filter(self.db_model.role != "system")
- .filter(self.db_model.role != "tool")
- .offset(offset)
- )
- if limit:
- query = query.limit(limit)
- results = query.all()
- # return [self.type(**vars(result)) for result in results]
- return [result.to_record() for result in results]
-
- # Should be used only in tests!
- def delete_table(self):
- close_all_sessions()
- with self.session_maker() as session:
- self.db_model.__table__.drop(session.bind)
- session.commit()
-
- def delete(self, filters: Optional[Dict] = {}):
- filters = self.get_filters(filters)
- with self.session_maker() as session:
- session.query(self.db_model).filter(*filters).delete()
- session.commit()
-
-
-class PostgresStorageConnector(SQLStorageConnector):
- """Storage via Postgres"""
-
- # TODO: this should probably eventually be moved into a parent DB class
-
- def __init__(self, table_type: str, config: LettaConfig, user_id, agent_id=None):
- from pgvector.sqlalchemy import Vector
-
- super().__init__(table_type=table_type, config=config, user_id=user_id, agent_id=agent_id)
-
- # construct URI from enviornment variables
- if settings.pg_uri:
- self.uri = settings.pg_uri
-
- # use config URI
- # TODO: remove this eventually (config should NOT contain URI)
- if table_type == TableType.ARCHIVAL_MEMORY or table_type == TableType.PASSAGES:
- self.uri = self.config.archival_storage_uri
- self.db_model = PassageModel
- if self.config.archival_storage_uri is None:
- raise ValueError(f"Must specify archival_storage_uri in config {self.config.config_path}")
- elif table_type == TableType.FILES:
- self.uri = self.config.metadata_storage_uri
- self.db_model = FileMetadataModel
- if self.config.metadata_storage_uri is None:
- raise ValueError(f"Must specify metadata_storage_uri in config {self.config.config_path}")
- else:
- raise ValueError(f"Table type {table_type} not implemented")
-
- if settings.pg_uri:
- for c in self.db_model.__table__.columns:
- if c.name == "embedding":
- assert isinstance(c.type, Vector), f"Embedding column must be of type Vector, got {c.type}"
-
- from letta.server.server import db_context
-
- self.session_maker = db_context
-
- # TODO: move to DB init
- if settings.pg_uri:
- with self.session_maker() as session:
- session.execute(text("CREATE EXTENSION IF NOT EXISTS vector")) # Enables the vector extension
-
- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}):
- filters = self.get_filters(filters)
- with self.session_maker() as session:
- results = session.scalars(
- select(self.db_model).filter(*filters).order_by(self.db_model.embedding.l2_distance(query_vec)).limit(top_k)
- ).all()
-
- # Convert the results into Passage objects
- records = [result.to_record() for result in results]
- return records
-
- def insert_many(self, records, exists_ok=True, show_progress=False):
- # TODO: this is terrible, should eventually be done the same way for all types (migrate to SQLModel)
- if len(records) == 0:
- return
-
- added_ids = [] # avoid adding duplicates
- # NOTE: this has not great performance due to the excessive commits
- with self.session_maker() as session:
- iterable = tqdm(records) if show_progress else records
- for record in iterable:
- # db_record = self.db_model(**vars(record))
-
- if record.id in added_ids:
- continue
-
- existing_record = session.query(self.db_model).filter_by(id=record.id).first()
- if existing_record:
- if exists_ok:
- fields = record.model_dump()
- fields.pop("id")
- session.query(self.db_model).filter(self.db_model.id == record.id).update(fields)
- print(f"Updated record with id {record.id}")
- session.commit()
- else:
- raise ValueError(f"Record with id {record.id} already exists.")
-
- else:
- db_record = self.db_model(**record.dict())
- session.add(db_record)
- # print(f"Added record with id {record.id}")
- session.commit()
-
- added_ids.append(record.id)
-
- def insert(self, record, exists_ok=True):
- self.insert_many([record], exists_ok=exists_ok)
-
- def update(self, record):
- """
- Updates a record in the database based on the provided Record object.
- """
- with self.session_maker() as session:
- # Find the record by its ID
- db_record = session.query(self.db_model).filter_by(id=record.id).first()
- if not db_record:
- raise ValueError(f"Record with id {record.id} does not exist.")
-
- # Update the record with new values from the provided Record object
- for attr, value in vars(record).items():
- setattr(db_record, attr, value)
-
- # Commit the changes to the database
- session.commit()
-
- def str_to_datetime(self, str_date: str) -> datetime:
- val = str_date.split("-")
- _datetime = datetime(int(val[0]), int(val[1]), int(val[2]))
- return _datetime
-
- def query_date(self, start_date, end_date, limit=None, offset=0):
- filters = self.get_filters({})
- _start_date = self.str_to_datetime(start_date) if isinstance(start_date, str) else start_date
- _end_date = self.str_to_datetime(end_date) if isinstance(end_date, str) else end_date
- with self.session_maker() as session:
- query = (
- session.query(self.db_model)
- .filter(*filters)
- .filter(self.db_model.created_at >= _start_date)
- .filter(self.db_model.created_at <= _end_date)
- .filter(self.db_model.role != "system")
- .filter(self.db_model.role != "tool")
- .offset(offset)
- )
- if limit:
- query = query.limit(limit)
- results = query.all()
- return [result.to_record() for result in results]
-
-
-class SQLLiteStorageConnector(SQLStorageConnector):
- def __init__(self, table_type: str, config: LettaConfig, user_id, agent_id=None):
- super().__init__(table_type=table_type, config=config, user_id=user_id, agent_id=agent_id)
-
- # get storage URI
- if table_type == TableType.ARCHIVAL_MEMORY or table_type == TableType.PASSAGES:
- self.db_model = PassageModel
- if settings.letta_pg_uri_no_default:
- self.uri = settings.letta_pg_uri_no_default
- else:
- # For SQLite, use the archival storage path
- self.path = config.archival_storage_path
- self.uri = f"sqlite:///{os.path.join(config.archival_storage_path, 'letta.db')}"
- elif table_type == TableType.FILES:
- self.path = self.config.metadata_storage_path
- if self.path is None:
- raise ValueError(f"Must specify metadata_storage_path in config.")
- self.db_model = FileMetadataModel
-
- else:
- raise ValueError(f"Table type {table_type} not implemented")
-
- self.path = os.path.join(self.path, f"sqlite.db")
-
- from letta.server.server import db_context
-
- self.session_maker = db_context
-
- # Need this in order to allow UUIDs to be stored successfully in the sqlite database
- # import sqlite3
- # import uuid
- #
- # sqlite3.register_adapter(uuid.UUID, lambda u: u.bytes_le)
- # sqlite3.register_converter("UUID", lambda b: uuid.UUID(bytes_le=b))
-
- def insert_many(self, records, exists_ok=True, show_progress=False):
- # TODO: this is terrible, should eventually be done the same way for all types (migrate to SQLModel)
- if len(records) == 0:
- return
-
- added_ids = [] # avoid adding duplicates
- # NOTE: this has not great performance due to the excessive commits
- with self.session_maker() as session:
- iterable = tqdm(records) if show_progress else records
- for record in iterable:
- # db_record = self.db_model(**vars(record))
-
- if record.id in added_ids:
- continue
-
- existing_record = session.query(self.db_model).filter_by(id=record.id).first()
- if existing_record:
- if exists_ok:
- fields = record.model_dump()
- fields.pop("id")
- session.query(self.db_model).filter(self.db_model.id == record.id).update(fields)
- session.commit()
- else:
- raise ValueError(f"Record with id {record.id} already exists.")
-
- else:
- db_record = self.db_model(**record.dict())
- session.add(db_record)
- session.commit()
-
- added_ids.append(record.id)
-
- def insert(self, record, exists_ok=True):
- self.insert_many([record], exists_ok=exists_ok)
-
- def update(self, record):
- """
- Updates an existing record in the database with values from the provided record object.
- """
- if not record.id:
- raise ValueError("Record must have an id.")
-
- with self.session_maker() as session:
- # Fetch the existing record from the database
- db_record = session.query(self.db_model).filter_by(id=record.id).first()
- if not db_record:
- raise ValueError(f"Record with id {record.id} does not exist.")
-
- # Update the database record with values from the provided record object
- for column in self.db_model.__table__.columns:
- column_name = column.name
- if hasattr(record, column_name):
- new_value = getattr(record, column_name)
- setattr(db_record, column_name, new_value)
-
- # Commit the changes to the database
- session.commit()
-
-
-def attach_base():
- # This should be invoked in server.py to make sure Base gets initialized properly
- # DO NOT REMOVE
- from letta.utils import printd
-
- printd("Initializing database...")
diff --git a/letta/agent_store/milvus.py b/letta/agent_store/milvus.py
deleted file mode 100644
index cd1ce71d2..000000000
--- a/letta/agent_store/milvus.py
+++ /dev/null
@@ -1,198 +0,0 @@
-import uuid
-from copy import deepcopy
-from typing import Dict, Iterator, List, Optional, cast
-
-from pymilvus import DataType, MilvusClient
-from pymilvus.client.constants import ConsistencyLevel
-
-from letta.agent_store.storage import StorageConnector, TableType
-from letta.config import LettaConfig
-from letta.constants import MAX_EMBEDDING_DIM
-from letta.data_types import Passage, Record, RecordType
-from letta.utils import datetime_to_timestamp, printd, timestamp_to_datetime
-
-
-class MilvusStorageConnector(StorageConnector):
- """Storage via Milvus"""
-
- def __init__(self, table_type: str, config: LettaConfig, user_id, agent_id=None):
- super().__init__(table_type=table_type, config=config, user_id=user_id, agent_id=agent_id)
-
- assert table_type in [TableType.ARCHIVAL_MEMORY, TableType.PASSAGES], "Milvus only supports archival memory"
- if config.archival_storage_uri:
- self.client = MilvusClient(uri=config.archival_storage_uri)
- self._create_collection()
- else:
- raise ValueError("Please set `archival_storage_uri` in the config file when using Milvus.")
-
- # need to be converted to strings
- self.uuid_fields = ["id", "user_id", "agent_id", "source_id", "file_id"]
-
- def _create_collection(self):
- schema = MilvusClient.create_schema(
- auto_id=False,
- enable_dynamic_field=True,
- )
- schema.add_field(field_name="id", datatype=DataType.VARCHAR, is_primary=True, max_length=65_535)
- schema.add_field(field_name="text", datatype=DataType.VARCHAR, is_primary=False, max_length=65_535)
- schema.add_field(field_name="embedding", datatype=DataType.FLOAT_VECTOR, dim=MAX_EMBEDDING_DIM)
- index_params = self.client.prepare_index_params()
- index_params.add_index(field_name="id")
- index_params.add_index(field_name="embedding", index_type="AUTOINDEX", metric_type="IP")
- self.client.create_collection(
- collection_name=self.table_name, schema=schema, index_params=index_params, consistency_level=ConsistencyLevel.Strong
- )
-
- def get_milvus_filter(self, filters: Optional[Dict] = {}) -> str:
- filter_conditions = {**self.filters, **filters} if filters is not None else self.filters
- if not filter_conditions:
- return ""
- conditions = []
- for key, value in filter_conditions.items():
- if key in self.uuid_fields or isinstance(key, str):
- condition = f'({key} == "{value}")'
- else:
- condition = f"({key} == {value})"
- conditions.append(condition)
- filter_expr = " and ".join(conditions)
- if len(conditions) == 1:
- filter_expr = filter_expr[1:-1]
- return filter_expr
-
- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: int = 1000) -> Iterator[List[RecordType]]:
- if not self.client.has_collection(collection_name=self.table_name):
- yield []
- filter_expr = self.get_milvus_filter(filters)
- offset = 0
- while True:
- # Retrieve a chunk of records with the given page_size
- query_res = self.client.query(
- collection_name=self.table_name,
- filter=filter_expr,
- offset=offset,
- limit=page_size,
- )
- if not query_res:
- break
- # Yield a list of Record objects converted from the chunk
- yield self._list_to_records(query_res)
-
- # Increment the offset to get the next chunk in the next iteration
- offset += page_size
-
- def get_all(self, filters: Optional[Dict] = {}, limit=None) -> List[RecordType]:
- if not self.client.has_collection(collection_name=self.table_name):
- return []
- filter_expr = self.get_milvus_filter(filters)
- query_res = self.client.query(
- collection_name=self.table_name,
- filter=filter_expr,
- limit=limit,
- )
- return self._list_to_records(query_res)
-
- def get(self, id: str) -> Optional[RecordType]:
- res = self.client.get(collection_name=self.table_name, ids=str(id))
- return self._list_to_records(res)[0] if res else None
-
- def size(self, filters: Optional[Dict] = {}) -> int:
- if not self.client.has_collection(collection_name=self.table_name):
- return 0
- filter_expr = self.get_milvus_filter(filters)
- count_expr = "count(*)"
- query_res = self.client.query(
- collection_name=self.table_name,
- filter=filter_expr,
- output_fields=[count_expr],
- )
- doc_num = query_res[0][count_expr]
- return doc_num
-
- def insert(self, record: RecordType):
- self.insert_many([record])
-
- def insert_many(self, records: List[RecordType], show_progress=False):
- if not records:
- return
-
- # Milvus lite currently does not support upsert, so we delete and insert instead
- # self.client.upsert(collection_name=self.table_name, data=self._records_to_list(records))
- ids = [str(record.id) for record in records]
- self.client.delete(collection_name=self.table_name, ids=ids)
- data = self._records_to_list(records)
- self.client.insert(collection_name=self.table_name, data=data)
-
- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}) -> List[RecordType]:
- if not self.client.has_collection(self.table_name):
- return []
- search_res = self.client.search(
- collection_name=self.table_name, data=[query_vec], filter=self.get_milvus_filter(filters), limit=top_k, output_fields=["*"]
- )[0]
- entity_res = [res["entity"] for res in search_res]
- return self._list_to_records(entity_res)
-
- def delete_table(self):
- self.client.drop_collection(collection_name=self.table_name)
-
- def delete(self, filters: Optional[Dict] = {}):
- if not self.client.has_collection(collection_name=self.table_name):
- return
- filter_expr = self.get_milvus_filter(filters)
- self.client.delete(collection_name=self.table_name, filter=filter_expr)
-
- def save(self):
- # save to persistence file (nothing needs to be done)
- printd("Saving milvus")
-
- def _records_to_list(self, records: List[Record]) -> List[Dict]:
- if records == []:
- return []
- assert all(isinstance(r, Passage) for r in records)
- record_list = []
- records = list(set(records))
- for record in records:
- record_vars = deepcopy(vars(record))
- _id = record_vars.pop("id")
- text = record_vars.pop("text", "")
- embedding = record_vars.pop("embedding")
- record_metadata = record_vars.pop("metadata_", None) or {}
- if "created_at" in record_vars:
- record_vars["created_at"] = datetime_to_timestamp(record_vars["created_at"])
- record_dict = {key: value for key, value in record_vars.items() if value is not None}
- record_dict = {
- **record_dict,
- **record_metadata,
- "id": str(_id),
- "text": text,
- "embedding": embedding,
- }
- for key, value in record_dict.items():
- if key in self.uuid_fields:
- record_dict[key] = str(value)
- record_list.append(record_dict)
- return record_list
-
- def _list_to_records(self, query_res: List[Dict]) -> List[RecordType]:
- records = []
- for res_dict in query_res:
- _id = res_dict.pop("id")
- embedding = res_dict.pop("embedding")
- text = res_dict.pop("text")
- metadata = deepcopy(res_dict)
- for key, value in metadata.items():
- if key in self.uuid_fields:
- metadata[key] = uuid.UUID(value)
- elif key == "created_at":
- metadata[key] = timestamp_to_datetime(value)
- records.append(
- cast(
- RecordType,
- self.type(
- text=text,
- embedding=embedding,
- id=uuid.UUID(_id),
- **metadata,
- ),
- )
- )
- return records
diff --git a/letta/agent_store/qdrant.py b/letta/agent_store/qdrant.py
deleted file mode 100644
index 2583f0857..000000000
--- a/letta/agent_store/qdrant.py
+++ /dev/null
@@ -1,201 +0,0 @@
-import os
-import uuid
-from copy import deepcopy
-from typing import Dict, Iterator, List, Optional, cast
-
-from letta.agent_store.storage import StorageConnector, TableType
-from letta.config import LettaConfig
-from letta.constants import MAX_EMBEDDING_DIM
-from letta.data_types import Passage, Record, RecordType
-from letta.utils import datetime_to_timestamp, timestamp_to_datetime
-
-TEXT_PAYLOAD_KEY = "text_content"
-METADATA_PAYLOAD_KEY = "metadata"
-
-
-class QdrantStorageConnector(StorageConnector):
- """Storage via Qdrant"""
-
- def __init__(self, table_type: str, config: LettaConfig, user_id, agent_id=None):
- super().__init__(table_type=table_type, config=config, user_id=user_id, agent_id=agent_id)
- try:
- from qdrant_client import QdrantClient, models
- except ImportError as e:
- raise ImportError("'qdrant-client' not installed. Run `pip install qdrant-client`.") from e
- assert table_type in [TableType.ARCHIVAL_MEMORY, TableType.PASSAGES], "Qdrant only supports archival memory"
- if config.archival_storage_uri and len(config.archival_storage_uri.split(":")) == 2:
- host, port = config.archival_storage_uri.split(":")
- self.qdrant_client = QdrantClient(host=host, port=port, api_key=os.getenv("QDRANT_API_KEY"))
- elif config.archival_storage_path:
- self.qdrant_client = QdrantClient(path=config.archival_storage_path)
- else:
- raise ValueError("Qdrant storage requires either a URI or a path to the storage configured")
- if not self.qdrant_client.collection_exists(self.table_name):
- self.qdrant_client.create_collection(
- collection_name=self.table_name,
- vectors_config=models.VectorParams(
- size=MAX_EMBEDDING_DIM,
- distance=models.Distance.COSINE,
- ),
- )
- self.uuid_fields = ["id", "user_id", "agent_id", "source_id", "file_id"]
-
- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: int = 10) -> Iterator[List[RecordType]]:
- from qdrant_client import grpc
-
- filters = self.get_qdrant_filters(filters)
- next_offset = None
- stop_scrolling = False
- while not stop_scrolling:
- results, next_offset = self.qdrant_client.scroll(
- collection_name=self.table_name,
- scroll_filter=filters,
- limit=page_size,
- offset=next_offset,
- with_payload=True,
- with_vectors=True,
- )
- stop_scrolling = next_offset is None or (
- isinstance(next_offset, grpc.PointId) and next_offset.num == 0 and next_offset.uuid == ""
- )
- yield self.to_records(results)
-
- def get_all(self, filters: Optional[Dict] = {}, limit=10) -> List[RecordType]:
- if self.size(filters) == 0:
- return []
- filters = self.get_qdrant_filters(filters)
- results, _ = self.qdrant_client.scroll(
- self.table_name,
- scroll_filter=filters,
- limit=limit,
- with_payload=True,
- with_vectors=True,
- )
- return self.to_records(results)
-
- def get(self, id: str) -> Optional[RecordType]:
- results = self.qdrant_client.retrieve(
- collection_name=self.table_name,
- ids=[str(id)],
- with_payload=True,
- with_vectors=True,
- )
- if not results:
- return None
- return self.to_records(results)[0]
-
- def insert(self, record: Record):
- points = self.to_points([record])
- self.qdrant_client.upsert(self.table_name, points=points)
-
- def insert_many(self, records: List[RecordType], show_progress=False):
- points = self.to_points(records)
- self.qdrant_client.upsert(self.table_name, points=points)
-
- def delete(self, filters: Optional[Dict] = {}):
- filters = self.get_qdrant_filters(filters)
- self.qdrant_client.delete(self.table_name, points_selector=filters)
-
- def delete_table(self):
- self.qdrant_client.delete_collection(self.table_name)
- self.qdrant_client.close()
-
- def size(self, filters: Optional[Dict] = {}) -> int:
- filters = self.get_qdrant_filters(filters)
- return self.qdrant_client.count(collection_name=self.table_name, count_filter=filters).count
-
- def close(self):
- self.qdrant_client.close()
-
- def query(
- self,
- query: str,
- query_vec: List[float],
- top_k: int = 10,
- filters: Optional[Dict] = {},
- ) -> List[RecordType]:
- filters = self.get_filters(filters)
- results = self.qdrant_client.search(
- self.table_name,
- query_vector=query_vec,
- query_filter=filters,
- limit=top_k,
- with_payload=True,
- with_vectors=True,
- )
- return self.to_records(results)
-
- def to_records(self, records: list) -> List[RecordType]:
- parsed_records = []
- for record in records:
- record = deepcopy(record)
- metadata = record.payload[METADATA_PAYLOAD_KEY]
- text = record.payload[TEXT_PAYLOAD_KEY]
- _id = metadata.pop("id")
- embedding = record.vector
- for key, value in metadata.items():
- if key in self.uuid_fields:
- metadata[key] = uuid.UUID(value)
- elif key == "created_at":
- metadata[key] = timestamp_to_datetime(value)
- parsed_records.append(
- cast(
- RecordType,
- self.type(
- text=text,
- embedding=embedding,
- id=uuid.UUID(_id),
- **metadata,
- ),
- )
- )
- return parsed_records
-
- def to_points(self, records: List[RecordType]):
- from qdrant_client import models
-
- assert all(isinstance(r, Passage) for r in records)
- points = []
- records = list(set(records))
- for record in records:
- record = vars(record)
- _id = record.pop("id")
- text = record.pop("text", "")
- embedding = record.pop("embedding", {})
- record_metadata = record.pop("metadata_", None) or {}
- if "created_at" in record:
- record["created_at"] = datetime_to_timestamp(record["created_at"])
- metadata = {key: value for key, value in record.items() if value is not None}
- metadata = {
- **metadata,
- **record_metadata,
- "id": str(_id),
- }
- for key, value in metadata.items():
- if key in self.uuid_fields:
- metadata[key] = str(value)
- points.append(
- models.PointStruct(
- id=str(_id),
- vector=embedding,
- payload={
- TEXT_PAYLOAD_KEY: text,
- METADATA_PAYLOAD_KEY: metadata,
- },
- )
- )
- return points
-
- def get_qdrant_filters(self, filters: Optional[Dict] = {}):
- from qdrant_client import models
-
- filter_conditions = {**self.filters, **filters} if filters is not None else self.filters
- must_conditions = []
- for key, value in filter_conditions.items():
- match_value = str(value) if key in self.uuid_fields else value
- field_condition = models.FieldCondition(
- key=f"{METADATA_PAYLOAD_KEY}.{key}",
- match=models.MatchValue(value=match_value),
- )
- must_conditions.append(field_condition)
- return models.Filter(must=must_conditions)
diff --git a/letta/agent_store/storage.py b/letta/agent_store/storage.py
deleted file mode 100644
index a7166d87f..000000000
--- a/letta/agent_store/storage.py
+++ /dev/null
@@ -1,186 +0,0 @@
-""" These classes define storage connectors.
-
-We originally tried to use Llama Index VectorIndex, but their limited API was extremely problematic.
-"""
-
-import uuid
-from abc import abstractmethod
-from typing import Dict, List, Optional, Tuple, Type, Union
-
-from pydantic import BaseModel
-
-from letta.config import LettaConfig
-from letta.schemas.file import FileMetadata
-from letta.schemas.message import Message
-from letta.schemas.passage import Passage
-from letta.utils import printd
-
-
-# ENUM representing table types in Letta
-# each table corresponds to a different table schema (specified in data_types.py)
-class TableType:
- ARCHIVAL_MEMORY = "archival_memory" # recall memory table: letta_agent_{agent_id}
- RECALL_MEMORY = "recall_memory" # archival memory table: letta_agent_recall_{agent_id}
- PASSAGES = "passages" # TODO
- FILES = "files"
-
-
-# table names used by Letta
-
-# agent tables
-RECALL_TABLE_NAME = "letta_recall_memory_agent" # agent memory
-ARCHIVAL_TABLE_NAME = "letta_archival_memory_agent" # agent memory
-
-# external data source tables
-PASSAGE_TABLE_NAME = "letta_passages" # chunked/embedded passages (from source)
-FILE_TABLE_NAME = "letta_files" # original files (from source)
-
-
-class StorageConnector:
- """Defines a DB connection that is user-specific to access data: files, Passages, Archival/Recall Memory"""
-
- type: Type[BaseModel]
-
- def __init__(
- self,
- table_type: Union[TableType.ARCHIVAL_MEMORY, TableType.RECALL_MEMORY, TableType.PASSAGES, TableType.FILES],
- config: LettaConfig,
- user_id: str,
- agent_id: Optional[str] = None,
- organization_id: Optional[str] = None,
- ):
- self.user_id = user_id
- self.agent_id = agent_id
- self.organization_id = organization_id
- self.table_type = table_type
-
- # get object type
- if table_type == TableType.ARCHIVAL_MEMORY:
- self.type = Passage
- self.table_name = ARCHIVAL_TABLE_NAME
- elif table_type == TableType.RECALL_MEMORY:
- self.type = Message
- self.table_name = RECALL_TABLE_NAME
- elif table_type == TableType.FILES:
- self.type = FileMetadata
- self.table_name = FILE_TABLE_NAME
- elif table_type == TableType.PASSAGES:
- self.type = Passage
- self.table_name = PASSAGE_TABLE_NAME
- else:
- raise ValueError(f"Table type {table_type} not implemented")
- printd(f"Using table name {self.table_name}")
-
- # setup base filters for agent-specific tables
- if self.table_type == TableType.ARCHIVAL_MEMORY or self.table_type == TableType.RECALL_MEMORY:
- # agent-specific table
- assert agent_id is not None, "Agent ID must be provided for agent-specific tables"
- self.filters = {"user_id": self.user_id, "agent_id": self.agent_id}
- elif self.table_type == TableType.FILES:
- # setup base filters for user-specific tables
- assert agent_id is None, "Agent ID must not be provided for user-specific tables"
- self.filters = {"user_id": self.user_id}
- elif self.table_type == TableType.PASSAGES:
- self.filters = {"organization_id": self.organization_id}
- else:
- raise ValueError(f"Table type {table_type} not implemented")
-
- @staticmethod
- def get_storage_connector(
- table_type: Union[TableType.ARCHIVAL_MEMORY, TableType.RECALL_MEMORY, TableType.PASSAGES, TableType.FILES],
- config: LettaConfig,
- user_id: str,
- organization_id: Optional[str] = None,
- agent_id: Optional[str] = None,
- ):
- if table_type == TableType.ARCHIVAL_MEMORY or table_type == TableType.PASSAGES:
- storage_type = config.archival_storage_type
- elif table_type == TableType.RECALL_MEMORY:
- storage_type = config.recall_storage_type
- elif table_type == TableType.FILES:
- storage_type = config.metadata_storage_type
- else:
- raise ValueError(f"Table type {table_type} not implemented")
-
- if storage_type == "postgres":
- from letta.agent_store.db import PostgresStorageConnector
-
- return PostgresStorageConnector(table_type, config, user_id, agent_id)
-
- elif storage_type == "qdrant":
- from letta.agent_store.qdrant import QdrantStorageConnector
-
- return QdrantStorageConnector(table_type, config, user_id, agent_id)
-
- elif storage_type == "sqlite":
- from letta.agent_store.db import SQLLiteStorageConnector
-
- return SQLLiteStorageConnector(table_type, config, user_id, agent_id)
- elif storage_type == "milvus":
- from letta.agent_store.milvus import MilvusStorageConnector
-
- return MilvusStorageConnector(table_type, config, user_id, agent_id)
- else:
- raise NotImplementedError(f"Storage type {storage_type} not implemented")
-
- @staticmethod
- def get_archival_storage_connector(user_id, agent_id):
- config = LettaConfig.load()
- return StorageConnector.get_storage_connector(TableType.ARCHIVAL_MEMORY, config, user_id, agent_id)
-
- @staticmethod
- def get_recall_storage_connector(user_id, agent_id):
- config = LettaConfig.load()
- return StorageConnector.get_storage_connector(TableType.RECALL_MEMORY, config, user_id, agent_id)
-
- @abstractmethod
- def get_filters(self, filters: Optional[Dict] = {}) -> Union[Tuple[list, dict], dict]:
- pass
-
- @abstractmethod
- def get_all_paginated(self, filters: Optional[Dict] = {}, page_size: int = 1000):
- pass
-
- @abstractmethod
- def get_all(self, filters: Optional[Dict] = {}, limit=10):
- pass
-
- @abstractmethod
- def get(self, id: uuid.UUID):
- pass
-
- @abstractmethod
- def size(self, filters: Optional[Dict] = {}) -> int:
- pass
-
- @abstractmethod
- def insert(self, record):
- pass
-
- @abstractmethod
- def insert_many(self, records, show_progress=False):
- pass
-
- @abstractmethod
- def query(self, query: str, query_vec: List[float], top_k: int = 10, filters: Optional[Dict] = {}):
- pass
-
- @abstractmethod
- def query_date(self, start_date, end_date):
- pass
-
- @abstractmethod
- def query_text(self, query):
- pass
-
- @abstractmethod
- def delete_table(self):
- pass
-
- @abstractmethod
- def delete(self, filters: Optional[Dict] = {}):
- pass
-
- @abstractmethod
- def save(self):
- pass
diff --git a/letta/data_sources/connectors.py b/letta/data_sources/connectors.py
index 6316863c0..741e46a91 100644
--- a/letta/data_sources/connectors.py
+++ b/letta/data_sources/connectors.py
@@ -2,7 +2,6 @@ from typing import Dict, Iterator, List, Tuple, Optional
import typer
-from letta.agent_store.storage import StorageConnector
from letta.data_sources.connectors_helper import (
assert_all_files_exist_locally,
extract_metadata_from_files,
@@ -12,6 +11,7 @@ from letta.embeddings import embedding_model
from letta.schemas.file import FileMetadata
from letta.schemas.passage import Passage
from letta.schemas.source import Source
+from letta.services.passage_manager import PassageManager
from letta.services.source_manager import SourceManager
from letta.utils import create_uuid_from_string
@@ -42,7 +42,7 @@ class DataConnector:
"""
-def load_data(connector: DataConnector, source: Source, passage_store: StorageConnector, source_manager: SourceManager, actor: "User", agent_id: Optional[str] = None):
+def load_data(connector: DataConnector, source: Source, passage_manager: PassageManager, source_manager: SourceManager, actor: "User", agent_id: Optional[str] = None):
"""Load data from a connector (generates file and passages) into a specified source_id, associated with a user_id."""
embedding_config = source.embedding_config
@@ -103,14 +103,14 @@ def load_data(connector: DataConnector, source: Source, passage_store: StorageCo
embedding_to_document_name[hashable_embedding] = file_name
if len(passages) >= 100:
# insert passages into passage store
- passage_store.insert_many(passages)
+ passage_manager.create_many_passages(passages, actor)
passage_count += len(passages)
passages = []
if len(passages) > 0:
# insert passages into passage store
- passage_store.insert_many(passages)
+ passage_manager.create_many_passages(passages, actor)
passage_count += len(passages)
return passage_count, file_count
@@ -170,74 +170,3 @@ class DirectoryConnector(DataConnector):
nodes = parser.get_nodes_from_documents(documents)
for node in nodes:
yield node.text, None
-
-
-"""
-The below isn't used anywhere, it isn't tested, and pretty much should be deleted.
-- Matt
-"""
-# class WebConnector(DirectoryConnector):
-# def __init__(self, urls: List[str] = None, html_to_text: bool = True):
-# self.urls = urls
-# self.html_to_text = html_to_text
-#
-# def generate_files(self) -> Iterator[Tuple[str, Dict]]: # -> Iterator[Document]:
-# from llama_index.readers.web import SimpleWebPageReader
-#
-# files = SimpleWebPageReader(html_to_text=self.html_to_text).load_data(self.urls)
-# for document in files:
-# yield document.text, {"url": document.id_}
-#
-#
-# class VectorDBConnector(DataConnector):
-# # NOTE: this class has not been properly tested, so is unlikely to work
-# # TODO: allow loading multiple tables (1:1 mapping between FileMetadata and Table)
-#
-# def __init__(
-# self,
-# name: str,
-# uri: str,
-# table_name: str,
-# text_column: str,
-# embedding_column: str,
-# embedding_dim: int,
-# ):
-# self.name = name
-# self.uri = uri
-# self.table_name = table_name
-# self.text_column = text_column
-# self.embedding_column = embedding_column
-# self.embedding_dim = embedding_dim
-#
-# # connect to db table
-# from sqlalchemy import create_engine
-#
-# self.engine = create_engine(uri)
-#
-# def generate_files(self) -> Iterator[Tuple[str, Dict]]: # -> Iterator[Document]:
-# yield self.table_name, None
-#
-# def generate_passages(self, file_text: str, file: FileMetadata, chunk_size: int = 1024) -> Iterator[Tuple[str, Dict]]: # -> Iterator[Passage]:
-# from pgvector.sqlalchemy import Vector
-# from sqlalchemy import Inspector, MetaData, Table, select
-#
-# metadata = MetaData()
-# # Create an inspector to inspect the database
-# inspector = Inspector.from_engine(self.engine)
-# table_names = inspector.get_table_names()
-# assert self.table_name in table_names, f"Table {self.table_name} not found in database: tables that exist {table_names}."
-#
-# table = Table(self.table_name, metadata, autoload_with=self.engine)
-#
-# # Prepare a select statement
-# select_statement = select(table.c[self.text_column], table.c[self.embedding_column].cast(Vector(self.embedding_dim)))
-#
-# # Execute the query and fetch the results
-# # TODO: paginate results
-# with self.engine.connect() as connection:
-# result = connection.execute(select_statement).fetchall()
-#
-# for text, embedding in result:
-# # assume that embeddings are the same model as in config
-# # TODO: don't re-compute embedding
-# yield text, {"embedding": embedding}
diff --git a/letta/memory.py b/letta/memory.py
index 8325de316..081c59d58 100644
--- a/letta/memory.py
+++ b/letta/memory.py
@@ -87,280 +87,3 @@ def summarize_messages(
printd(f"summarize_messages gpt reply: {response.choices[0]}")
reply = response.choices[0].message.content
return reply
-
-
-class ArchivalMemory(ABC):
- @abstractmethod
- def insert(self, memory_string: str):
- """Insert new archival memory
-
- :param memory_string: Memory string to insert
- :type memory_string: str
- """
-
- @abstractmethod
- def search(self, query_string, count=None, start=None) -> Tuple[List[str], int]:
- """Search archival memory
-
- :param query_string: Query string
- :type query_string: str
- :param count: Number of results to return (None for all)
- :type count: Optional[int]
- :param start: Offset to start returning results from (None if 0)
- :type start: Optional[int]
-
- :return: Tuple of (list of results, total number of results)
- """
-
- @abstractmethod
- def compile(self) -> str:
- """Convert archival memory into a string representation for a prompt"""
-
- @abstractmethod
- def count(self) -> int:
- """Count the number of memories in the archival memory"""
-
-
-class RecallMemory(ABC):
- @abstractmethod
- def text_search(self, query_string, count=None, start=None):
- """Search messages that match query_string in recall memory"""
-
- @abstractmethod
- def date_search(self, start_date, end_date, count=None, start=None):
- """Search messages between start_date and end_date in recall memory"""
-
- @abstractmethod
- def compile(self) -> str:
- """Convert recall memory into a string representation for a prompt"""
-
- @abstractmethod
- def count(self) -> int:
- """Count the number of memories in the recall memory"""
-
- @abstractmethod
- def insert(self, message: Message):
- """Insert message into recall memory"""
-
-
-class DummyRecallMemory(RecallMemory):
- """Dummy in-memory version of a recall memory database (eg run on MongoDB)
-
- Recall memory here is basically just a full conversation history with the user.
- Queryable via string matching, or date matching.
-
- Recall Memory: The AI's capability to search through past interactions,
- effectively allowing it to 'remember' prior engagements with a user.
- """
-
- def __init__(self, message_database=None, restrict_search_to_summaries=False):
- self._message_logs = [] if message_database is None else message_database # consists of full message dicts
-
- # If true, the pool of messages that can be queried are the automated summaries only
- # (generated when the conversation window needs to be shortened)
- self.restrict_search_to_summaries = restrict_search_to_summaries
-
- def __len__(self):
- return len(self._message_logs)
-
- def count(self) -> int:
- return len(self)
-
- def compile(self) -> str:
- # don't dump all the conversations, just statistics
- system_count = user_count = assistant_count = function_count = other_count = 0
- for msg in self._message_logs:
- role = msg["message"]["role"]
- if role == "system":
- system_count += 1
- elif role == "user":
- user_count += 1
- elif role == "assistant":
- assistant_count += 1
- elif role == "function":
- function_count += 1
- else:
- other_count += 1
- memory_str = (
- f"Statistics:"
- + f"\n{len(self._message_logs)} total messages"
- + f"\n{system_count} system"
- + f"\n{user_count} user"
- + f"\n{assistant_count} assistant"
- + f"\n{function_count} function"
- + f"\n{other_count} other"
- )
- return f"\n### RECALL MEMORY ###" + f"\n{memory_str}"
-
- def insert(self, message):
- raise NotImplementedError("This should be handled by the PersistenceManager, recall memory is just a search layer on top")
-
- def text_search(self, query_string, count=None, start=None):
- # in the dummy version, run an (inefficient) case-insensitive match search
- message_pool = [d for d in self._message_logs if d["message"]["role"] not in ["system", "function"]]
- start = 0 if start is None else int(start)
- count = 0 if count is None else int(count)
-
- printd(
- f"recall_memory.text_search: searching for {query_string} (c={count}, s={start}) in {len(self._message_logs)} total messages"
- )
- matches = [
- d for d in message_pool if d["message"]["content"] is not None and query_string.lower() in d["message"]["content"].lower()
- ]
- printd(f"recall_memory - matches:\n{matches[start:start+count]}")
-
- # start/count support paging through results
- if start is not None and count is not None:
- return matches[start : start + count], len(matches)
- elif start is None and count is not None:
- return matches[:count], len(matches)
- elif start is not None and count is None:
- return matches[start:], len(matches)
- else:
- return matches, len(matches)
-
- def date_search(self, start_date, end_date, count=None, start=None):
- message_pool = [d for d in self._message_logs if d["message"]["role"] not in ["system", "function"]]
-
- # First, validate the start_date and end_date format
- if not validate_date_format(start_date) or not validate_date_format(end_date):
- raise ValueError("Invalid date format. Expected format: YYYY-MM-DD")
-
- # Convert dates to datetime objects for comparison
- start_date_dt = datetime.datetime.strptime(start_date, "%Y-%m-%d")
- end_date_dt = datetime.datetime.strptime(end_date, "%Y-%m-%d")
-
- # Next, match items inside self._message_logs
- matches = [
- d
- for d in message_pool
- if start_date_dt <= datetime.datetime.strptime(extract_date_from_timestamp(d["timestamp"]), "%Y-%m-%d") <= end_date_dt
- ]
-
- # start/count support paging through results
- start = 0 if start is None else int(start)
- count = 0 if count is None else int(count)
- if start is not None and count is not None:
- return matches[start : start + count], len(matches)
- elif start is None and count is not None:
- return matches[:count], len(matches)
- elif start is not None and count is None:
- return matches[start:], len(matches)
- else:
- return matches, len(matches)
-
-
-class EmbeddingArchivalMemory(ArchivalMemory):
- """Archival memory with embedding based search"""
-
- def __init__(self, agent_state: AgentState, top_k: int = 100):
- """Init function for archival memory
-
- :param archival_memory_database: name of dataset to pre-fill archival with
- :type archival_memory_database: str
- """
- from letta.agent_store.storage import StorageConnector
-
- self.top_k = top_k
- self.agent_state = agent_state
-
- # create embedding model
- self.embed_model = embedding_model(agent_state.embedding_config)
- if agent_state.embedding_config.embedding_chunk_size is None:
- raise ValueError(f"Must set {agent_state.embedding_config.embedding_chunk_size}")
- else:
- self.embedding_chunk_size = agent_state.embedding_config.embedding_chunk_size
-
- # create storage backend
- self.storage = StorageConnector.get_archival_storage_connector(user_id=agent_state.user_id, agent_id=agent_state.id)
- # TODO: have some mechanism for cleanup otherwise will lead to OOM
- self.cache = {}
-
- def create_passage(self, text, embedding):
- return Passage(
- user_id=self.agent_state.user_id,
- agent_id=self.agent_state.id,
- text=text,
- embedding=embedding,
- embedding_config=self.agent_state.embedding_config,
- )
-
- def save(self):
- """Save the index to disk"""
- self.storage.save()
-
- def insert(self, memory_string, return_ids=False) -> Union[bool, List[str]]:
- """Embed and save memory string"""
-
- if not isinstance(memory_string, str):
- raise TypeError("memory must be a string")
-
- try:
- passages = []
-
- # breakup string into passages
- for text in parse_and_chunk_text(memory_string, self.embedding_chunk_size):
- embedding = self.embed_model.get_text_embedding(text)
- # fixing weird bug where type returned isn't a list, but instead is an object
- # eg: embedding={'object': 'list', 'data': [{'object': 'embedding', 'embedding': [-0.0071973633, -0.07893023,
- if isinstance(embedding, dict):
- try:
- embedding = embedding["data"][0]["embedding"]
- except (KeyError, IndexError):
- # TODO as a fallback, see if we can find any lists in the payload
- raise TypeError(
- f"Got back an unexpected payload from text embedding function, type={type(embedding)}, value={embedding}"
- )
- passages.append(self.create_passage(text, embedding))
-
- # grab the return IDs before the list gets modified
- ids = [str(p.id) for p in passages]
-
- # insert passages
- self.storage.insert_many(passages)
-
- if return_ids:
- return ids
- else:
- return True
-
- except Exception as e:
- print("Archival insert error", e)
- raise e
-
- def search(self, query_string, count=None, start=None):
- """Search query string"""
- start = 0 if start is None else int(start)
- count = self.top_k if count is None else int(count)
-
- if not isinstance(query_string, str):
- return TypeError("query must be a string")
-
- try:
- if query_string not in self.cache:
- # self.cache[query_string] = self.retriever.retrieve(query_string)
- query_vec = query_embedding(self.embed_model, query_string)
- self.cache[query_string] = self.storage.query(query_string, query_vec, top_k=self.top_k)
-
- end = min(count + start, len(self.cache[query_string]))
-
- results = self.cache[query_string][start:end]
- results = [{"timestamp": get_local_time(), "content": node.text} for node in results]
- return results, len(results)
- except Exception as e:
- print("Archival search error", e)
- raise e
-
- def compile(self) -> str:
- limit = 10
- passages = []
- for passage in list(self.storage.get_all(limit=limit)): # TODO: only get first 10
- passages.append(str(passage.text))
- memory_str = "\n".join(passages)
- return f"\n### ARCHIVAL MEMORY ###" + f"\n{memory_str}" + f"\nSize: {self.storage.size()}"
-
- def __len__(self):
- return self.storage.size()
-
- def count(self) -> int:
- return len(self)
diff --git a/letta/server/server.py b/letta/server/server.py
index 8f87e611a..30751c3cb 100644
--- a/letta/server/server.py
+++ b/letta/server/server.py
@@ -16,7 +16,6 @@ import letta.constants as constants
import letta.server.utils as server_utils
import letta.system as system
from letta.agent import Agent, save_agent
-from letta.agent_store.storage import StorageConnector, TableType
from letta.chat_only_agent import ChatOnlyAgent
from letta.credentials import LettaCredentials
from letta.data_sources.connectors import DataConnector, load_data
@@ -558,7 +557,6 @@ class SyncServer(Server):
raise ValueError(command)
# attach data to agent from source
- source_connector = StorageConnector.get_storage_connector(TableType.PASSAGES, self.config, user_id=user_id)
letta_agent.attach_source(
user=self.user_manager.get_user_by_id(user_id=user_id),
source_id=data_source,
@@ -1571,8 +1569,7 @@ class SyncServer(Server):
self.source_manager.delete_source(source_id=source_id, actor=actor)
# delete data from passage store
- passage_store = StorageConnector.get_storage_connector(TableType.PASSAGES, self.config, user_id=actor.id)
- passage_store.delete({"source_id": source_id})
+ self.passage_manager.delete_passages(actor=actor, limit=None, source_id=source_id)
# TODO: delete data from agent passage stores (?)
@@ -1614,11 +1611,8 @@ class SyncServer(Server):
if source is None:
raise ValueError(f"Data source {source_name} does not exist for user {user_id}")
- # get the data connectors
- passage_store = StorageConnector.get_storage_connector(TableType.PASSAGES, self.config, user_id=user_id)
-
# load data into the document store
- passage_count, document_count = load_data(connector, source, passage_store, self.source_manager, actor=user, agent_id=agent_id)
+ passage_count, document_count = load_data(connector, source, self.passage_manager, self.source_manager, actor=user, agent_id=agent_id)
return passage_count, document_count
def attach_source_to_agent(
@@ -1694,8 +1688,7 @@ class SyncServer(Server):
for source in sources:
# count number of passages
- passage_conn = StorageConnector.get_storage_connector(TableType.PASSAGES, self.config, user_id=actor.id)
- num_passages = passage_conn.size({"source_id": source.id})
+ num_passages = self.passage_manager.size(actor=actor, source_id=source.id)
# TODO: add when files table implemented
## count number of files
diff --git a/poetry.lock b/poetry.lock
index dda0b0bac..9130cc158 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -905,13 +905,37 @@ vision = ["Pillow (>=9.4.0)"]
[[package]]
name = "debugpy"
-version = "1.8.10"
+version = "1.8.9"
description = "An implementation of the Debug Adapter Protocol for Python"
optional = false
python-versions = ">=3.8"
files = [
- {file = "debugpy-1.8.10-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:97aa00af95983887806e06f37e144909d35215d66db74f8b0e9799b4eef40cfd"},
- {file = "debugpy-1.8.10.tar.gz", hash = "sha256:ee4ed903cbeb14ee1839549f953af519ffa512598ec987b2051f9c868e2249a8"},
+ {file = "debugpy-1.8.9-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:cfe1e6c6ad7178265f74981edf1154ffce97b69005212fbc90ca22ddfe3d017e"},
+ {file = "debugpy-1.8.9-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ada7fb65102a4d2c9ab62e8908e9e9f12aed9d76ef44880367bc9308ebe49a0f"},
+ {file = "debugpy-1.8.9-cp310-cp310-win32.whl", hash = "sha256:c36856343cbaa448171cba62a721531e10e7ffb0abff838004701454149bc037"},
+ {file = "debugpy-1.8.9-cp310-cp310-win_amd64.whl", hash = "sha256:17c5e0297678442511cf00a745c9709e928ea4ca263d764e90d233208889a19e"},
+ {file = "debugpy-1.8.9-cp311-cp311-macosx_14_0_universal2.whl", hash = "sha256:b74a49753e21e33e7cf030883a92fa607bddc4ede1aa4145172debc637780040"},
+ {file = "debugpy-1.8.9-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:62d22dacdb0e296966d7d74a7141aaab4bec123fa43d1a35ddcb39bf9fd29d70"},
+ {file = "debugpy-1.8.9-cp311-cp311-win32.whl", hash = "sha256:8138efff315cd09b8dcd14226a21afda4ca582284bf4215126d87342bba1cc66"},
+ {file = "debugpy-1.8.9-cp311-cp311-win_amd64.whl", hash = "sha256:ff54ef77ad9f5c425398efb150239f6fe8e20c53ae2f68367eba7ece1e96226d"},
+ {file = "debugpy-1.8.9-cp312-cp312-macosx_14_0_universal2.whl", hash = "sha256:957363d9a7a6612a37458d9a15e72d03a635047f946e5fceee74b50d52a9c8e2"},
+ {file = "debugpy-1.8.9-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5e565fc54b680292b418bb809f1386f17081d1346dca9a871bf69a8ac4071afe"},
+ {file = "debugpy-1.8.9-cp312-cp312-win32.whl", hash = "sha256:3e59842d6c4569c65ceb3751075ff8d7e6a6ada209ceca6308c9bde932bcef11"},
+ {file = "debugpy-1.8.9-cp312-cp312-win_amd64.whl", hash = "sha256:66eeae42f3137eb428ea3a86d4a55f28da9bd5a4a3d369ba95ecc3a92c1bba53"},
+ {file = "debugpy-1.8.9-cp313-cp313-macosx_14_0_universal2.whl", hash = "sha256:957ecffff80d47cafa9b6545de9e016ae8c9547c98a538ee96ab5947115fb3dd"},
+ {file = "debugpy-1.8.9-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1efbb3ff61487e2c16b3e033bc8595aea578222c08aaf3c4bf0f93fadbd662ee"},
+ {file = "debugpy-1.8.9-cp313-cp313-win32.whl", hash = "sha256:7c4d65d03bee875bcb211c76c1d8f10f600c305dbd734beaed4077e902606fee"},
+ {file = "debugpy-1.8.9-cp313-cp313-win_amd64.whl", hash = "sha256:e46b420dc1bea64e5bbedd678148be512442bc589b0111bd799367cde051e71a"},
+ {file = "debugpy-1.8.9-cp38-cp38-macosx_14_0_x86_64.whl", hash = "sha256:472a3994999fe6c0756945ffa359e9e7e2d690fb55d251639d07208dbc37caea"},
+ {file = "debugpy-1.8.9-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:365e556a4772d7d0d151d7eb0e77ec4db03bcd95f26b67b15742b88cacff88e9"},
+ {file = "debugpy-1.8.9-cp38-cp38-win32.whl", hash = "sha256:54a7e6d3014c408eb37b0b06021366ee985f1539e12fe49ca2ee0d392d9ceca5"},
+ {file = "debugpy-1.8.9-cp38-cp38-win_amd64.whl", hash = "sha256:8e99c0b1cc7bf86d83fb95d5ccdc4ad0586d4432d489d1f54e4055bcc795f693"},
+ {file = "debugpy-1.8.9-cp39-cp39-macosx_14_0_x86_64.whl", hash = "sha256:7e8b079323a56f719977fde9d8115590cb5e7a1cba2fcee0986ef8817116e7c1"},
+ {file = "debugpy-1.8.9-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6953b335b804a41f16a192fa2e7851bdcfd92173cbb2f9f777bb934f49baab65"},
+ {file = "debugpy-1.8.9-cp39-cp39-win32.whl", hash = "sha256:7e646e62d4602bb8956db88b1e72fe63172148c1e25c041e03b103a25f36673c"},
+ {file = "debugpy-1.8.9-cp39-cp39-win_amd64.whl", hash = "sha256:3d9755e77a2d680ce3d2c5394a444cf42be4a592caaf246dbfbdd100ffcf7ae5"},
+ {file = "debugpy-1.8.9-py2.py3-none-any.whl", hash = "sha256:cc37a6c9987ad743d9c3a14fa1b1a14b7e4e6041f9dd0c8abf8895fe7a97b899"},
+ {file = "debugpy-1.8.9.zip", hash = "sha256:1339e14c7d980407248f09824d1b25ff5c5616651689f1e0f0e51bdead3ea13e"},
]
[[package]]
@@ -2633,13 +2657,13 @@ query-tools = ["guidance (>=0.0.64,<0.0.65)", "jsonpath-ng (>=1.6.0,<2.0.0)", "l
[[package]]
name = "llama-index-llms-openai"
-version = "0.3.8"
+version = "0.3.9"
description = "llama-index llms openai integration"
optional = false
python-versions = "<4.0,>=3.9"
files = [
- {file = "llama_index_llms_openai-0.3.8-py3-none-any.whl", hash = "sha256:b6d507adcb735f0fc0cd38856411112250a6625971257666a77e496b96cec3ca"},
- {file = "llama_index_llms_openai-0.3.8.tar.gz", hash = "sha256:784865a3ef121bbf1cebc30159df8de3872297a8aa48631f4a785a7d38e2bd6e"},
+ {file = "llama_index_llms_openai-0.3.9-py3-none-any.whl", hash = "sha256:a237a6cfffa5169893e12b77a402874ed70bef2f5fecc96927907afee57361d2"},
+ {file = "llama_index_llms_openai-0.3.9.tar.gz", hash = "sha256:ff62cab778456dfdd32bd558d43d958a67f265678f1ef039eb2cac84a1055944"},
]
[package.dependencies]
@@ -6222,4 +6246,4 @@ tests = ["wikipedia"]
[metadata]
lock-version = "2.0"
python-versions = "<4.0,>=3.10"
-content-hash = "9c623c4d8c98b3fe724518428bb48ae85f8152453f200f767e13f48c59e0fe13"
+content-hash = "9c623c4d8c98b3fe724518428bb48ae85f8152453f200f767e13f48c59e0fe13"
\ No newline at end of file