Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: add tests to cypress
Shubham Naik0b8017853a65
diff --git a/alembic/env.py b/alembic/env.pyindex 767b7bbdb..e7dfe71c6 100644--- a/alembic/env.py+++ b/alembic/env.py@@ -1,12 +1,11 @@import osfrom logging.config import fileConfig-from sqlalchemy import engine_from_config, pool-from alembic import contextfrom letta.config import LettaConfigfrom letta.orm import Basefrom letta.settings import settings+from sqlalchemy import engine_from_config, poolletta_config = LettaConfig.load()diff --git a/alembic/versions/08b2f8225812_adding_toolsagents_orm.py b/alembic/versions/08b2f8225812_adding_toolsagents_orm.pyindex 902225ab1..d0e2cac86 100644--- a/alembic/versions/08b2f8225812_adding_toolsagents_orm.py+++ b/alembic/versions/08b2f8225812_adding_toolsagents_orm.py@@ -5,40 +5,44 @@ Revises: 3c683a662c82Create Date: 2024-12-05 16:46:51.258831"""+from typing import Sequence, Union-from alembic import opimport sqlalchemy as sa-+from alembic import op# revision identifiers, used by Alembic.-revision: str = '08b2f8225812'-down_revision: Union[str, None] = '3c683a662c82'+revision: str = "08b2f8225812"+down_revision: Union[str, None] = "3c683a662c82"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:# ### commands auto generated by Alembic - please adjust! ###- op.create_table('tools_agents',- sa.Column('agent_id', sa.String(), nullable=False),- sa.Column('tool_id', sa.String(), nullable=False),- sa.Column('tool_name', sa.String(), nullable=False),- sa.Column('id', sa.String(), nullable=False),- sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),- sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),- sa.Column('is_deleted', sa.Boolean(), server_default=sa.text('FALSE'), nullable=False),- sa.Column('_created_by_id', sa.String(), nullable=True),- sa.Column('_last_updated_by_id', sa.String(), nullable=True),- sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),- sa.ForeignKeyConstraint(['tool_id'], ['tools.id'], name='fk_tool_id'),- sa.PrimaryKeyConstraint('agent_id', 'tool_id', 'tool_name', 'id'),- sa.UniqueConstraint('agent_id', 'tool_name', name='unique_tool_per_agent')+ op.create_table(+ "tools_agents",+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("tool_id", sa.String(), nullable=False),+ sa.Column("tool_name", sa.String(), nullable=False),+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),+ sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False),+ sa.Column("_created_by_id", sa.String(), nullable=True),+ sa.Column("_last_updated_by_id", sa.String(), nullable=True),+ sa.ForeignKeyConstraint(+ ["agent_id"],+ ["agents.id"],+ ),+ sa.ForeignKeyConstraint(["tool_id"], ["tools.id"], name="fk_tool_id"),+ sa.PrimaryKeyConstraint("agent_id", "tool_id", "tool_name", "id"),+ sa.UniqueConstraint("agent_id", "tool_name", name="unique_tool_per_agent"),)# ### end Alembic commands ###def downgrade() -> None:# ### commands auto generated by Alembic - please adjust! ###- op.drop_table('tools_agents')+ op.drop_table("tools_agents")# ### end Alembic commands ###diff --git a/alembic/versions/1c8880d671ee_make_an_blocks_agents_mapping_table.py b/alembic/versions/1c8880d671ee_make_an_blocks_agents_mapping_table.pyindex ffcb0b671..6890e0ed7 100644--- a/alembic/versions/1c8880d671ee_make_an_blocks_agents_mapping_table.py+++ b/alembic/versions/1c8880d671ee_make_an_blocks_agents_mapping_table.py@@ -9,7 +9,6 @@ Create Date: 2024-11-22 15:42:47.209229from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import op# revision identifiers, used by Alembic.diff --git a/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.py b/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.pyindex 4f9b746d5..62b97e9d7 100644--- a/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.py+++ b/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.py@@ -9,9 +9,8 @@ Create Date: 2024-12-04 15:59:41.708396from typing import Sequence, Unionimport sqlalchemy as sa-from sqlalchemy.dialects import postgresql-from alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "3c683a662c82"diff --git a/alembic/versions/4e88e702f85e_drop_api_tokens_table_in_oss.py b/alembic/versions/4e88e702f85e_drop_api_tokens_table_in_oss.pyindex 75a90445a..b692e8556 100644--- a/alembic/versions/4e88e702f85e_drop_api_tokens_table_in_oss.py+++ b/alembic/versions/4e88e702f85e_drop_api_tokens_table_in_oss.py@@ -9,7 +9,6 @@ Create Date: 2024-12-13 17:19:55.796210from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import op# revision identifiers, used by Alembic.diff --git a/alembic/versions/54dec07619c4_divide_passage_table_into_.py b/alembic/versions/54dec07619c4_divide_passage_table_into_.pyindex afe9d4185..ead70ec64 100644--- a/alembic/versions/54dec07619c4_divide_passage_table_into_.py+++ b/alembic/versions/54dec07619c4_divide_passage_table_into_.py@@ -5,18 +5,18 @@ Revises: 4e88e702f85eCreate Date: 2024-12-14 17:23:08.772554"""+from typing import Sequence, Union+import sqlalchemy as safrom alembic import op+from letta.orm.custom_columns import EmbeddingConfigColumnfrom pgvector.sqlalchemy import Vector-import sqlalchemy as safrom sqlalchemy.dialects import postgresql-from letta.orm.custom_columns import EmbeddingConfigColumn-# revision identifiers, used by Alembic.-revision: str = '54dec07619c4'-down_revision: Union[str, None] = '4e88e702f85e'+revision: str = "54dec07619c4"+down_revision: Union[str, None] = "4e88e702f85e"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None@@ -24,82 +24,88 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:# ### commands auto generated by Alembic - please adjust! ###op.create_table(- 'agent_passages',- sa.Column('id', sa.String(), nullable=False),- sa.Column('text', sa.String(), nullable=False),- sa.Column('embedding_config', EmbeddingConfigColumn(), nullable=False),- sa.Column('metadata_', sa.JSON(), nullable=False),- sa.Column('embedding', Vector(dim=4096), nullable=True),- sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),- sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),- sa.Column('is_deleted', sa.Boolean(), server_default=sa.text('FALSE'), nullable=False),- sa.Column('_created_by_id', sa.String(), nullable=True),- sa.Column('_last_updated_by_id', sa.String(), nullable=True),- sa.Column('organization_id', sa.String(), nullable=False),- sa.Column('agent_id', sa.String(), nullable=False),- sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ondelete='CASCADE'),- sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),- sa.PrimaryKeyConstraint('id')+ "agent_passages",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("text", sa.String(), nullable=False),+ sa.Column("embedding_config", EmbeddingConfigColumn(), nullable=False),+ sa.Column("metadata_", sa.JSON(), nullable=False),+ sa.Column("embedding", Vector(dim=4096), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),+ sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False),+ sa.Column("_created_by_id", sa.String(), nullable=True),+ sa.Column("_last_updated_by_id", sa.String(), nullable=True),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(+ ["organization_id"],+ ["organizations.id"],+ ),+ sa.PrimaryKeyConstraint("id"),)- op.create_index('agent_passages_org_idx', 'agent_passages', ['organization_id'], unique=False)+ op.create_index("agent_passages_org_idx", "agent_passages", ["organization_id"], unique=False)op.create_table(- 'source_passages',- sa.Column('id', sa.String(), nullable=False),- sa.Column('text', sa.String(), nullable=False),- sa.Column('embedding_config', EmbeddingConfigColumn(), nullable=False),- sa.Column('metadata_', sa.JSON(), nullable=False),- sa.Column('embedding', Vector(dim=4096), nullable=True),- sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),- sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),- sa.Column('is_deleted', sa.Boolean(), server_default=sa.text('FALSE'), nullable=False),- sa.Column('_created_by_id', sa.String(), nullable=True),- sa.Column('_last_updated_by_id', sa.String(), nullable=True),- sa.Column('organization_id', sa.String(), nullable=False),- sa.Column('file_id', sa.String(), nullable=True),- sa.Column('source_id', sa.String(), nullable=False),- sa.ForeignKeyConstraint(['file_id'], ['files.id'], ondelete='CASCADE'),- sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),- sa.ForeignKeyConstraint(['source_id'], ['sources.id'], ondelete='CASCADE'),- sa.PrimaryKeyConstraint('id')+ "source_passages",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("text", sa.String(), nullable=False),+ sa.Column("embedding_config", EmbeddingConfigColumn(), nullable=False),+ sa.Column("metadata_", sa.JSON(), nullable=False),+ sa.Column("embedding", Vector(dim=4096), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True),+ sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False),+ sa.Column("_created_by_id", sa.String(), nullable=True),+ sa.Column("_last_updated_by_id", sa.String(), nullable=True),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("file_id", sa.String(), nullable=True),+ sa.Column("source_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["file_id"], ["files.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(+ ["organization_id"],+ ["organizations.id"],+ ),+ sa.ForeignKeyConstraint(["source_id"], ["sources.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),)- op.create_index('source_passages_org_idx', 'source_passages', ['organization_id'], unique=False)- op.drop_table('passages')- op.drop_constraint('files_source_id_fkey', 'files', type_='foreignkey')- op.create_foreign_key(None, 'files', 'sources', ['source_id'], ['id'], ondelete='CASCADE')- op.drop_constraint('messages_agent_id_fkey', 'messages', type_='foreignkey')- op.create_foreign_key(None, 'messages', 'agents', ['agent_id'], ['id'], ondelete='CASCADE')+ op.create_index("source_passages_org_idx", "source_passages", ["organization_id"], unique=False)+ op.drop_table("passages")+ op.drop_constraint("files_source_id_fkey", "files", type_="foreignkey")+ op.create_foreign_key(None, "files", "sources", ["source_id"], ["id"], ondelete="CASCADE")+ op.drop_constraint("messages_agent_id_fkey", "messages", type_="foreignkey")+ op.create_foreign_key(None, "messages", "agents", ["agent_id"], ["id"], ondelete="CASCADE")# ### end Alembic commands ###def downgrade() -> None:# ### commands auto generated by Alembic - please adjust! ###- op.drop_constraint(None, 'messages', type_='foreignkey')- op.create_foreign_key('messages_agent_id_fkey', 'messages', 'agents', ['agent_id'], ['id'])- op.drop_constraint(None, 'files', type_='foreignkey')- op.create_foreign_key('files_source_id_fkey', 'files', 'sources', ['source_id'], ['id'])+ op.drop_constraint(None, "messages", type_="foreignkey")+ op.create_foreign_key("messages_agent_id_fkey", "messages", "agents", ["agent_id"], ["id"])+ op.drop_constraint(None, "files", type_="foreignkey")+ op.create_foreign_key("files_source_id_fkey", "files", "sources", ["source_id"], ["id"])op.create_table(- 'passages',- sa.Column('id', sa.VARCHAR(), autoincrement=False, nullable=False),- sa.Column('text', sa.VARCHAR(), autoincrement=False, nullable=False),- sa.Column('file_id', sa.VARCHAR(), autoincrement=False, nullable=True),- sa.Column('agent_id', sa.VARCHAR(), autoincrement=False, nullable=True),- sa.Column('source_id', sa.VARCHAR(), autoincrement=False, nullable=True),- sa.Column('embedding', Vector(dim=4096), autoincrement=False, nullable=True),- sa.Column('embedding_config', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=False),- sa.Column('metadata_', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=False),- sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=False),- sa.Column('updated_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=True),- sa.Column('is_deleted', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False),- sa.Column('_created_by_id', sa.VARCHAR(), autoincrement=False, nullable=True),- sa.Column('_last_updated_by_id', sa.VARCHAR(), autoincrement=False, nullable=True),- sa.Column('organization_id', sa.VARCHAR(), autoincrement=False, nullable=False),- sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], name='passages_agent_id_fkey'),- sa.ForeignKeyConstraint(['file_id'], ['files.id'], name='passages_file_id_fkey', ondelete='CASCADE'),- sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], name='passages_organization_id_fkey'),- sa.PrimaryKeyConstraint('id', name='passages_pkey')+ "passages",+ sa.Column("id", sa.VARCHAR(), autoincrement=False, nullable=False),+ sa.Column("text", sa.VARCHAR(), autoincrement=False, nullable=False),+ sa.Column("file_id", sa.VARCHAR(), autoincrement=False, nullable=True),+ sa.Column("agent_id", sa.VARCHAR(), autoincrement=False, nullable=True),+ sa.Column("source_id", sa.VARCHAR(), autoincrement=False, nullable=True),+ sa.Column("embedding", Vector(dim=4096), autoincrement=False, nullable=True),+ sa.Column("embedding_config", postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=False),+ sa.Column("metadata_", postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=False),+ sa.Column("created_at", postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=False),+ sa.Column("updated_at", postgresql.TIMESTAMP(timezone=True), server_default=sa.text("now()"), autoincrement=False, nullable=True),+ sa.Column("is_deleted", sa.BOOLEAN(), server_default=sa.text("false"), autoincrement=False, nullable=False),+ sa.Column("_created_by_id", sa.VARCHAR(), autoincrement=False, nullable=True),+ sa.Column("_last_updated_by_id", sa.VARCHAR(), autoincrement=False, nullable=True),+ sa.Column("organization_id", sa.VARCHAR(), autoincrement=False, nullable=False),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], name="passages_agent_id_fkey"),+ sa.ForeignKeyConstraint(["file_id"], ["files.id"], name="passages_file_id_fkey", ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"], name="passages_organization_id_fkey"),+ sa.PrimaryKeyConstraint("id", name="passages_pkey"),)- op.drop_index('source_passages_org_idx', table_name='source_passages')- op.drop_table('source_passages')- op.drop_index('agent_passages_org_idx', table_name='agent_passages')- op.drop_table('agent_passages')+ op.drop_index("source_passages_org_idx", table_name="source_passages")+ op.drop_table("source_passages")+ op.drop_index("agent_passages_org_idx", table_name="agent_passages")+ op.drop_table("agent_passages")# ### end Alembic commands ###diff --git a/alembic/versions/5987401b40ae_refactor_agent_memory.py b/alembic/versions/5987401b40ae_refactor_agent_memory.pyindex 889e9425b..84e4ebe2d 100644--- a/alembic/versions/5987401b40ae_refactor_agent_memory.py+++ b/alembic/versions/5987401b40ae_refactor_agent_memory.py@@ -9,9 +9,8 @@ Create Date: 2024-11-25 14:35:00.896507from typing import Sequence, Unionimport sqlalchemy as sa-from sqlalchemy.dialects import postgresql-from alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "5987401b40ae"diff --git a/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.py b/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.pyindex 73254e39e..f200e65e8 100644--- a/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.py+++ b/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.py@@ -9,9 +9,8 @@ Create Date: 2024-12-05 14:02:04.163150from typing import Sequence, Unionimport sqlalchemy as sa-from sqlalchemy.dialects import postgresql-from alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "95badb46fdf9"diff --git a/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.py b/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.pyindex 21f6a3961..6ef44d476 100644--- a/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.py+++ b/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.py@@ -8,12 +8,11 @@ Create Date: 2024-10-11 14:19:19.875656from typing import Sequence, Union+import letta.ormimport pgvectorimport sqlalchemy as sa-from sqlalchemy.dialects import postgresql--import letta.ormfrom alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "9a505cc7eca9"diff --git a/alembic/versions/a91994b9752f_add_column_to_tools_table_to_contain_.py b/alembic/versions/a91994b9752f_add_column_to_tools_table_to_contain_.pyindex f8da3856b..157e87ef3 100644--- a/alembic/versions/a91994b9752f_add_column_to_tools_table_to_contain_.py+++ b/alembic/versions/a91994b9752f_add_column_to_tools_table_to_contain_.py@@ -9,7 +9,6 @@ Create Date: 2024-12-09 18:27:25.650079from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import opfrom letta.constants import FUNCTION_RETURN_CHAR_LIMITdiff --git a/alembic/versions/b6d7ca024aa9_add_agents_tags_table.py b/alembic/versions/b6d7ca024aa9_add_agents_tags_table.pyindex 2aec8a09f..638bc5b5c 100644--- a/alembic/versions/b6d7ca024aa9_add_agents_tags_table.py+++ b/alembic/versions/b6d7ca024aa9_add_agents_tags_table.py@@ -9,7 +9,6 @@ Create Date: 2024-11-06 10:48:08.424108from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import op# revision identifiers, used by Alembic.diff --git a/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.py b/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.pyindex a16fdae44..fb0eafab6 100644--- a/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.py+++ b/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.py@@ -5,25 +5,26 @@ Revises: a91994b9752fCreate Date: 2024-12-10 15:05:32.335519"""+from typing import Sequence, Union-from alembic import opimport sqlalchemy as sa+from alembic import opfrom sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.-revision: str = 'c5d964280dff'-down_revision: Union[str, None] = 'a91994b9752f'+revision: str = "c5d964280dff"+down_revision: Union[str, None] = "a91994b9752f"branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:# ### commands auto generated by Alembic - please adjust! ###- op.add_column('passages', sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True))- op.add_column('passages', sa.Column('is_deleted', sa.Boolean(), server_default=sa.text('FALSE'), nullable=False))- op.add_column('passages', sa.Column('_created_by_id', sa.String(), nullable=True))- op.add_column('passages', sa.Column('_last_updated_by_id', sa.String(), nullable=True))+ op.add_column("passages", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))+ op.add_column("passages", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))+ op.add_column("passages", sa.Column("_created_by_id", sa.String(), nullable=True))+ op.add_column("passages", sa.Column("_last_updated_by_id", sa.String(), nullable=True))# Data migration step:op.add_column("passages", sa.Column("organization_id", sa.String(), nullable=True))@@ -41,48 +42,32 @@ def upgrade() -> None:# Set `organization_id` as non-nullable after populationop.alter_column("passages", "organization_id", nullable=False)- op.alter_column('passages', 'text',- existing_type=sa.VARCHAR(),- nullable=False)- op.alter_column('passages', 'embedding_config',- existing_type=postgresql.JSON(astext_type=sa.Text()),- nullable=False)- op.alter_column('passages', 'metadata_',- existing_type=postgresql.JSON(astext_type=sa.Text()),- nullable=False)- op.alter_column('passages', 'created_at',- existing_type=postgresql.TIMESTAMP(timezone=True),- nullable=False)- op.drop_index('passage_idx_user', table_name='passages')- op.create_foreign_key(None, 'passages', 'organizations', ['organization_id'], ['id'])- op.create_foreign_key(None, 'passages', 'agents', ['agent_id'], ['id'])- op.create_foreign_key(None, 'passages', 'files', ['file_id'], ['id'], ondelete='CASCADE')- op.drop_column('passages', 'user_id')+ op.alter_column("passages", "text", existing_type=sa.VARCHAR(), nullable=False)+ op.alter_column("passages", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False)+ op.alter_column("passages", "metadata_", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False)+ op.alter_column("passages", "created_at", existing_type=postgresql.TIMESTAMP(timezone=True), nullable=False)+ op.drop_index("passage_idx_user", table_name="passages")+ op.create_foreign_key(None, "passages", "organizations", ["organization_id"], ["id"])+ op.create_foreign_key(None, "passages", "agents", ["agent_id"], ["id"])+ op.create_foreign_key(None, "passages", "files", ["file_id"], ["id"], ondelete="CASCADE")+ op.drop_column("passages", "user_id")# ### end Alembic commands ###def downgrade() -> None:# ### commands auto generated by Alembic - please adjust! ###- op.add_column('passages', sa.Column('user_id', sa.VARCHAR(), autoincrement=False, nullable=False))- op.drop_constraint(None, 'passages', type_='foreignkey')- op.drop_constraint(None, 'passages', type_='foreignkey')- op.drop_constraint(None, 'passages', type_='foreignkey')- op.create_index('passage_idx_user', 'passages', ['user_id', 'agent_id', 'file_id'], unique=False)- op.alter_column('passages', 'created_at',- existing_type=postgresql.TIMESTAMP(timezone=True),- nullable=True)- op.alter_column('passages', 'metadata_',- existing_type=postgresql.JSON(astext_type=sa.Text()),- nullable=True)- op.alter_column('passages', 'embedding_config',- existing_type=postgresql.JSON(astext_type=sa.Text()),- nullable=True)- op.alter_column('passages', 'text',- existing_type=sa.VARCHAR(),- nullable=True)- op.drop_column('passages', 'organization_id')- op.drop_column('passages', '_last_updated_by_id')- op.drop_column('passages', '_created_by_id')- op.drop_column('passages', 'is_deleted')- op.drop_column('passages', 'updated_at')+ op.add_column("passages", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=False))+ op.drop_constraint(None, "passages", type_="foreignkey")+ op.drop_constraint(None, "passages", type_="foreignkey")+ op.drop_constraint(None, "passages", type_="foreignkey")+ op.create_index("passage_idx_user", "passages", ["user_id", "agent_id", "file_id"], unique=False)+ op.alter_column("passages", "created_at", existing_type=postgresql.TIMESTAMP(timezone=True), nullable=True)+ op.alter_column("passages", "metadata_", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True)+ op.alter_column("passages", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True)+ op.alter_column("passages", "text", existing_type=sa.VARCHAR(), nullable=True)+ op.drop_column("passages", "organization_id")+ op.drop_column("passages", "_last_updated_by_id")+ op.drop_column("passages", "_created_by_id")+ op.drop_column("passages", "is_deleted")+ op.drop_column("passages", "updated_at")# ### end Alembic commands ###diff --git a/alembic/versions/c85a3d07c028_move_files_to_orm.py b/alembic/versions/c85a3d07c028_move_files_to_orm.pyindex b05d79303..7d853e6a8 100644--- a/alembic/versions/c85a3d07c028_move_files_to_orm.py+++ b/alembic/versions/c85a3d07c028_move_files_to_orm.py@@ -9,7 +9,6 @@ Create Date: 2024-11-12 13:58:57.221081from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import op# revision identifiers, used by Alembic.diff --git a/alembic/versions/cda66b6cb0d6_move_sources_to_orm.py b/alembic/versions/cda66b6cb0d6_move_sources_to_orm.pyindex f46bef6b4..ae10edbd0 100644--- a/alembic/versions/cda66b6cb0d6_move_sources_to_orm.py+++ b/alembic/versions/cda66b6cb0d6_move_sources_to_orm.py@@ -9,9 +9,8 @@ Create Date: 2024-11-07 13:29:57.186107from typing import Sequence, Unionimport sqlalchemy as sa-from sqlalchemy.dialects import postgresql-from alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "cda66b6cb0d6"diff --git a/alembic/versions/d05669b60ebe_migrate_agents_to_orm.py b/alembic/versions/d05669b60ebe_migrate_agents_to_orm.pyindex d03652c85..61b24f5ed 100644--- a/alembic/versions/d05669b60ebe_migrate_agents_to_orm.py+++ b/alembic/versions/d05669b60ebe_migrate_agents_to_orm.py@@ -9,9 +9,8 @@ Create Date: 2024-12-12 10:25:31.825635from typing import Sequence, Unionimport sqlalchemy as sa-from sqlalchemy.dialects import postgresql-from alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "d05669b60ebe"diff --git a/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.py b/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.pyindex e8733313f..5c0dab194 100644--- a/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.py+++ b/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.py@@ -8,11 +8,10 @@ Create Date: 2024-11-05 15:03:12.350096from typing import Sequence, Union-import sqlalchemy as sa-from sqlalchemy.dialects import postgresql-import letta+import sqlalchemy as safrom alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "d14ae606614c"diff --git a/alembic/versions/e1a625072dbf_tweak_created_at_field_for_messages.py b/alembic/versions/e1a625072dbf_tweak_created_at_field_for_messages.pyindex fb425db31..4fd8abd2d 100644--- a/alembic/versions/e1a625072dbf_tweak_created_at_field_for_messages.py+++ b/alembic/versions/e1a625072dbf_tweak_created_at_field_for_messages.py@@ -8,9 +8,8 @@ Create Date: 2024-12-07 14:28:27.643583from typing import Sequence, Union-from sqlalchemy.dialects import postgresql-from alembic import op+from sqlalchemy.dialects import postgresql# revision identifiers, used by Alembic.revision: str = "e1a625072dbf"diff --git a/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.py b/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.pyindex 9e7fa270c..37a67d88e 100644--- a/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.py+++ b/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.py@@ -9,7 +9,6 @@ Create Date: 2024-11-18 15:40:13.149438from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import op# revision identifiers, used by Alembic.diff --git a/alembic/versions/f81ceea2c08d_create_sandbox_config_and_sandbox_env_.py b/alembic/versions/f81ceea2c08d_create_sandbox_config_and_sandbox_env_.pyindex 55332bfc1..32a1b6779 100644--- a/alembic/versions/f81ceea2c08d_create_sandbox_config_and_sandbox_env_.py+++ b/alembic/versions/f81ceea2c08d_create_sandbox_config_and_sandbox_env_.py@@ -9,7 +9,6 @@ Create Date: 2024-11-14 17:51:27.263561from typing import Sequence, Unionimport sqlalchemy as sa-from alembic import op# revision identifiers, used by Alembic.diff --git a/examples/swarm/simple.py b/examples/swarm/simple.pyindex 8e10c486d..7bedb0329 100644--- a/examples/swarm/simple.py+++ b/examples/swarm/simple.py@@ -1,7 +1,6 @@import typer-from swarm import Swarm-from letta import EmbeddingConfig, LLMConfig+from swarm import Swarm"""This is an example of how to implement the basic example provided by OpenAI for tranferring a conversation between two agents:diff --git a/examples/swarm/swarm.py b/examples/swarm/swarm.pyindex ef080806d..40552997b 100644--- a/examples/swarm/swarm.py+++ b/examples/swarm/swarm.py@@ -2,7 +2,6 @@ import jsonfrom typing import List, Optionalimport typer-from letta import AgentState, EmbeddingConfig, LLMConfig, create_clientfrom letta.schemas.agent import AgentTypefrom letta.schemas.memory import BasicBlockMemory, Blockdiff --git a/examples/tool_rule_usage.py b/examples/tool_rule_usage.pyindex 7d04df6c5..4e0193f8f 100644--- a/examples/tool_rule_usage.py+++ b/examples/tool_rule_usage.py@@ -5,8 +5,8 @@ from letta import create_clientfrom letta.schemas.letta_message import ToolCallMessagefrom letta.schemas.tool_rule import ChildToolRule, InitToolRule, TerminalToolRulefrom tests.helpers.endpoints_helper import (- assert_invoked_send_message_with_keyword,- setup_agent,+ assert_invoked_send_message_with_keyword,+ setup_agent,)from tests.helpers.utils import cleanupfrom tests.test_model_letta_perfomance import llm_config_dirdiff --git a/letta/benchmark/benchmark.py b/letta/benchmark/benchmark.pyindex 7109210e9..b7c01ab7e 100644--- a/letta/benchmark/benchmark.py+++ b/letta/benchmark/benchmark.py@@ -5,7 +5,6 @@ import uuidfrom typing import Annotated, Unionimport typer-from letta import LocalClient, RESTClient, create_clientfrom letta.benchmark.constants import HUMAN, PERSONA, PROMPTS, TRIESfrom letta.config import LettaConfigdiff --git a/letta/cli/cli.py b/letta/cli/cli.pyindex e5a649f7c..efd58df75 100644--- a/letta/cli/cli.py+++ b/letta/cli/cli.py@@ -3,10 +3,9 @@ import sysfrom enum import Enumfrom typing import Annotated, Optional+import letta.utils as utilsimport questionaryimport typer--import letta.utils as utilsfrom letta import create_clientfrom letta.agent import Agent, save_agentfrom letta.config import LettaConfigdiff --git a/letta/cli/cli_config.py b/letta/cli/cli_config.pyindex 8278d5531..f70b466b2 100644--- a/letta/cli/cli_config.py+++ b/letta/cli/cli_config.py@@ -5,11 +5,10 @@ from typing import Annotated, List, Optionalimport questionaryimport typer+from letta import utilsfrom prettytable.colortable import ColorTable, Themesfrom tqdm import tqdm-from letta import utils-app = typer.Typer()diff --git a/letta/cli/cli_load.py b/letta/cli/cli_load.pyindex b27da4d81..e1d7b1b8c 100644--- a/letta/cli/cli_load.py+++ b/letta/cli/cli_load.py@@ -13,7 +13,6 @@ from typing import Annotated, List, Optionalimport questionaryimport typer-from letta import create_clientfrom letta.data_sources.connectors import DirectoryConnectordiff --git a/letta/client/client.py b/letta/client/client.pyindex bb6d2f0ff..af81a5626 100644--- a/letta/client/client.py+++ b/letta/client/client.py@@ -2,9 +2,8 @@ import loggingimport timefrom typing import Callable, Dict, Generator, List, Optional, Union-import requests-import letta.utils+import requestsfrom letta.constants import (ADMIN_PREFIX,BASE_MEMORY_TOOLS,diff --git a/letta/client/streaming.py b/letta/client/streaming.pyindex a364ada6f..7d7e11292 100644--- a/letta/client/streaming.py+++ b/letta/client/streaming.py@@ -3,14 +3,13 @@ from typing import Generatorimport httpxfrom httpx_sse import SSEError, connect_sse-from letta.constants import OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRINGfrom letta.errors import LLMErrorfrom letta.schemas.enums import MessageStreamStatusfrom letta.schemas.letta_message import (+ ReasoningMessage,ToolCallMessage,ToolReturnMessage,- ReasoningMessage,)from letta.schemas.letta_response import LettaStreamingResponsefrom letta.schemas.usage import LettaUsageStatisticsdiff --git a/letta/client/utils.py b/letta/client/utils.pyindex 1ff28f8c9..871269c7c 100644--- a/letta/client/utils.py+++ b/letta/client/utils.py@@ -3,12 +3,11 @@ from datetime import datetimefrom typing import Optionalfrom IPython.display import HTML, display-from sqlalchemy.testing.plugin.plugin_base import warnings-from letta.local_llm.constants import (ASSISTANT_MESSAGE_CLI_SYMBOL,INNER_THOUGHTS_CLI_SYMBOL,)+from sqlalchemy.testing.plugin.plugin_base import warningsdef pprint(messages):diff --git a/letta/data_sources/connectors.py b/letta/data_sources/connectors.pyindex f9fdd2616..3d5778104 100644--- a/letta/data_sources/connectors.py+++ b/letta/data_sources/connectors.py@@ -1,7 +1,6 @@from typing import Dict, Iterator, List, Tupleimport typer-from letta.data_sources.connectors_helper import (assert_all_files_exist_locally,extract_metadata_from_files,@@ -14,6 +13,7 @@ from letta.schemas.source import Sourcefrom letta.services.passage_manager import PassageManagerfrom letta.services.source_manager import SourceManager+class DataConnector:"""Base class for data connectors that can be extended to generate files and passages from a custom data source.diff --git a/letta/embeddings.py b/letta/embeddings.pyindex 0d82d158a..e27ee1add 100644--- a/letta/embeddings.py+++ b/letta/embeddings.py@@ -3,7 +3,6 @@ from typing import Any, List, Optionalimport numpy as npimport tiktoken-from letta.constants import (EMBEDDING_TO_TOKENIZER_DEFAULT,EMBEDDING_TO_TOKENIZER_MAP,diff --git a/letta/errors.py b/letta/errors.pyindex 4957139be..2c4703c0d 100644--- a/letta/errors.py+++ b/letta/errors.py@@ -52,12 +52,10 @@ class LettaConfigurationError(LettaError):class LettaAgentNotFoundError(LettaError):"""Error raised when an agent is not found."""- passclass LettaUserNotFoundError(LettaError):"""Error raised when a user is not found."""- passclass LLMError(LettaError):diff --git a/letta/functions/function_sets/extras.py b/letta/functions/function_sets/extras.pyindex f29f85ba4..c911ffca1 100644--- a/letta/functions/function_sets/extras.py+++ b/letta/functions/function_sets/extras.py@@ -3,7 +3,6 @@ import uuidfrom typing import Optionalimport requests-from letta.constants import (MESSAGE_CHATGPT_FUNCTION_MODEL,MESSAGE_CHATGPT_FUNCTION_SYSTEM_MESSAGE,diff --git a/letta/helpers/tool_rule_solver.py b/letta/helpers/tool_rule_solver.pyindex 02919b2e8..24eff3075 100644--- a/letta/helpers/tool_rule_solver.py+++ b/letta/helpers/tool_rule_solver.py@@ -1,8 +1,6 @@import jsonfrom typing import List, Optional, Union-from pydantic import BaseModel, Field-from letta.schemas.enums import ToolRuleTypefrom letta.schemas.tool_rule import (BaseToolRule,@@ -11,6 +9,7 @@ from letta.schemas.tool_rule import (InitToolRule,TerminalToolRule,)+from pydantic import BaseModel, Fieldclass ToolRuleValidationError(Exception):@@ -50,7 +49,6 @@ class ToolRulesSolver(BaseModel):assert isinstance(rule, TerminalToolRule)self.terminal_tool_rules.append(rule)-def update_tool_usage(self, tool_name: str):"""Update the internal state to track the last tool called."""self.last_tool_name = tool_name@@ -88,7 +86,7 @@ class ToolRulesSolver(BaseModel):return any(rule.tool_name == tool_name for rule in self.tool_rules)def validate_conditional_tool(self, rule: ConditionalToolRule):- '''+ """Validate a conditional tool ruleArgs:@@ -96,13 +94,13 @@ class ToolRulesSolver(BaseModel):Raises:ToolRuleValidationError: If the rule is invalid- '''+ """if len(rule.child_output_mapping) == 0:raise ToolRuleValidationError("Conditional tool rule must have at least one child tool.")return Truedef evaluate_conditional_tool(self, tool: ConditionalToolRule, last_function_response: str) -> str:- '''+ """Parse function response to determine which child tool to use based on the mappingArgs:@@ -111,7 +109,7 @@ class ToolRulesSolver(BaseModel):Returns:str: The name of the child tool to use next- '''+ """json_response = json.loads(last_function_response)function_output = json_response["message"]diff --git a/letta/interface.py b/letta/interface.pyindex aac10453f..41276b17a 100644--- a/letta/interface.py+++ b/letta/interface.py@@ -3,7 +3,6 @@ from abc import ABC, abstractmethodfrom typing import List, Optionalfrom colorama import Fore, Style, init-from letta.constants import CLI_WARNING_PREFIXfrom letta.local_llm.constants import (ASSISTANT_MESSAGE_CLI_SYMBOL,diff --git a/letta/llm_api/anthropic.py b/letta/llm_api/anthropic.pyindex 4cca920a5..78980d520 100644--- a/letta/llm_api/anthropic.py+++ b/letta/llm_api/anthropic.py@@ -102,13 +102,9 @@ def convert_tools_to_anthropic_format(tools: List[Tool]) -> List[dict]:formatted_tools = []for tool in tools:formatted_tool = {- "name" : tool.function.name,- "description" : tool.function.description,- "input_schema" : tool.function.parameters or {- "type": "object",- "properties": {},- "required": []- }+ "name": tool.function.name,+ "description": tool.function.description,+ "input_schema": tool.function.parameters or {"type": "object", "properties": {}, "required": []},}formatted_tools.append(formatted_tool)@@ -346,7 +342,7 @@ def anthropic_chat_completions_request(data["tool_choice"] = {"type": "tool", # Changed from "function" to "tool""name": anthropic_tools[0]["name"], # Directly specify name without nested "function" object- "disable_parallel_tool_use": True # Force single tool use+ "disable_parallel_tool_use": True, # Force single tool use}# Move 'system' to the top leveldiff --git a/letta/llm_api/azure_openai.py b/letta/llm_api/azure_openai.pyindex e60b547be..047f2f86b 100644--- a/letta/llm_api/azure_openai.py+++ b/letta/llm_api/azure_openai.py@@ -1,7 +1,6 @@from collections import defaultdictimport requests-from letta.llm_api.helpers import make_post_requestfrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.openai.chat_completion_response import ChatCompletionResponsediff --git a/letta/llm_api/cohere.py b/letta/llm_api/cohere.pyindex 1e8b5fd6c..844e618f4 100644--- a/letta/llm_api/cohere.py+++ b/letta/llm_api/cohere.py@@ -3,7 +3,6 @@ import uuidfrom typing import List, Optional, Unionimport requests-from letta.local_llm.utils import count_tokensfrom letta.schemas.message import Messagefrom letta.schemas.openai.chat_completion_request import ChatCompletionRequest, Tooldiff --git a/letta/llm_api/google_ai.py b/letta/llm_api/google_ai.pyindex 57071a239..f16fc447c 100644--- a/letta/llm_api/google_ai.py+++ b/letta/llm_api/google_ai.py@@ -2,7 +2,6 @@ import uuidfrom typing import List, Optional, Tupleimport requests-from letta.constants import NON_USER_MSG_PREFIXfrom letta.llm_api.helpers import make_post_requestfrom letta.local_llm.json_parser import clean_json_string_extra_backslashdiff --git a/letta/llm_api/helpers.py b/letta/llm_api/helpers.pyindex 1244b6ffe..25f77e244 100644--- a/letta/llm_api/helpers.py+++ b/letta/llm_api/helpers.py@@ -5,7 +5,6 @@ from collections import OrderedDictfrom typing import Any, List, Unionimport requests-from letta.constants import OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRINGfrom letta.schemas.openai.chat_completion_response import ChatCompletionResponse, Choicefrom letta.utils import json_dumps, printddiff --git a/letta/llm_api/llm_api_tools.py b/letta/llm_api/llm_api_tools.pyindex 578779d72..7b39b31ae 100644--- a/letta/llm_api/llm_api_tools.py+++ b/letta/llm_api/llm_api_tools.py@@ -3,7 +3,6 @@ import timefrom typing import List, Optional, Unionimport requests-from letta.constants import CLI_WARNING_PREFIXfrom letta.errors import LettaConfigurationError, RateLimitExceededErrorfrom letta.llm_api.anthropic import anthropic_chat_completions_request@@ -255,12 +254,7 @@ def create(tool_call = Noneif force_tool_call is not None:- tool_call = {- "type": "function",- "function": {- "name": force_tool_call- }- }+ tool_call = {"type": "function", "function": {"name": force_tool_call}}assert functions is not Nonereturn anthropic_chat_completions_request(diff --git a/letta/llm_api/mistral.py b/letta/llm_api/mistral.pyindex 932cf8748..b53d76edb 100644--- a/letta/llm_api/mistral.py+++ b/letta/llm_api/mistral.py@@ -1,5 +1,4 @@import requests-from letta.utils import printd, smart_urljoindiff --git a/letta/llm_api/openai.py b/letta/llm_api/openai.pyindex 813ae68d5..407ac6aec 100644--- a/letta/llm_api/openai.py+++ b/letta/llm_api/openai.py@@ -6,7 +6,6 @@ import httpximport requestsfrom httpx_sse import connect_ssefrom httpx_sse._exceptions import SSEError-from letta.constants import OPENAI_CONTEXT_WINDOW_ERROR_SUBSTRINGfrom letta.errors import LLMErrorfrom letta.llm_api.helpers import (diff --git a/letta/local_llm/chat_completion_proxy.py b/letta/local_llm/chat_completion_proxy.pyindex c6dbd4a16..9eba5ca85 100644--- a/letta/local_llm/chat_completion_proxy.py+++ b/letta/local_llm/chat_completion_proxy.py@@ -3,7 +3,6 @@import uuidimport requests-from letta.constants import CLI_WARNING_PREFIXfrom letta.errors import LocalLLMConnectionError, LocalLLMErrorfrom letta.local_llm.constants import DEFAULT_WRAPPERdiff --git a/letta/local_llm/grammars/gbnf_grammar_generator.py b/letta/local_llm/grammars/gbnf_grammar_generator.pyindex ddd628175..1cb793ef1 100644--- a/letta/local_llm/grammars/gbnf_grammar_generator.py+++ b/letta/local_llm/grammars/gbnf_grammar_generator.py@@ -19,9 +19,8 @@ from typing import ()from docstring_parser import parse-from pydantic import BaseModel, create_model-from letta.utils import json_dumps+from pydantic import BaseModel, create_modelclass PydanticDataType(Enum):diff --git a/letta/local_llm/llm_chat_completion_wrappers/configurable_wrapper.py b/letta/local_llm/llm_chat_completion_wrappers/configurable_wrapper.pyindex 19f256685..4b41d7a57 100644--- a/letta/local_llm/llm_chat_completion_wrappers/configurable_wrapper.py+++ b/letta/local_llm/llm_chat_completion_wrappers/configurable_wrapper.py@@ -1,5 +1,4 @@import yaml-from letta.utils import json_dumps, json_loadsfrom ...errors import LLMJSONParsingErrordiff --git a/letta/local_llm/utils.py b/letta/local_llm/utils.pyindex b0529c358..796b3c57a 100644--- a/letta/local_llm/utils.py+++ b/letta/local_llm/utils.py@@ -2,15 +2,14 @@ import osimport warningsfrom typing import List, Union-import requests-import tiktoken-import letta.local_llm.llm_chat_completion_wrappers.airoboros as airoborosimport letta.local_llm.llm_chat_completion_wrappers.chatml as chatmlimport letta.local_llm.llm_chat_completion_wrappers.configurable_wrapper as configurable_wrapperimport letta.local_llm.llm_chat_completion_wrappers.dolphin as dolphinimport letta.local_llm.llm_chat_completion_wrappers.llama3 as llama3import letta.local_llm.llm_chat_completion_wrappers.zephyr as zephyr+import requests+import tiktokenfrom letta.schemas.openai.chat_completion_request import Tool, ToolCalldiff --git a/letta/main.py b/letta/main.pyindex de1b4028a..bbcd56e59 100644--- a/letta/main.py+++ b/letta/main.py@@ -2,14 +2,12 @@ import osimport sysimport traceback-import questionary-import requests-import typer-from rich.console import Console-import letta.agent as agentimport letta.errors as errorsimport letta.system as system+import questionary+import requests+import typer# import benchmarkfrom letta import create_client@@ -22,6 +20,7 @@ from letta.constants import FUNC_FAILED_HEARTBEAT_MESSAGE, REQ_HEARTBEAT_MESSAGE# from letta.interface import CLIInterface as interface # for printing to terminalfrom letta.streaming_interface import AgentRefreshStreamingInterface+from rich.console import Console# interface = interface()diff --git a/letta/orm/__init__.py b/letta/orm/__init__.pyindex 8a0f0c777..e083efce2 100644--- a/letta/orm/__init__.py+++ b/letta/orm/__init__.py@@ -7,7 +7,7 @@ from letta.orm.file import FileMetadatafrom letta.orm.job import Jobfrom letta.orm.message import Messagefrom letta.orm.organization import Organization-from letta.orm.passage import BasePassage, AgentPassage, SourcePassage+from letta.orm.passage import AgentPassage, BasePassage, SourcePassagefrom letta.orm.sandbox_config import SandboxConfig, SandboxEnvironmentVariablefrom letta.orm.source import Sourcefrom letta.orm.sources_agents import SourcesAgentsdiff --git a/letta/orm/agent.py b/letta/orm/agent.pyindex c4645c3ed..de9dd5ce0 100644--- a/letta/orm/agent.py+++ b/letta/orm/agent.py@@ -1,9 +1,6 @@import uuidfrom typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON, String, UniqueConstraint-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.block import Blockfrom letta.orm.custom_columns import (EmbeddingConfigColumn,@@ -20,6 +17,8 @@ from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import Memoryfrom letta.schemas.tool_rule import ToolRule+from sqlalchemy import JSON, String, UniqueConstraint+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm.agents_tags import AgentsTagsdiff --git a/letta/orm/agents_tags.py b/letta/orm/agents_tags.pyindex 76ff90110..5041f629c 100644--- a/letta/orm/agents_tags.py+++ b/letta/orm/agents_tags.py@@ -1,8 +1,7 @@+from letta.orm.base import Basefrom sqlalchemy import ForeignKey, String, UniqueConstraintfrom sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.base import Base-class AgentsTags(Base):__tablename__ = "agents_tags"diff --git a/letta/orm/block.py b/letta/orm/block.pyindex 99cfa29b2..6759596da 100644--- a/letta/orm/block.py+++ b/letta/orm/block.py@@ -1,14 +1,13 @@from typing import TYPE_CHECKING, Optional, Type-from sqlalchemy import JSON, BigInteger, Integer, UniqueConstraint, event-from sqlalchemy.orm import Mapped, attributes, mapped_column, relationship-from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMITfrom letta.orm.blocks_agents import BlocksAgentsfrom letta.orm.mixins import OrganizationMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.block import Block as PydanticBlockfrom letta.schemas.block import Human, Persona+from sqlalchemy import JSON, BigInteger, Integer, UniqueConstraint, event+from sqlalchemy.orm import Mapped, attributes, mapped_column, relationshipif TYPE_CHECKING:from letta.orm import Organizationdiff --git a/letta/orm/blocks_agents.py b/letta/orm/blocks_agents.pyindex 4774783b5..86a75e9a1 100644--- a/letta/orm/blocks_agents.py+++ b/letta/orm/blocks_agents.py@@ -1,8 +1,7 @@+from letta.orm.base import Basefrom sqlalchemy import ForeignKey, ForeignKeyConstraint, String, UniqueConstraintfrom sqlalchemy.orm import Mapped, mapped_column-from letta.orm.base import Base-class BlocksAgents(Base):"""Agents must have one or many blocks to make up their core memory."""diff --git a/letta/orm/custom_columns.py b/letta/orm/custom_columns.pyindex f53169d93..b20760f98 100644--- a/letta/orm/custom_columns.py+++ b/letta/orm/custom_columns.py@@ -2,14 +2,18 @@ import base64from typing import List, Unionimport numpy as np-from sqlalchemy import JSON-from sqlalchemy.types import BINARY, TypeDecorator-from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.enums import ToolRuleTypefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.openai.chat_completions import ToolCall, ToolCallFunction-from letta.schemas.tool_rule import ChildToolRule, ConditionalToolRule, InitToolRule, TerminalToolRule+from letta.schemas.tool_rule import (+ ChildToolRule,+ ConditionalToolRule,+ InitToolRule,+ TerminalToolRule,+)+from sqlalchemy import JSON+from sqlalchemy.types import BINARY, TypeDecoratorclass EmbeddingConfigColumn(TypeDecorator):diff --git a/letta/orm/file.py b/letta/orm/file.pyindex 45470c6c9..4216a01a4 100644--- a/letta/orm/file.py+++ b/letta/orm/file.py@@ -1,16 +1,16 @@-from typing import TYPE_CHECKING, Optional, List--from sqlalchemy import Integer, String-from sqlalchemy.orm import Mapped, mapped_column, relationship+from typing import TYPE_CHECKING, List, Optionalfrom letta.orm.mixins import OrganizationMixin, SourceMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.file import FileMetadata as PydanticFileMetadata+from sqlalchemy import Integer, String+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm.organization import Organization- from letta.orm.source import Sourcefrom letta.orm.passage import SourcePassage+ from letta.orm.source import Source+class FileMetadata(SqlalchemyBase, OrganizationMixin, SourceMixin):"""Represents metadata for an uploaded file."""@@ -28,4 +28,6 @@ class FileMetadata(SqlalchemyBase, OrganizationMixin, SourceMixin):# relationshipsorganization: Mapped["Organization"] = relationship("Organization", back_populates="files", lazy="selectin")source: Mapped["Source"] = relationship("Source", back_populates="files", lazy="selectin")- source_passages: Mapped[List["SourcePassage"]] = relationship("SourcePassage", back_populates="file", lazy="selectin", cascade="all, delete-orphan")+ source_passages: Mapped[List["SourcePassage"]] = relationship(+ "SourcePassage", back_populates="file", lazy="selectin", cascade="all, delete-orphan"+ )diff --git a/letta/orm/job.py b/letta/orm/job.pyindex d95abe443..fabdb9188 100644--- a/letta/orm/job.py+++ b/letta/orm/job.py@@ -1,13 +1,12 @@from datetime import datetimefrom typing import TYPE_CHECKING, Optional-from sqlalchemy import JSON, String-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.mixins import UserMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.enums import JobStatusfrom letta.schemas.job import Job as PydanticJob+from sqlalchemy import JSON, String+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm.user import Userdiff --git a/letta/orm/message.py b/letta/orm/message.pyindex a8bbb9001..6e2194f5c 100644--- a/letta/orm/message.py+++ b/letta/orm/message.py@@ -1,13 +1,12 @@from typing import Optional-from sqlalchemy import Index-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.custom_columns import ToolCallColumnfrom letta.orm.mixins import AgentMixin, OrganizationMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.message import Message as PydanticMessagefrom letta.schemas.openai.chat_completions import ToolCall+from sqlalchemy import Index+from sqlalchemy.orm import Mapped, mapped_column, relationshipclass Message(SqlalchemyBase, OrganizationMixin, AgentMixin):diff --git a/letta/orm/mixins.py b/letta/orm/mixins.pyindex 328772d7e..3e82f4d69 100644--- a/letta/orm/mixins.py+++ b/letta/orm/mixins.py@@ -1,11 +1,10 @@from typing import Optionalfrom uuid import UUID+from letta.orm.base import Basefrom sqlalchemy import ForeignKey, Stringfrom sqlalchemy.orm import Mapped, mapped_column-from letta.orm.base import Base-def is_valid_uuid4(uuid_string: str) -> bool:"""Check if a string is a valid UUID4."""@@ -31,6 +30,7 @@ class UserMixin(Base):user_id: Mapped[str] = mapped_column(String, ForeignKey("users.id"))+class AgentMixin(Base):"""Mixin for models that belong to an agent."""@@ -38,6 +38,7 @@ class AgentMixin(Base):agent_id: Mapped[str] = mapped_column(String, ForeignKey("agents.id", ondelete="CASCADE"))+class FileMixin(Base):"""Mixin for models that belong to a file."""diff --git a/letta/orm/organization.py b/letta/orm/organization.pyindex 9a71a09b7..9bcc09b2a 100644--- a/letta/orm/organization.py+++ b/letta/orm/organization.py@@ -1,9 +1,8 @@from typing import TYPE_CHECKING, List, Union-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.organization import Organization as PydanticOrganization+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:@@ -38,19 +37,11 @@ class Organization(SqlalchemyBase):agents: Mapped[List["Agent"]] = relationship("Agent", back_populates="organization", cascade="all, delete-orphan")messages: Mapped[List["Message"]] = relationship("Message", back_populates="organization", cascade="all, delete-orphan")source_passages: Mapped[List["SourcePassage"]] = relationship(- "SourcePassage",- back_populates="organization",- cascade="all, delete-orphan"- )- agent_passages: Mapped[List["AgentPassage"]] = relationship(- "AgentPassage",- back_populates="organization",- cascade="all, delete-orphan"+ "SourcePassage", back_populates="organization", cascade="all, delete-orphan")+ agent_passages: Mapped[List["AgentPassage"]] = relationship("AgentPassage", back_populates="organization", cascade="all, delete-orphan")@propertydef passages(self) -> List[Union["SourcePassage", "AgentPassage"]]:"""Convenience property to get all passages"""return self.source_passages + self.agent_passages--diff --git a/letta/orm/passage.py b/letta/orm/passage.pyindex 492c60217..8237ed612 100644--- a/letta/orm/passage.py+++ b/letta/orm/passage.py@@ -1,8 +1,5 @@from typing import TYPE_CHECKING-from sqlalchemy import JSON, Column, Index-from sqlalchemy.orm import Mapped, declared_attr, mapped_column, relationship-from letta.config import LettaConfigfrom letta.constants import MAX_EMBEDDING_DIMfrom letta.orm.custom_columns import CommonVector, EmbeddingConfigColumn@@ -10,6 +7,8 @@ from letta.orm.mixins import AgentMixin, FileMixin, OrganizationMixin, SourceMixfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.passage import Passage as PydanticPassagefrom letta.settings import settings+from sqlalchemy import JSON, Column, Index+from sqlalchemy.orm import Mapped, declared_attr, mapped_column, relationshipconfig = LettaConfig()diff --git a/letta/orm/sandbox_config.py b/letta/orm/sandbox_config.pyindex aa8e07dc9..0b0cad17f 100644--- a/letta/orm/sandbox_config.py+++ b/letta/orm/sandbox_config.py@@ -1,10 +1,5 @@from typing import TYPE_CHECKING, Dict, List, Optional-from sqlalchemy import JSON-from sqlalchemy import Enum as SqlEnum-from sqlalchemy import String, UniqueConstraint-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.mixins import OrganizationMixin, SandboxConfigMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.sandbox_config import SandboxConfig as PydanticSandboxConfig@@ -12,6 +7,10 @@ from letta.schemas.sandbox_config import (SandboxEnvironmentVariable as PydanticSandboxEnvironmentVariable,)from letta.schemas.sandbox_config import SandboxType+from sqlalchemy import JSON+from sqlalchemy import Enum as SqlEnum+from sqlalchemy import String, UniqueConstraint+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm.organization import Organizationdiff --git a/letta/orm/source.py b/letta/orm/source.pyindex e7443ea67..838f4c78d 100644--- a/letta/orm/source.py+++ b/letta/orm/source.py@@ -1,14 +1,13 @@from typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm import FileMetadatafrom letta.orm.custom_columns import EmbeddingConfigColumnfrom letta.orm.mixins import OrganizationMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.source import Source as PydanticSource+from sqlalchemy import JSON+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm.agent import Agentdiff --git a/letta/orm/sources_agents.py b/letta/orm/sources_agents.pyindex ffe8a9d0e..2da5003f4 100644--- a/letta/orm/sources_agents.py+++ b/letta/orm/sources_agents.py@@ -1,8 +1,7 @@+from letta.orm.base import Basefrom sqlalchemy import ForeignKey, Stringfrom sqlalchemy.orm import Mapped, mapped_column-from letta.orm.base import Base-class SourcesAgents(Base):"""Agents can have zero to many sources"""diff --git a/letta/orm/sqlalchemy_base.py b/letta/orm/sqlalchemy_base.pyindex 6879c74b4..857d09902 100644--- a/letta/orm/sqlalchemy_base.py+++ b/letta/orm/sqlalchemy_base.py@@ -3,10 +3,6 @@ from enum import Enumfrom functools import wrapsfrom typing import TYPE_CHECKING, List, Literal, Optional-from sqlalchemy import String, desc, func, or_, select-from sqlalchemy.exc import DBAPIError, IntegrityError, TimeoutError-from sqlalchemy.orm import Mapped, Session, mapped_column-from letta.log import get_loggerfrom letta.orm.base import Base, CommonSqlalchemyMetaMixinsfrom letta.orm.errors import (@@ -16,6 +12,9 @@ from letta.orm.errors import (UniqueConstraintViolationError,)from letta.orm.sqlite_functions import adapt_array+from sqlalchemy import String, desc, func, or_, select+from sqlalchemy.exc import DBAPIError, IntegrityError, TimeoutError+from sqlalchemy.orm import Mapped, Session, mapped_columnif TYPE_CHECKING:from pydantic import BaseModeldiff --git a/letta/orm/sqlite_functions.py b/letta/orm/sqlite_functions.pyindex a5b741aa5..50c257a08 100644--- a/letta/orm/sqlite_functions.py+++ b/letta/orm/sqlite_functions.py@@ -1,12 +1,12 @@+import base64+import sqlite3from typing import Optional, Union-import base64import numpy as np+from letta.constants import MAX_EMBEDDING_DIMfrom sqlalchemy import eventfrom sqlalchemy.engine import Engine-import sqlite3-from letta.constants import MAX_EMBEDDING_DIMdef adapt_array(arr):"""@@ -19,12 +19,13 @@ def adapt_array(arr):arr = np.array(arr, dtype=np.float32)elif not isinstance(arr, np.ndarray):raise ValueError(f"Unsupported type: {type(arr)}")-+# Convert to bytes and then base64 encodebytes_data = arr.tobytes()base64_data = base64.b64encode(bytes_data)return sqlite3.Binary(base64_data)+def convert_array(text):"""Converts binary back to numpy array@@ -38,23 +39,24 @@ def convert_array(text):# Handle both bytes and sqlite3.Binarybinary_data = bytes(text) if isinstance(text, sqlite3.Binary) else text-+try:# First decode base64decoded_data = base64.b64decode(binary_data)# Then convert to numpy arrayreturn np.frombuffer(decoded_data, dtype=np.float32)- except Exception as e:+ except Exception:return None+def verify_embedding_dimension(embedding: np.ndarray, expected_dim: int = MAX_EMBEDDING_DIM) -> bool:"""Verifies that an embedding has the expected dimension-+Args:embedding: Input embedding arrayexpected_dim: Expected embedding dimension (default: 4096)-+Returns:bool: True if dimension matches, False otherwise"""@@ -62,28 +64,27 @@ def verify_embedding_dimension(embedding: np.ndarray, expected_dim: int = MAX_EMreturn Falsereturn embedding.shape[0] == expected_dim+def validate_and_transform_embedding(- embedding: Union[bytes, sqlite3.Binary, list, np.ndarray],- expected_dim: int = MAX_EMBEDDING_DIM,- dtype: np.dtype = np.float32+ embedding: Union[bytes, sqlite3.Binary, list, np.ndarray], expected_dim: int = MAX_EMBEDDING_DIM, dtype: np.dtype = np.float32) -> Optional[np.ndarray]:"""Validates and transforms embeddings to ensure correct dimensionality.-+Args:embedding: Input embedding in various possible formatsexpected_dim: Expected embedding dimension (default 4096)dtype: NumPy dtype for the embedding (default float32)-+Returns:np.ndarray: Validated and transformed embedding-+Raises:ValueError: If embedding dimension doesn't match expected dimension"""if embedding is None:return None-+# Convert to numpy array based on input typeif isinstance(embedding, (bytes, sqlite3.Binary)):vec = convert_array(embedding)@@ -93,48 +94,49 @@ def validate_and_transform_embedding(vec = embedding.astype(dtype)else:raise ValueError(f"Unsupported embedding type: {type(embedding)}")-+# Validate dimensionif vec.shape[0] != expected_dim:- raise ValueError(- f"Invalid embedding dimension: got {vec.shape[0]}, expected {expected_dim}"- )-+ raise ValueError(f"Invalid embedding dimension: got {vec.shape[0]}, expected {expected_dim}")+return vec+def cosine_distance(embedding1, embedding2, expected_dim=MAX_EMBEDDING_DIM):"""Calculate cosine distance between two embeddings-+Args:embedding1: First embeddingembedding2: Second embeddingexpected_dim: Expected embedding dimension (default 4096)-+Returns:float: Cosine distance"""-+if embedding1 is None or embedding2 is None:return 0.0 # Maximum distance if either embedding is None-+try:vec1 = validate_and_transform_embedding(embedding1, expected_dim)vec2 = validate_and_transform_embedding(embedding2, expected_dim)- except ValueError as e:+ except ValueError:return 0.0-+similarity = np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))distance = float(1.0 - similarity)-+return distance+@event.listens_for(Engine, "connect")def register_functions(dbapi_connection, connection_record):"""Register SQLite functions"""if isinstance(dbapi_connection, sqlite3.Connection):dbapi_connection.create_function("cosine_distance", 2, cosine_distance)-++# Register adapters and converters for numpy arrayssqlite3.register_adapter(np.ndarray, adapt_array)sqlite3.register_converter("ARRAY", convert_array)diff --git a/letta/orm/tool.py b/letta/orm/tool.pyindex a25c7ebb0..50d475062 100644--- a/letta/orm/tool.py+++ b/letta/orm/tool.py@@ -1,13 +1,12 @@from typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON, String, UniqueConstraint-from sqlalchemy.orm import Mapped, mapped_column, relationship-# TODO everything in functions should live in this modelfrom letta.orm.enums import ToolSourceTypefrom letta.orm.mixins import OrganizationMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.tool import Tool as PydanticTool+from sqlalchemy import JSON, String, UniqueConstraint+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm.organization import Organizationdiff --git a/letta/orm/tools_agents.py b/letta/orm/tools_agents.pyindex 52c1e0a1e..50668d940 100644--- a/letta/orm/tools_agents.py+++ b/letta/orm/tools_agents.py@@ -1,8 +1,7 @@+from letta.orm import Basefrom sqlalchemy import ForeignKey, String, UniqueConstraintfrom sqlalchemy.orm import Mapped, mapped_column-from letta.orm import Base-class ToolsAgents(Base):"""Agents can have one or many tools associated with them."""diff --git a/letta/orm/user.py b/letta/orm/user.pyindex 9f626b104..23c2b268a 100644--- a/letta/orm/user.py+++ b/letta/orm/user.py@@ -1,10 +1,9 @@from typing import TYPE_CHECKING, List-from sqlalchemy.orm import Mapped, mapped_column, relationship-from letta.orm.mixins import OrganizationMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.user import User as PydanticUser+from sqlalchemy.orm import Mapped, mapped_column, relationshipif TYPE_CHECKING:from letta.orm import Job, Organizationdiff --git a/letta/providers.py b/letta/providers.pyindex e8ebadfa7..cb7bf72b7 100644--- a/letta/providers.py+++ b/letta/providers.py@@ -1,7 +1,5 @@from typing import List, Optional-from pydantic import BaseModel, Field, model_validator-from letta.constants import LLM_MAX_TOKENS, MIN_CONTEXT_WINDOWfrom letta.llm_api.azure_openai import (get_azure_chat_completions_endpoint,@@ -10,6 +8,7 @@ from letta.llm_api.azure_openai import (from letta.llm_api.azure_openai_constants import AZURE_MODEL_TO_CONTEXT_LENGTHfrom letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.llm_config import LLMConfig+from pydantic import BaseModel, Field, model_validatorclass Provider(BaseModel):@@ -27,12 +26,11 @@ class Provider(BaseModel):def provider_tag(self) -> str:"""String representation of the provider for display purposes"""raise NotImplementedError-+def get_handle(self, model_name: str) -> str:return f"{self.name}/{model_name}"-class LettaProvider(Provider):name: str = "letta"@@ -44,7 +42,7 @@ class LettaProvider(Provider):model_endpoint_type="openai",model_endpoint="https://inference.memgpt.ai",context_window=16384,- handle=self.get_handle("letta-free")+ handle=self.get_handle("letta-free"),)]@@ -56,7 +54,7 @@ class LettaProvider(Provider):embedding_endpoint="https://embeddings.memgpt.ai",embedding_dim=1024,embedding_chunk_size=300,- handle=self.get_handle("letta-free")+ handle=self.get_handle("letta-free"),)]@@ -121,7 +119,13 @@ class OpenAIProvider(Provider):# continueconfigs.append(- LLMConfig(model=model_name, model_endpoint_type="openai", model_endpoint=self.base_url, context_window=context_window_size, handle=self.get_handle(model_name))+ LLMConfig(+ model=model_name,+ model_endpoint_type="openai",+ model_endpoint=self.base_url,+ context_window=context_window_size,+ handle=self.get_handle(model_name),+ ))# for OpenAI, sort in reverse order@@ -141,7 +145,7 @@ class OpenAIProvider(Provider):embedding_endpoint="https://api.openai.com/v1",embedding_dim=1536,embedding_chunk_size=300,- handle=self.get_handle("text-embedding-ada-002")+ handle=self.get_handle("text-embedding-ada-002"),)]@@ -170,7 +174,7 @@ class AnthropicProvider(Provider):model_endpoint_type="anthropic",model_endpoint=self.base_url,context_window=model["context_window"],- handle=self.get_handle(model["name"])+ handle=self.get_handle(model["name"]),))return configs@@ -203,7 +207,7 @@ class MistralProvider(Provider):model_endpoint_type="openai",model_endpoint=self.base_url,context_window=model["max_context_length"],- handle=self.get_handle(model["id"])+ handle=self.get_handle(model["id"]),))@@ -259,7 +263,7 @@ class OllamaProvider(OpenAIProvider):model_endpoint=self.base_url,model_wrapper=self.default_prompt_formatter,context_window=context_window,- handle=self.get_handle(model["name"])+ handle=self.get_handle(model["name"]),))return configs@@ -335,7 +339,7 @@ class OllamaProvider(OpenAIProvider):embedding_endpoint=self.base_url,embedding_dim=embedding_dim,embedding_chunk_size=300,- handle=self.get_handle(model["name"])+ handle=self.get_handle(model["name"]),))return configs@@ -356,7 +360,11 @@ class GroqProvider(OpenAIProvider):continueconfigs.append(LLMConfig(- model=model["id"], model_endpoint_type="groq", model_endpoint=self.base_url, context_window=model["context_window"], handle=self.get_handle(model["id"])+ model=model["id"],+ model_endpoint_type="groq",+ model_endpoint=self.base_url,+ context_window=model["context_window"],+ handle=self.get_handle(model["id"]),))return configs@@ -424,7 +432,7 @@ class TogetherProvider(OpenAIProvider):model_endpoint=self.base_url,model_wrapper=self.default_prompt_formatter,context_window=context_window_size,- handle=self.get_handle(model_name)+ handle=self.get_handle(model_name),))@@ -505,7 +513,7 @@ class GoogleAIProvider(Provider):model_endpoint_type="google_ai",model_endpoint=self.base_url,context_window=self.get_model_context_window(model),- handle=self.get_handle(model)+ handle=self.get_handle(model),))return configs@@ -529,7 +537,7 @@ class GoogleAIProvider(Provider):embedding_endpoint=self.base_url,embedding_dim=768,embedding_chunk_size=300, # NOTE: max is 2048- handle=self.get_handle(model)+ handle=self.get_handle(model),))return configs@@ -570,7 +578,8 @@ class AzureProvider(Provider):context_window_size = self.get_model_context_window(model_name)model_endpoint = get_azure_chat_completions_endpoint(self.base_url, model_name, self.api_version)configs.append(- LLMConfig(model=model_name, model_endpoint_type="azure", model_endpoint=model_endpoint, context_window=context_window_size), handle=self.get_handle(model_name)+ LLMConfig(model=model_name, model_endpoint_type="azure", model_endpoint=model_endpoint, context_window=context_window_size),+ handle=self.get_handle(model_name),)return configs@@ -591,7 +600,7 @@ class AzureProvider(Provider):embedding_endpoint=model_endpoint,embedding_dim=768,embedding_chunk_size=300, # NOTE: max is 2048- handle=self.get_handle(model_name)+ handle=self.get_handle(model_name),))return configs@@ -625,7 +634,7 @@ class VLLMChatCompletionsProvider(Provider):model_endpoint_type="openai",model_endpoint=self.base_url,context_window=model["max_model_len"],- handle=self.get_handle(model["id"])+ handle=self.get_handle(model["id"]),))return configs@@ -658,7 +667,7 @@ class VLLMCompletionsProvider(Provider):model_endpoint=self.base_url,model_wrapper=self.default_prompt_formatter,context_window=model["max_model_len"],- handle=self.get_handle(model["id"])+ handle=self.get_handle(model["id"]),))return configsdiff --git a/letta/schemas/agent.py b/letta/schemas/agent.pyindex 03d40350e..06fe58600 100644--- a/letta/schemas/agent.py+++ b/letta/schemas/agent.py@@ -1,8 +1,6 @@from enum import Enumfrom typing import Dict, List, Optional-from pydantic import BaseModel, Field, field_validator-from letta.constants import DEFAULT_EMBEDDING_CHUNK_SIZEfrom letta.schemas.block import CreateBlockfrom letta.schemas.embedding_config import EmbeddingConfig@@ -15,6 +13,7 @@ from letta.schemas.source import Sourcefrom letta.schemas.tool import Toolfrom letta.schemas.tool_rule import ToolRulefrom letta.utils import create_random_username+from pydantic import BaseModel, Field, field_validatorclass AgentType(str, Enum):diff --git a/letta/schemas/block.py b/letta/schemas/block.pyindex 25e84b7da..bd905bd2d 100644--- a/letta/schemas/block.py+++ b/letta/schemas/block.py@@ -1,10 +1,9 @@from typing import Optional-from pydantic import BaseModel, Field, model_validator-from typing_extensions import Self-from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMITfrom letta.schemas.letta_base import LettaBase+from pydantic import BaseModel, Field, model_validator+from typing_extensions import Self# block of the LLM contextdiff --git a/letta/schemas/file.py b/letta/schemas/file.pyindex b43eb64c3..0671bc3eb 100644--- a/letta/schemas/file.py+++ b/letta/schemas/file.py@@ -1,9 +1,8 @@from datetime import datetimefrom typing import Optional-from pydantic import Field-from letta.schemas.letta_base import LettaBase+from pydantic import Fieldclass FileMetadataBase(LettaBase):diff --git a/letta/schemas/job.py b/letta/schemas/job.pyindex 17c2b98da..b767b5671 100644--- a/letta/schemas/job.py+++ b/letta/schemas/job.py@@ -1,10 +1,9 @@from datetime import datetimefrom typing import Optional-from pydantic import Field-from letta.schemas.enums import JobStatusfrom letta.schemas.letta_base import OrmMetadataBase+from pydantic import Fieldclass JobBase(OrmMetadataBase):diff --git a/letta/schemas/letta_request.py b/letta/schemas/letta_request.pyindex 123d817cf..73f956ff5 100644--- a/letta/schemas/letta_request.py+++ b/letta/schemas/letta_request.py@@ -1,9 +1,8 @@from typing import List-from pydantic import BaseModel, Field-from letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARGfrom letta.schemas.message import MessageCreate+from pydantic import BaseModel, Fieldclass LettaRequest(BaseModel):diff --git a/letta/schemas/letta_response.py b/letta/schemas/letta_response.pyindex c6a1e8be5..7084c3ba0 100644--- a/letta/schemas/letta_response.py+++ b/letta/schemas/letta_response.py@@ -3,12 +3,11 @@ import jsonimport refrom typing import List, Union-from pydantic import BaseModel, Field-from letta.schemas.enums import MessageStreamStatusfrom letta.schemas.letta_message import LettaMessage, LettaMessageUnionfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.utils import json_dumps+from pydantic import BaseModel, Field# TODO: consider moving into own filediff --git a/letta/schemas/message.py b/letta/schemas/message.pyindex 74bb81356..24022ece5 100644--- a/letta/schemas/message.py+++ b/letta/schemas/message.py@@ -4,8 +4,6 @@ import warningsfrom datetime import datetime, timezonefrom typing import List, Literal, Optional-from pydantic import BaseModel, Field, field_validator-from letta.constants import (DEFAULT_MESSAGE_TOOL,DEFAULT_MESSAGE_TOOL_KWARG,@@ -16,16 +14,15 @@ from letta.schemas.enums import MessageRolefrom letta.schemas.letta_base import OrmMetadataBasefrom letta.schemas.letta_message import (AssistantMessage,- ToolCall as LettaToolCall,- ToolCallMessage,- ToolReturnMessage,- ReasoningMessage,LettaMessage,+ ReasoningMessage,SystemMessage,- UserMessage,)+from letta.schemas.letta_message import ToolCall as LettaToolCall+from letta.schemas.letta_message import ToolCallMessage, ToolReturnMessage, UserMessagefrom letta.schemas.openai.chat_completions import ToolCall, ToolCallFunctionfrom letta.utils import get_utc_time, is_utc_datetime, json_dumps+from pydantic import BaseModel, Field, field_validatordef add_inner_thoughts_to_tool_call(diff --git a/letta/schemas/organization.py b/letta/schemas/organization.pyindex 35784ad0d..6220b987a 100644--- a/letta/schemas/organization.py+++ b/letta/schemas/organization.py@@ -1,10 +1,9 @@from datetime import datetimefrom typing import Optional-from pydantic import Field-from letta.schemas.letta_base import LettaBasefrom letta.utils import create_random_username, get_utc_time+from pydantic import Fieldclass OrganizationBase(LettaBase):diff --git a/letta/schemas/passage.py b/letta/schemas/passage.pyindex c1ec13bec..c613c2e1b 100644--- a/letta/schemas/passage.py+++ b/letta/schemas/passage.py@@ -1,12 +1,11 @@from datetime import datetimefrom typing import Dict, List, Optional-from pydantic import Field, field_validator-from letta.constants import MAX_EMBEDDING_DIMfrom letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.letta_base import OrmMetadataBasefrom letta.utils import get_utc_time+from pydantic import Field, field_validatorclass PassageBase(OrmMetadataBase):diff --git a/letta/schemas/sandbox_config.py b/letta/schemas/sandbox_config.pyindex f86233fae..993711cc5 100644--- a/letta/schemas/sandbox_config.py+++ b/letta/schemas/sandbox_config.py@@ -3,11 +3,10 @@ import jsonfrom enum import Enumfrom typing import Any, Dict, List, Literal, Optional, Union-from pydantic import BaseModel, Field, model_validator-from letta.schemas.agent import AgentStatefrom letta.schemas.letta_base import LettaBase, OrmMetadataBasefrom letta.settings import tool_settings+from pydantic import BaseModel, Field, model_validator# Sandbox Configdiff --git a/letta/schemas/source.py b/letta/schemas/source.pyindex 0a458dfde..d6a14d79f 100644--- a/letta/schemas/source.py+++ b/letta/schemas/source.py@@ -1,10 +1,9 @@from datetime import datetimefrom typing import Optional-from pydantic import Field-from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.letta_base import LettaBase+from pydantic import Fieldclass BaseSource(LettaBase):diff --git a/letta/schemas/tool.py b/letta/schemas/tool.pyindex 997965ab5..2837ee7fe 100644--- a/letta/schemas/tool.py+++ b/letta/schemas/tool.py@@ -1,7 +1,5 @@from typing import Dict, List, Optional-from pydantic import Field, model_validator-from letta.constants import FUNCTION_RETURN_CHAR_LIMITfrom letta.functions.functions import derive_openai_json_schemafrom letta.functions.helpers import (@@ -11,6 +9,7 @@ from letta.functions.helpers import (from letta.functions.schema_generator import generate_schema_from_args_schema_v2from letta.schemas.letta_base import LettaBasefrom letta.schemas.openai.chat_completions import ToolCall+from pydantic import Field, model_validatorclass BaseTool(LettaBase):diff --git a/letta/schemas/tool_rule.py b/letta/schemas/tool_rule.pyindex 259e5452d..e88ff2904 100644--- a/letta/schemas/tool_rule.py+++ b/letta/schemas/tool_rule.py@@ -1,9 +1,8 @@from typing import Any, Dict, List, Optional, Union-from pydantic import Field-from letta.schemas.enums import ToolRuleTypefrom letta.schemas.letta_base import LettaBase+from pydantic import Fieldclass BaseToolRule(LettaBase):@@ -25,6 +24,7 @@ class ConditionalToolRule(BaseToolRule):"""A ToolRule that conditionally maps to different child tools based on the output."""+type: ToolRuleType = ToolRuleType.conditionaldefault_child: Optional[str] = Field(None, description="The default child tool to be called. If None, any tool can be called.")child_output_mapping: Dict[Any, str] = Field(..., description="The output case to check for mapping")diff --git a/letta/schemas/usage.py b/letta/schemas/usage.pyindex 53cda8b25..d317cc5b1 100644--- a/letta/schemas/usage.py+++ b/letta/schemas/usage.py@@ -1,4 +1,5 @@from typing import Literal+from pydantic import BaseModel, Field@@ -12,6 +13,7 @@ class LettaUsageStatistics(BaseModel):total_tokens (int): The total number of tokens processed by the agent.step_count (int): The number of steps taken by the agent."""+message_type: Literal["usage_statistics"] = "usage_statistics"completion_tokens: int = Field(0, description="The number of tokens generated by the agent.")prompt_tokens: int = Field(0, description="The number of tokens in the prompt.")diff --git a/letta/schemas/user.py b/letta/schemas/user.pyindex 59a4594e0..b2bcb9337 100644--- a/letta/schemas/user.py+++ b/letta/schemas/user.py@@ -1,10 +1,9 @@from datetime import datetimefrom typing import Optional-from pydantic import Field-from letta.schemas.letta_base import LettaBasefrom letta.services.organization_manager import OrganizationManager+from pydantic import Fieldclass UserBase(LettaBase):diff --git a/letta/server/rest_api/app.py b/letta/server/rest_api/app.pyindex 8cb9b27e6..425d9bad7 100644--- a/letta/server/rest_api/app.py+++ b/letta/server/rest_api/app.py@@ -8,9 +8,6 @@ from typing import Optionalimport uvicornfrom fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse-from starlette.middleware.base import BaseHTTPMiddleware-from starlette.middleware.cors import CORSMiddleware-from letta.__init__ import __version__from letta.constants import ADMIN_PREFIX, API_PREFIX, OPENAI_API_PREFIXfrom letta.errors import LettaAgentNotFoundError, LettaUserNotFoundError@@ -47,6 +44,8 @@ from letta.server.rest_api.routers.v1.users import (from letta.server.rest_api.static_files import mount_static_filesfrom letta.server.server import SyncServerfrom letta.settings import settings+from starlette.middleware.base import BaseHTTPMiddleware+from starlette.middleware.cors import CORSMiddleware# TODO(ethan)# NOTE(charles): @ethan I had to add this to get the global as the bottom to workdiff --git a/letta/server/rest_api/auth/index.py b/letta/server/rest_api/auth/index.pyindex 28d22435b..7a29f6b4e 100644--- a/letta/server/rest_api/auth/index.py+++ b/letta/server/rest_api/auth/index.py@@ -2,11 +2,10 @@ from typing import Optionalfrom uuid import UUIDfrom fastapi import APIRouter-from pydantic import BaseModel, Field-from letta.log import get_loggerfrom letta.server.rest_api.interface import QueuingInterfacefrom letta.server.server import SyncServer+from pydantic import BaseModel, Fieldlogger = get_logger(__name__)router = APIRouter()diff --git a/letta/server/rest_api/auth_token.py b/letta/server/rest_api/auth_token.pyindex 40e26d805..72387bbdb 100644--- a/letta/server/rest_api/auth_token.py+++ b/letta/server/rest_api/auth_token.py@@ -2,7 +2,6 @@ import uuidfrom fastapi import Depends, HTTPExceptionfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer-from letta.server.server import SyncServersecurity = HTTPBearer()diff --git a/letta/server/rest_api/interface.py b/letta/server/rest_api/interface.pyindex 1e68ce6e2..ba06e1d6a 100644--- a/letta/server/rest_api/interface.py+++ b/letta/server/rest_api/interface.py@@ -12,14 +12,14 @@ from letta.local_llm.constants import INNER_THOUGHTS_KWARGfrom letta.schemas.enums import MessageStreamStatusfrom letta.schemas.letta_message import (AssistantMessage,+ LegacyFunctionCallMessage,+ LegacyLettaMessage,+ LettaMessage,+ ReasoningMessage,ToolCall,ToolCallDelta,ToolCallMessage,ToolReturnMessage,- ReasoningMessage,- LegacyFunctionCallMessage,- LegacyLettaMessage,- LettaMessage,)from letta.schemas.message import Messagefrom letta.schemas.openai.chat_completion_response import ChatCompletionChunkResponsediff --git a/letta/server/rest_api/routers/openai/assistants/assistants.py b/letta/server/rest_api/routers/openai/assistants/assistants.pyindex 2b646f931..59e57cdfe 100644--- a/letta/server/rest_api/routers/openai/assistants/assistants.py+++ b/letta/server/rest_api/routers/openai/assistants/assistants.py@@ -1,7 +1,6 @@from typing import Listfrom fastapi import APIRouter, Body, HTTPException, Path, Query-from letta.constants import DEFAULT_PRESETfrom letta.schemas.openai.openai import AssistantFile, OpenAIAssistantfrom letta.server.rest_api.routers.openai.assistants.schemas import (diff --git a/letta/server/rest_api/routers/openai/assistants/schemas.py b/letta/server/rest_api/routers/openai/assistants/schemas.pyindex b3cbf389c..5a6649ebe 100644--- a/letta/server/rest_api/routers/openai/assistants/schemas.py+++ b/letta/server/rest_api/routers/openai/assistants/schemas.py@@ -1,7 +1,5 @@from typing import List, Optional-from pydantic import BaseModel, Field-from letta.schemas.openai.openai import (MessageRoleType,OpenAIMessage,@@ -9,6 +7,7 @@ from letta.schemas.openai.openai import (ToolCall,ToolCallOutput,)+from pydantic import BaseModel, Fieldclass CreateAssistantRequest(BaseModel):diff --git a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.pyindex deabcaf5c..72b647db0 100644--- a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py+++ b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py@@ -2,9 +2,8 @@ import jsonfrom typing import TYPE_CHECKING, Optionalfrom fastapi import APIRouter, Body, Depends, Header, HTTPException-from letta.schemas.enums import MessageRole-from letta.schemas.letta_message import ToolCall, LettaMessage+from letta.schemas.letta_message import LettaMessage, ToolCallfrom letta.schemas.openai.chat_completion_request import ChatCompletionRequestfrom letta.schemas.openai.chat_completion_response import (ChatCompletionResponse,diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex 405ab1cf1..a69c4fce9 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -14,8 +14,6 @@ from fastapi import (status,)from fastapi.responses import JSONResponse, StreamingResponse-from pydantic import Field-from letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARGfrom letta.log import get_loggerfrom letta.orm.errors import NoResultFound@@ -49,6 +47,7 @@ from letta.schemas.user import Userfrom letta.server.rest_api.interface import StreamingServerInterfacefrom letta.server.rest_api.utils import get_letta_server, sse_async_generatorfrom letta.server.server import SyncServer+from pydantic import Field# These can be forward refs, but because Fastapi needs them at runtime the must be imported normallydiff --git a/letta/server/rest_api/routers/v1/blocks.py b/letta/server/rest_api/routers/v1/blocks.pyindex d92132334..9d2a937d1 100644--- a/letta/server/rest_api/routers/v1/blocks.py+++ b/letta/server/rest_api/routers/v1/blocks.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING, List, Optionalfrom fastapi import APIRouter, Body, Depends, Header, HTTPException, Query, Response-from letta.orm.errors import NoResultFoundfrom letta.schemas.block import Block, BlockUpdate, CreateBlockfrom letta.server.rest_api.utils import get_letta_serverdiff --git a/letta/server/rest_api/routers/v1/health.py b/letta/server/rest_api/routers/v1/health.pyindex 99fce66d4..81bb41e05 100644--- a/letta/server/rest_api/routers/v1/health.py+++ b/letta/server/rest_api/routers/v1/health.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKINGfrom fastapi import APIRouter-from letta.cli.cli import versionfrom letta.schemas.health import Healthdiff --git a/letta/server/rest_api/routers/v1/jobs.py b/letta/server/rest_api/routers/v1/jobs.pyindex 4245d2f98..bec226251 100644--- a/letta/server/rest_api/routers/v1/jobs.py+++ b/letta/server/rest_api/routers/v1/jobs.py@@ -1,7 +1,6 @@from typing import List, Optionalfrom fastapi import APIRouter, Depends, Header, HTTPException, Query-from letta.orm.errors import NoResultFoundfrom letta.schemas.enums import JobStatusfrom letta.schemas.job import Jobdiff --git a/letta/server/rest_api/routers/v1/llms.py b/letta/server/rest_api/routers/v1/llms.pyindex 4536ae498..f0bf9f425 100644--- a/letta/server/rest_api/routers/v1/llms.py+++ b/letta/server/rest_api/routers/v1/llms.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING, Listfrom fastapi import APIRouter, Depends-from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.llm_config import LLMConfigfrom letta.server.rest_api.utils import get_letta_serverdiff --git a/letta/server/rest_api/routers/v1/organizations.py b/letta/server/rest_api/routers/v1/organizations.pyindex 2f4cdb1b5..8fbead6d9 100644--- a/letta/server/rest_api/routers/v1/organizations.py+++ b/letta/server/rest_api/routers/v1/organizations.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING, List, Optionalfrom fastapi import APIRouter, Body, Depends, HTTPException, Query-from letta.schemas.organization import Organization, OrganizationCreatefrom letta.server.rest_api.utils import get_letta_serverdiff --git a/letta/server/rest_api/routers/v1/sandbox_configs.py b/letta/server/rest_api/routers/v1/sandbox_configs.pyindex bf06bae74..17dcbb4f3 100644--- a/letta/server/rest_api/routers/v1/sandbox_configs.py+++ b/letta/server/rest_api/routers/v1/sandbox_configs.py@@ -1,7 +1,6 @@from typing import List, Optionalfrom fastapi import APIRouter, Depends, Query-from letta.schemas.sandbox_config import SandboxConfig as PydanticSandboxConfigfrom letta.schemas.sandbox_config import SandboxConfigCreate, SandboxConfigUpdatefrom letta.schemas.sandbox_config import SandboxEnvironmentVariable as PydanticEnvVardiff --git a/letta/server/rest_api/routers/v1/sources.py b/letta/server/rest_api/routers/v1/sources.pyindex fb48d125c..c51fee687 100644--- a/letta/server/rest_api/routers/v1/sources.py+++ b/letta/server/rest_api/routers/v1/sources.py@@ -11,7 +11,6 @@ from fastapi import (Query,UploadFile,)-from letta.schemas.file import FileMetadatafrom letta.schemas.job import Jobfrom letta.schemas.passage import Passagediff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.pyindex ffc2b2124..bb297a36e 100644--- a/letta/server/rest_api/routers/v1/tools.py+++ b/letta/server/rest_api/routers/v1/tools.py@@ -6,7 +6,6 @@ from composio.client.enums.base import EnumStringNotFoundfrom composio.exceptions import ApiKeyNotProvidedError, ComposioSDKErrorfrom composio.tools.base.abs import InvalidClassDefinitionfrom fastapi import APIRouter, Body, Depends, Header, HTTPException-from letta.errors import LettaToolCreateErrorfrom letta.orm.errors import UniqueConstraintViolationErrorfrom letta.schemas.letta_message import ToolReturnMessagediff --git a/letta/server/rest_api/routers/v1/users.py b/letta/server/rest_api/routers/v1/users.pyindex 27a2feeb0..2dfeb06b1 100644--- a/letta/server/rest_api/routers/v1/users.py+++ b/letta/server/rest_api/routers/v1/users.py@@ -1,7 +1,6 @@from typing import TYPE_CHECKING, List, Optionalfrom fastapi import APIRouter, Body, Depends, HTTPException, Query-from letta.schemas.user import User, UserCreate, UserUpdatefrom letta.server.rest_api.utils import get_letta_serverdiff --git a/letta/server/rest_api/utils.py b/letta/server/rest_api/utils.pyindex 86a889904..650f0e3e4 100644--- a/letta/server/rest_api/utils.py+++ b/letta/server/rest_api/utils.py@@ -6,12 +6,11 @@ from enum import Enumfrom typing import AsyncGenerator, Optional, Unionfrom fastapi import Header-from pydantic import BaseModel-from letta.errors import ContextWindowExceededError, RateLimitExceededErrorfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.server.rest_api.interface import StreamingServerInterfacefrom letta.server.server import SyncServer+from pydantic import BaseModel# from letta.orm.user import User# from letta.orm.utilities import get_db_session@@ -102,6 +101,7 @@ def get_user_id(user_id: Optional[str] = Header(None, alias="user_id")) -> Optiodef get_current_interface() -> StreamingServerInterface:return StreamingServerInterface+def log_error_to_sentry(e):import tracebackdiff --git a/letta/server/server.py b/letta/server/server.pyindex 85aee52b2..17bc5771b 100644--- a/letta/server/server.py+++ b/letta/server/server.py@@ -7,13 +7,12 @@ from abc import abstractmethodfrom datetime import datetimefrom typing import Callable, List, Optional, Tuple, Union-from composio.client import Composio-from composio.client.collections import ActionModel, AppModel-from fastapi import HTTPException-import letta.constants as constantsimport letta.server.utils as server_utilsimport letta.system as system+from composio.client import Composio+from composio.client.collections import ActionModel, AppModel+from fastapi import HTTPExceptionfrom letta.agent import Agent, save_agentfrom letta.chat_only_agent import ChatOnlyAgentfrom letta.credentials import LettaCredentials@@ -139,17 +138,16 @@ class Server(object):from contextlib import contextmanager+from letta.config import LettaConfig++# NOTE: hack to see if single session management works+from letta.settings import model_settings, settings, tool_settingsfrom rich.console import Consolefrom rich.panel import Panelfrom rich.text import Textfrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker-from letta.config import LettaConfig--# NOTE: hack to see if single session management works-from letta.settings import model_settings, settings, tool_settings-config = LettaConfig.load()diff --git a/letta/server/ws_api/example_client.py b/letta/server/ws_api/example_client.pyindex a7fc57b52..fdfdd6605 100644--- a/letta/server/ws_api/example_client.py+++ b/letta/server/ws_api/example_client.py@@ -1,8 +1,7 @@import asyncio-import websockets-import letta.server.ws_api.protocol as protocol+import websocketsfrom letta.server.constants import WS_CLIENT_TIMEOUT, WS_DEFAULT_PORTfrom letta.server.utils import condition_to_stop_receiving, print_server_responsediff --git a/letta/server/ws_api/server.py b/letta/server/ws_api/server.pyindex e2408ddaa..b3dcc2ba1 100644--- a/letta/server/ws_api/server.py+++ b/letta/server/ws_api/server.py@@ -3,9 +3,8 @@ import signalimport sysimport traceback-import websockets-import letta.server.ws_api.protocol as protocol+import websocketsfrom letta.server.constants import WS_DEFAULT_PORTfrom letta.server.server import SyncServerfrom letta.server.ws_api.interface import SyncWebSocketInterfacediff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.pyindex 4e6b80ec5..b1040f313 100644--- a/letta/services/agent_manager.py+++ b/letta/services/agent_manager.py@@ -2,8 +2,6 @@ from datetime import datetimefrom typing import Dict, List, Optionalimport numpy as np-from sqlalchemy import Select, func, literal, select, union_all-from letta.constants import BASE_MEMORY_TOOLS, BASE_TOOLS, MAX_EMBEDDING_DIMfrom letta.embeddings import embedding_modelfrom letta.log import get_logger@@ -40,6 +38,7 @@ from letta.services.source_manager import SourceManagerfrom letta.services.tool_manager import ToolManagerfrom letta.settings import settingsfrom letta.utils import enforce_types, get_utc_time, united_diff+from sqlalchemy import Select, func, literal, select, union_alllogger = get_logger(__name__)diff --git a/letta/services/passage_manager.py b/letta/services/passage_manager.pyindex d8554063b..f80e01602 100644--- a/letta/services/passage_manager.py+++ b/letta/services/passage_manager.py@@ -1,21 +1,15 @@-from typing import List, Optionalfrom datetime import datetime-import numpy as np--from sqlalchemy import select, union_all, literal+from typing import List, Optional-from letta.constants import MAX_EMBEDDING_DIMfrom letta.embeddings import embedding_model, parse_and_chunk_textfrom letta.orm.errors import NoResultFoundfrom letta.orm.passage import AgentPassage, SourcePassagefrom letta.schemas.agent import AgentState-from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.passage import Passage as PydanticPassagefrom letta.schemas.user import User as PydanticUserfrom letta.utils import enforce_types-class PassageManager:"""Manager class to handle business logic related to Passages."""diff --git a/letta/settings.py b/letta/settings.pyindex 1b6ba44bb..3b9af8018 100644--- a/letta/settings.py+++ b/letta/settings.py@@ -1,11 +1,10 @@from pathlib import Pathfrom typing import Optional+from letta.local_llm.constants import DEFAULT_WRAPPER_NAMEfrom pydantic import Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDict-from letta.local_llm.constants import DEFAULT_WRAPPER_NAME-class ToolSettings(BaseSettings):composio_api_key: Optional[str] = Nonediff --git a/letta/streaming_interface.py b/letta/streaming_interface.pyindex e21e5e73e..f79865309 100644--- a/letta/streaming_interface.py+++ b/letta/streaming_interface.py@@ -3,11 +3,6 @@ from abc import ABC, abstractmethodfrom datetime import datetimefrom typing import List, Optional-# from colorama import Fore, Style, init-from rich.console import Console-from rich.live import Live-from rich.markup import escape-from letta.interface import CLIInterfacefrom letta.local_llm.constants import (ASSISTANT_MESSAGE_CLI_SYMBOL,@@ -19,6 +14,11 @@ from letta.schemas.openai.chat_completion_response import (ChatCompletionResponse,)+# from colorama import Fore, Style, init+from rich.console import Console+from rich.live import Live+from rich.markup import escape+# init(autoreset=True)# DEBUG = True # puts full message outputs in the terminaldiff --git a/letta/utils.py b/letta/utils.pyindex 4be8a543f..f80159644 100644--- a/letta/utils.py+++ b/letta/utils.py@@ -19,11 +19,9 @@ from typing import List, Union, _GenericAlias, get_args, get_origin, get_type_hifrom urllib.parse import urljoin, urlparseimport demjson3 as demjson+import lettaimport pytzimport tiktoken-from pathvalidate import sanitize_filename as pathvalidate_sanitize_filename--import lettafrom letta.constants import (CLI_WARNING_PREFIX,CORE_MEMORY_HUMAN_CHAR_LIMIT,@@ -34,6 +32,7 @@ from letta.constants import (TOOL_CALL_ID_MAX_LEN,)from letta.schemas.openai.chat_completion_response import ChatCompletionResponse+from pathvalidate import sanitize_filename as pathvalidate_sanitize_filenameDEBUG = Falseif "LOG_LEVEL" in os.environ:@@ -1120,6 +1119,7 @@ def sanitize_filename(filename: str) -> str:# Return the sanitized filenamereturn sanitized_filename+def get_friendly_error_msg(function_name: str, exception_name: str, exception_message: str):from letta.constants import MAX_ERROR_MESSAGE_CHAR_LIMITdiff --git a/locust_test.py b/locust_test.pyindex 570e6eef4..bf32fb489 100644--- a/locust_test.py+++ b/locust_test.py@@ -1,8 +1,6 @@import randomimport string-from locust import HttpUser, between, task-from letta.constants import BASE_TOOLS, DEFAULT_HUMAN, DEFAULT_PERSONAfrom letta.schemas.agent import AgentState, CreateAgentfrom letta.schemas.letta_request import LettaRequest@@ -10,6 +8,7 @@ from letta.schemas.letta_response import LettaResponsefrom letta.schemas.memory import ChatMemoryfrom letta.schemas.message import MessageCreate, MessageRolefrom letta.utils import get_human_text, get_persona_text+from locust import HttpUser, between, taskclass LettaUser(HttpUser):diff --git a/paper_experiments/doc_qa_task/doc_qa.py b/paper_experiments/doc_qa_task/doc_qa.pyindex e07060d1a..205fa0d01 100644--- a/paper_experiments/doc_qa_task/doc_qa.py+++ b/paper_experiments/doc_qa_task/doc_qa.py@@ -23,9 +23,6 @@ import uuidfrom typing import Listfrom icml_experiments.utils import get_experiment_config, load_gzipped_file-from openai import OpenAI-from tqdm import tqdm-from letta import utilsfrom letta.agent_store.storage import StorageConnector, TableTypefrom letta.cli.cli_config import delete@@ -33,6 +30,8 @@ from letta.config import LettaConfigfrom letta.credentials import LettaCredentialsfrom letta.embeddings import embedding_modelfrom letta.utils import count_tokens+from openai import OpenAI+from tqdm import tqdmDATA_SOURCE_NAME = "wikipedia"DOC_QA_PERSONA = "You are Letta DOC-QA bot. Your job is to answer questions about documents that are stored in your archival memory. The answer to the users question will ALWAYS be in your archival memory, so remember to keep searching if you can't find the answer. Answer the questions as if though the year is 2018." # TODO decide on a good persona/humandiff --git a/paper_experiments/doc_qa_task/llm_judge_doc_qa.py b/paper_experiments/doc_qa_task/llm_judge_doc_qa.pyindex c6ff6cfee..18d907a36 100644--- a/paper_experiments/doc_qa_task/llm_judge_doc_qa.py+++ b/paper_experiments/doc_qa_task/llm_judge_doc_qa.py@@ -2,11 +2,10 @@ import argparseimport jsonimport re+from letta.credentials import LettaCredentialsfrom openai import OpenAIfrom tqdm import tqdm-from letta.credentials import LettaCredentials-# Note: did not end up using since no cases of cheating were observed# CHEATING_PROMPT = \# """diff --git a/paper_experiments/doc_qa_task/load_wikipedia_embeddings.py b/paper_experiments/doc_qa_task/load_wikipedia_embeddings.pyindex 94b981437..e80e7e9bc 100644--- a/paper_experiments/doc_qa_task/load_wikipedia_embeddings.py+++ b/paper_experiments/doc_qa_task/load_wikipedia_embeddings.py@@ -8,11 +8,10 @@ from concurrent.futures import ThreadPoolExecutor, as_completedfrom absl import app, flagsfrom icml_experiments.utils import get_experiment_config-from tqdm import tqdm-from letta.agent_store.storage import StorageConnector, TableTypefrom letta.cli.cli_config import deletefrom letta.data_types import Passage+from tqdm import tqdm# Create an empty list to store the JSON objectssource_name = "wikipedia"diff --git a/paper_experiments/nested_kv_task/nested_kv.py b/paper_experiments/nested_kv_task/nested_kv.pyindex 04c95ac54..64fa06a26 100644--- a/paper_experiments/nested_kv_task/nested_kv.py+++ b/paper_experiments/nested_kv_task/nested_kv.py@@ -29,11 +29,10 @@ from typing import Optionalimport openaifrom icml_experiments.utils import get_experiment_config, load_gzipped_file-from tqdm import tqdm-from letta import utilsfrom letta.cli.cli_config import deletefrom letta.config import LettaConfig+from tqdm import tqdm# TODO: update personasNESTED_PERSONA = "You are Letta DOC-QA bot. Your job is to answer questions about documents that are stored in your archival memory. The answer to the users question will ALWAYS be in your archival memory, so remember to keep searching if you can't find the answer. DO NOT STOP SEARCHING UNTIL YOU VERIFY THAT THE VALUE IS NOT A KEY. Do not stop making nested lookups until this condition is met." # TODO decide on a good persona/humandiff --git a/scripts/migrate_tools.py b/scripts/migrate_tools.pyindex 53578c690..91e16071e 100644--- a/scripts/migrate_tools.py+++ b/scripts/migrate_tools.py@@ -1,8 +1,7 @@-from tqdm import tqdm-from letta.schemas.user import Userfrom letta.services.organization_manager import OrganizationManagerfrom letta.services.tool_manager import ToolManager+from tqdm import tqdmdef deprecated_tool():diff --git a/tests/integration_test_agent_tool_graph.py b/tests/integration_test_agent_tool_graph.pyindex 44aad0d07..289b023a5 100644--- a/tests/integration_test_agent_tool_graph.py+++ b/tests/integration_test_agent_tool_graph.py@@ -194,16 +194,13 @@ def test_check_tool_rules_with_different_models(mock_e2b_api_key_none):"tests/configs/llm_model_configs/openai-gpt-3.5-turbo.json","tests/configs/llm_model_configs/openai-gpt-4o.json",]-+# Create two test toolst1_name = "first_secret_word"t2_name = "second_secret_word"t1 = client.create_or_update_tool(first_secret_word, name=t1_name)t2 = client.create_or_update_tool(second_secret_word, name=t2_name)- tool_rules = [- InitToolRule(tool_name=t1_name),- InitToolRule(tool_name=t2_name)- ]+ tool_rules = [InitToolRule(tool_name=t1_name), InitToolRule(tool_name=t2_name)]tools = [t1, t2]for config_file in config_files:@@ -212,34 +209,26 @@ def test_check_tool_rules_with_different_models(mock_e2b_api_key_none):if "gpt-4o" in config_file:# Structured output model (should work with multiple init tools)- agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid,- tool_ids=[t.id for t in tools],- tool_rules=tool_rules)+ agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)assert agent_state is not Noneelse:# Non-structured output model (should raise error with multiple init tools)with pytest.raises(ValueError, match="Multiple initial tools are not supported for non-structured models"):- setup_agent(client, config_file, agent_uuid=agent_uuid,- tool_ids=[t.id for t in tools],- tool_rules=tool_rules)-+ setup_agent(client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)+# Cleanupcleanup(client=client, agent_uuid=agent_uuid)# Create tool rule with single initial toolt3_name = "third_secret_word"t3 = client.create_or_update_tool(third_secret_word, name=t3_name)- tool_rules = [- InitToolRule(tool_name=t3_name)- ]+ tool_rules = [InitToolRule(tool_name=t3_name)]tools = [t3]for config_file in config_files:agent_uuid = str(uuid.uuid4())# Structured output model (should work with single init tool)- agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid,- tool_ids=[t.id for t in tools],- tool_rules=tool_rules)+ agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)assert agent_state is not Nonecleanup(client=client, agent_uuid=agent_uuid)@@ -257,7 +246,7 @@ def test_claude_initial_tool_rule_enforced(mock_e2b_api_key_none):tool_rules = [InitToolRule(tool_name=t1_name),ChildToolRule(tool_name=t1_name, children=[t2_name]),- TerminalToolRule(tool_name=t2_name)+ TerminalToolRule(tool_name=t2_name),]tools = [t1, t2]@@ -265,7 +254,9 @@ def test_claude_initial_tool_rule_enforced(mock_e2b_api_key_none):anthropic_config_file = "tests/configs/llm_model_configs/claude-3-sonnet-20240229.json"for i in range(3):agent_uuid = str(uuid.uuid4())- agent_state = setup_agent(client, anthropic_config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)+ agent_state = setup_agent(+ client, anthropic_config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules+ )response = client.user_message(agent_id=agent_state.id, message="What is the second secret word?")assert_sanity_checks(response)@@ -289,9 +280,10 @@ def test_claude_initial_tool_rule_enforced(mock_e2b_api_key_none):# Implement exponential backoff with initial time of 10 secondsif i < 2:- backoff_time = 10 * (2 ** i)+ backoff_time = 10 * (2**i)time.sleep(backoff_time)+@pytest.mark.timeout(60) # Sets a 60-second timeout for the test since this could loop infinitelydef test_agent_no_structured_output_with_one_child_tool(mock_e2b_api_key_none):client = create_client()@@ -389,7 +381,7 @@ def test_agent_conditional_tool_easy(mock_e2b_api_key_none):default_child=coin_flip_name,child_output_mapping={"hj2hwibbqm": secret_word_tool,- }+ },),TerminalToolRule(tool_name=secret_word_tool),]@@ -425,7 +417,6 @@ def test_agent_conditional_tool_easy(mock_e2b_api_key_none):cleanup(client=client, agent_uuid=agent_uuid)-@pytest.mark.timeout(90) # Longer timeout since this test has more stepsdef test_agent_conditional_tool_hard(mock_e2b_api_key_none):"""@@ -450,7 +441,7 @@ def test_agent_conditional_tool_hard(mock_e2b_api_key_none):final_tool = "fourth_secret_word"play_game_tool = client.create_or_update_tool(can_play_game, name=play_game)flip_coin_tool = client.create_or_update_tool(flip_coin_hard, name=coin_flip_name)- reveal_secret = client.create_or_update_tool(fourth_secret_word, name=final_tool)+ reveal_secret = client.create_or_update_tool(fourth_secret_word, name=final_tool)# Make tool rules - chain them together with conditional rulestool_rules = [@@ -458,16 +449,10 @@ def test_agent_conditional_tool_hard(mock_e2b_api_key_none):ConditionalToolRule(tool_name=play_game,default_child=play_game, # Keep trying if we can't play- child_output_mapping={- True: coin_flip_name # Only allow access when can_play_game returns True- }+ child_output_mapping={True: coin_flip_name}, # Only allow access when can_play_game returns True),ConditionalToolRule(- tool_name=coin_flip_name,- default_child=coin_flip_name,- child_output_mapping={- "hj2hwibbqm": final_tool, "START_OVER": play_game- }+ tool_name=coin_flip_name, default_child=coin_flip_name, child_output_mapping={"hj2hwibbqm": final_tool, "START_OVER": play_game}),TerminalToolRule(tool_name=final_tool),]@@ -475,13 +460,7 @@ def test_agent_conditional_tool_hard(mock_e2b_api_key_none):# Setup agent with all toolstools = [play_game_tool, flip_coin_tool, reveal_secret]config_file = "tests/configs/llm_model_configs/claude-3-sonnet-20240229.json"- agent_state = setup_agent(- client,- config_file,- agent_uuid=agent_uuid,- tool_ids=[t.id for t in tools],- tool_rules=tool_rules- )+ agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)# Ask agent to try to get all secret wordsresponse = client.user_message(agent_id=agent_state.id, message="hi")@@ -520,7 +499,7 @@ def test_agent_conditional_tool_without_default_child(mock_e2b_api_key_none):Test the agent with a conditional tool that allows any child tool to be called if a function returns None.Tool Flow:-+return_none|v@@ -541,27 +520,16 @@ def test_agent_conditional_tool_without_default_child(mock_e2b_api_key_none):ConditionalToolRule(tool_name=tool_name,default_child=None, # Allow any tool to be called if output doesn't match- child_output_mapping={- "anything but none": "first_secret_word"- }- )+ child_output_mapping={"anything but none": "first_secret_word"},+ ),]tools = [tool, secret_word]# Setup agent with all tools- agent_state = setup_agent(- client,- config_file,- agent_uuid=agent_uuid,- tool_ids=[t.id for t in tools],- tool_rules=tool_rules- )+ agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)# Ask agent to try different tools based on the game output- response = client.user_message(- agent_id=agent_state.id,- message="call a function, any function. then call send_message"- )+ response = client.user_message(agent_id=agent_state.id, message="call a function, any function. then call send_message")# Make checksassert_sanity_checks(response)@@ -613,18 +581,14 @@ def test_agent_reload_remembers_function_response(mock_e2b_api_key_none):ConditionalToolRule(tool_name=flip_coin_name,default_child=flip_coin_name, # Allow any tool to be called if output doesn't match- child_output_mapping={- "hj2hwibbqm": secret_word- }+ child_output_mapping={"hj2hwibbqm": secret_word},),- TerminalToolRule(tool_name=secret_word)+ TerminalToolRule(tool_name=secret_word),]tools = [flip_coin_tool, secret_word_tool]# Setup initial agent- agent_state = setup_agent(- client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules- )+ agent_state = setup_agent(client, config_file, agent_uuid=agent_uuid, tool_ids=[t.id for t in tools], tool_rules=tool_rules)# Call flip_coin firstresponse = client.user_message(agent_id=agent_state.id, message="flip a coin")@@ -643,4 +607,4 @@ def test_agent_reload_remembers_function_response(mock_e2b_api_key_none):assert reloaded_agent.last_function_response is not Noneprint(f"Got successful response from client: \n\n{response}")- cleanup(client=client, agent_uuid=agent_uuid)\ No newline at end of file+ cleanup(client=client, agent_uuid=agent_uuid)diff --git a/tests/integration_test_offline_memory_agent.py b/tests/integration_test_offline_memory_agent.pyindex 15d4161d5..5803e8205 100644--- a/tests/integration_test_offline_memory_agent.py+++ b/tests/integration_test_offline_memory_agent.py@@ -1,5 +1,4 @@import pytest-from letta import BasicBlockMemoryfrom letta.client.client import Block, create_clientfrom letta.constants import DEFAULT_HUMAN, DEFAULT_PERSONAdiff --git a/tests/integration_test_summarizer.py b/tests/integration_test_summarizer.pyindex b4de0043b..ce6c41b25 100644--- a/tests/integration_test_summarizer.py+++ b/tests/integration_test_summarizer.py@@ -4,7 +4,6 @@ import uuidfrom typing import Listimport pytest-from letta import create_clientfrom letta.agent import Agentfrom letta.client.client import LocalClientdiff --git a/tests/integration_test_tool_execution_sandbox.py b/tests/integration_test_tool_execution_sandbox.pyindex 299e1e967..0938fdc87 100644--- a/tests/integration_test_tool_execution_sandbox.py+++ b/tests/integration_test_tool_execution_sandbox.py@@ -5,8 +5,6 @@ from pathlib import Pathfrom unittest.mock import patchimport pytest-from sqlalchemy import delete-from letta import create_clientfrom letta.functions.function_sets.base import core_memory_append, core_memory_replacefrom letta.orm import SandboxConfig, SandboxEnvironmentVariable@@ -31,6 +29,7 @@ from letta.services.tool_execution_sandbox import ToolExecutionSandboxfrom letta.services.tool_manager import ToolManagerfrom letta.services.user_manager import UserManagerfrom letta.settings import tool_settings+from sqlalchemy import deletefrom tests.helpers.utils import create_tool_from_func# Constantsdiff --git a/tests/test_base_functions.py b/tests/test_base_functions.pyindex 5b5bec6f4..007d2bf9c 100644--- a/tests/test_base_functions.py+++ b/tests/test_base_functions.py@@ -1,6 +1,5 @@-import pytest-import letta.functions.function_sets.base as base_functions+import pytestfrom letta import LocalClient, create_clientfrom letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.llm_config import LLMConfigdiff --git a/tests/test_cli.py b/tests/test_cli.pyindex 7b2ffae10..54faa804a 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -4,7 +4,6 @@ import sysimport pexpectimport pytest-from letta.local_llm.constants import (ASSISTANT_MESSAGE_CLI_SYMBOL,INNER_THOUGHTS_CLI_SYMBOL,diff --git a/tests/test_client.py b/tests/test_client.pyindex ac0f4f187..71f7216c1 100644--- a/tests/test_client.py+++ b/tests/test_client.py@@ -8,8 +8,6 @@ from typing import List, Unionimport pytestfrom dotenv import load_dotenv-from sqlalchemy import delete-from letta import LocalClient, RESTClient, create_clientfrom letta.orm import SandboxConfig, SandboxEnvironmentVariablefrom letta.schemas.agent import AgentState@@ -20,6 +18,7 @@ from letta.schemas.letta_message import ToolReturnMessagefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.sandbox_config import LocalSandboxConfig, SandboxTypefrom letta.utils import create_random_username+from sqlalchemy import delete# ConstantsSERVER_PORT = 8283@@ -341,7 +340,9 @@ def test_messages(client: Union[LocalClient, RESTClient], agent: AgentState):def test_send_system_message(client: Union[LocalClient, RESTClient], agent: AgentState):"""Important unit test since the Letta API exposes sending system messages, but some backends don't natively support it (eg Anthropic)"""- send_system_message_response = client.send_message(agent_id=agent.id, message="Event occurred: The user just logged off.", role="system")+ send_system_message_response = client.send_message(+ agent_id=agent.id, message="Event occurred: The user just logged off.", role="system"+ )assert send_system_message_response, "Sending message failed"@@ -390,7 +391,7 @@ def test_function_always_error(client: Union[LocalClient, RESTClient]):"""Always throw an error."""- return 5/0+ return 5 / 0tool = client.create_or_update_tool(func=always_error)agent = client.create_agent(tool_ids=[tool.id])@@ -410,8 +411,8 @@ def test_function_always_error(client: Union[LocalClient, RESTClient]):assert response_message.tool_return == "Error executing function always_error: ZeroDivisionError: division by zero"else:response_json = json.loads(response_message.tool_return)- assert response_json['status'] == "Failed"- assert response_json['message'] == "Error executing function always_error: ZeroDivisionError: division by zero"+ assert response_json["status"] == "Failed"+ assert response_json["message"] == "Error executing function always_error: ZeroDivisionError: division by zero"client.delete_agent(agent_id=agent.id)diff --git a/tests/test_client_legacy.py b/tests/test_client_legacy.pyindex 3d907fa37..a635a28e3 100644--- a/tests/test_client_legacy.py+++ b/tests/test_client_legacy.py@@ -7,8 +7,6 @@ from typing import List, Unionimport pytestfrom dotenv import load_dotenv-from sqlalchemy import delete-from letta import create_clientfrom letta.client.client import LocalClient, RESTClientfrom letta.constants import BASE_MEMORY_TOOLS, BASE_TOOLS, DEFAULT_PRESET@@ -34,6 +32,7 @@ from letta.services.organization_manager import OrganizationManagerfrom letta.services.user_manager import UserManagerfrom letta.settings import model_settingsfrom letta.utils import get_utc_time+from sqlalchemy import deletefrom tests.helpers.client_helper import upload_file_using_client# from tests.utils import create_configdiff --git a/tests/test_local_client.py b/tests/test_local_client.pyindex da5e533c5..8b0c76178 100644--- a/tests/test_local_client.py+++ b/tests/test_local_client.py@@ -1,7 +1,6 @@import uuidimport pytest-from letta import create_clientfrom letta.client.client import LocalClientfrom letta.schemas.agent import AgentStatediff --git a/tests/test_managers.py b/tests/test_managers.pyindex 388d477c6..5dac4c893 100644--- a/tests/test_managers.py+++ b/tests/test_managers.py@@ -3,9 +3,6 @@ import timefrom datetime import datetime, timedeltaimport pytest-from sqlalchemy import delete-from sqlalchemy.exc import IntegrityError-from letta.config import LettaConfigfrom letta.constants import BASE_MEMORY_TOOLS, BASE_TOOLSfrom letta.embeddings import embedding_model@@ -63,6 +60,8 @@ from letta.server.server import SyncServerfrom letta.services.block_manager import BlockManagerfrom letta.services.organization_manager import OrganizationManagerfrom letta.settings import tool_settings+from sqlalchemy import delete+from sqlalchemy.exc import IntegrityErrorfrom tests.helpers.utils import comprehensive_agent_checksDEFAULT_EMBEDDING_CONFIG = EmbeddingConfig(diff --git a/tests/test_server.py b/tests/test_server.pyindex 4775ed91f..631ec1f38 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -3,9 +3,8 @@ import uuidimport warningsfrom typing import List, Tuple-import pytest-import letta.utils as utils+import pytestfrom letta.constants import BASE_MEMORY_TOOLS, BASE_TOOLSfrom letta.schemas.block import CreateBlockfrom letta.schemas.enums import MessageRolediff --git a/tests/test_stream_buffer_readers.py b/tests/test_stream_buffer_readers.pyindex 9a0bb5e85..92335cc70 100644--- a/tests/test_stream_buffer_readers.py+++ b/tests/test_stream_buffer_readers.py@@ -1,7 +1,6 @@import jsonimport pytest-from letta.streaming_utils import JSONInnerThoughtsExtractordiff --git a/tests/test_tool_rule_solver.py b/tests/test_tool_rule_solver.pyindex c524d53a3..3504ed98d 100644--- a/tests/test_tool_rule_solver.py+++ b/tests/test_tool_rule_solver.py@@ -1,12 +1,11 @@import pytest-from letta.helpers import ToolRulesSolverfrom letta.helpers.tool_rule_solver import ToolRuleValidationErrorfrom letta.schemas.tool_rule import (ChildToolRule,ConditionalToolRule,InitToolRule,- TerminalToolRule+ TerminalToolRule,)# Constants for tool names used in the tests@@ -113,11 +112,7 @@ def test_conditional_tool_rule():# Setup: Define a conditional tool ruleinit_rule = InitToolRule(tool_name=START_TOOL)terminal_rule = TerminalToolRule(tool_name=END_TOOL)- rule = ConditionalToolRule(- tool_name=START_TOOL,- default_child=None,- child_output_mapping={True: END_TOOL, False: START_TOOL}- )+ rule = ConditionalToolRule(tool_name=START_TOOL, default_child=None, child_output_mapping={True: END_TOOL, False: START_TOOL})solver = ToolRulesSolver(tool_rules=[init_rule, rule, terminal_rule])# Action & Assert: Verify the rule properties@@ -126,8 +121,12 @@ def test_conditional_tool_rule():# Step 2: After using 'start_tool'solver.update_tool_usage(START_TOOL)- assert solver.get_allowed_tool_names(last_function_response='{"message": "true"}') == [END_TOOL], "After 'start_tool' returns true, should allow 'end_tool'"- assert solver.get_allowed_tool_names(last_function_response='{"message": "false"}') == [START_TOOL], "After 'start_tool' returns false, should allow 'start_tool'"+ assert solver.get_allowed_tool_names(last_function_response='{"message": "true"}') == [+ END_TOOL+ ], "After 'start_tool' returns true, should allow 'end_tool'"+ assert solver.get_allowed_tool_names(last_function_response='{"message": "false"}') == [+ START_TOOL+ ], "After 'start_tool' returns false, should allow 'start_tool'"# Step 3: After using 'end_tool'assert solver.is_terminal_tool(END_TOOL) is True, "Should recognize 'end_tool' as terminal"@@ -137,11 +136,7 @@ def test_invalid_conditional_tool_rule():# Setup: Define an invalid conditional tool ruleinit_rule = InitToolRule(tool_name=START_TOOL)terminal_rule = TerminalToolRule(tool_name=END_TOOL)- invalid_rule_1 = ConditionalToolRule(- tool_name=START_TOOL,- default_child=END_TOOL,- child_output_mapping={}- )+ invalid_rule_1 = ConditionalToolRule(tool_name=START_TOOL, default_child=END_TOOL, child_output_mapping={})# Test 1: Missing child output mappingwith pytest.raises(ToolRuleValidationError, match="Conditional tool rule must have at least one child tool."):diff --git a/tests/test_tool_schema_parsing.py b/tests/test_tool_schema_parsing.pyindex f6738a06f..6eed18f19 100644--- a/tests/test_tool_schema_parsing.py+++ b/tests/test_tool_schema_parsing.py@@ -2,7 +2,6 @@ import jsonimport osimport pytest-from letta.functions.functions import derive_openai_json_schemafrom letta.llm_api.helpers import convert_to_structured_output, make_post_requestdiff --git a/tests/test_utils.py b/tests/test_utils.pyindex 904e903e7..f8fd42ddb 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -1,5 +1,4 @@import pytest-from letta.constants import MAX_FILENAME_LENGTHfrom letta.utils import sanitize_filenamediff --git a/tests/test_v1_routes.py b/tests/test_v1_routes.pyindex 2865bb2ec..266d8dcbd 100644--- a/tests/test_v1_routes.py+++ b/tests/test_v1_routes.py@@ -8,7 +8,6 @@ from composio.client.collections import (AppModel,)from fastapi.testclient import TestClient-from letta.schemas.tool import ToolCreate, ToolUpdatefrom letta.server.rest_api.app import appfrom letta.server.rest_api.utils import get_letta_serverdiff --git a/tests/test_vector_embeddings.py b/tests/test_vector_embeddings.pyindex e65e6b9b1..8640f628f 100644--- a/tests/test_vector_embeddings.py+++ b/tests/test_vector_embeddings.py@@ -1,5 +1,4 @@import numpy as np-from letta.orm.sqlalchemy_base import adapt_arrayfrom letta.orm.sqlite_functions import convert_array, verify_embedding_dimensiondiff --git a/tests/utils.py b/tests/utils.pyindex 19a05a090..3ce1cb62b 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -5,7 +5,6 @@ from importlib import utilfrom typing import Dict, Iterator, List, Tupleimport requests-from letta.config import LettaConfigfrom letta.data_sources.connectors import DataConnectorfrom letta.schemas.file import FileMetadata