Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
chore: bump v0.8.16 (#2724)
cthomas8bce54046614
diff --git a/alembic/env.py b/alembic/env.pyindex 8b60f2d47..dac40ea43 100644--- a/alembic/env.py+++ b/alembic/env.py@@ -6,7 +6,7 @@ from sqlalchemy import engine_from_config, poolfrom alembic import contextfrom letta.config import LettaConfigfrom letta.orm import Base-from letta.settings import settings+from letta.settings import DatabaseChoice, settingsletta_config = LettaConfig.load()@@ -14,9 +14,9 @@ letta_config = LettaConfig.load()# access to the values within the .ini file in use.config = context.config-if settings.letta_pg_uri_no_default:+if settings.database_engine is DatabaseChoice.POSTGRES:config.set_main_option("sqlalchemy.url", settings.letta_pg_uri)- print(f"Using database: ", settings.letta_pg_uri)+ print("Using database: ", settings.letta_pg_uri)else:config.set_main_option("sqlalchemy.url", "sqlite:///" + os.path.join(letta_config.recall_storage_path, "sqlite.db"))diff --git a/alembic/versions/0335b1eb9c40_add_batch_item_id_to_messages.py b/alembic/versions/0335b1eb9c40_add_batch_item_id_to_messages.pyindex 01c874292..1c047db8c 100644--- a/alembic/versions/0335b1eb9c40_add_batch_item_id_to_messages.py+++ b/alembic/versions/0335b1eb9c40_add_batch_item_id_to_messages.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "0335b1eb9c40"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("messages", sa.Column("batch_item_id", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("messages", "batch_item_id")# ### end Alembic commands ###diff --git a/alembic/versions/08b2f8225812_adding_toolsagents_orm.py b/alembic/versions/08b2f8225812_adding_toolsagents_orm.pyindex 0da80aae5..da0e190e0 100644--- a/alembic/versions/08b2f8225812_adding_toolsagents_orm.py+++ b/alembic/versions/08b2f8225812_adding_toolsagents_orm.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "08b2f8225812"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("tools_agents",@@ -44,6 +49,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("tools_agents")# ### end Alembic commands ###diff --git a/alembic/versions/0b496eae90de_add_file_agent_table.py b/alembic/versions/0b496eae90de_add_file_agent_table.pyindex 91b107813..e5222067b 100644--- a/alembic/versions/0b496eae90de_add_file_agent_table.py+++ b/alembic/versions/0b496eae90de_add_file_agent_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "0b496eae90de"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("files_agents",@@ -48,6 +53,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_files_agents_file_id_agent_id", table_name="files_agents")op.drop_table("files_agents")diff --git a/alembic/versions/0ceb975e0063_add_llm_batch_jobs_tables.py b/alembic/versions/0ceb975e0063_add_llm_batch_jobs_tables.pyindex fee45f75e..625a6e0fe 100644--- a/alembic/versions/0ceb975e0063_add_llm_batch_jobs_tables.py+++ b/alembic/versions/0ceb975e0063_add_llm_batch_jobs_tables.py@@ -12,6 +12,7 @@ import sqlalchemy as saimport lettafrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "0ceb975e0063"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("llm_batch_job",@@ -75,6 +80,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_llm_batch_items_status", table_name="llm_batch_items")op.drop_index("ix_llm_batch_items_batch_id", table_name="llm_batch_items")diff --git a/alembic/versions/167491cfb7a8_add_identities_for_blocks.py b/alembic/versions/167491cfb7a8_add_identities_for_blocks.pyindex 8e0b8a17d..8f0e04d25 100644--- a/alembic/versions/167491cfb7a8_add_identities_for_blocks.py+++ b/alembic/versions/167491cfb7a8_add_identities_for_blocks.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "167491cfb7a8"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("identities_blocks",@@ -33,6 +38,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("identities_blocks")# ### end Alembic commands ###diff --git a/alembic/versions/18e300709530_add_instructions_field_to_sources.py b/alembic/versions/18e300709530_add_instructions_field_to_sources.pyindex 138494d0a..9d730c921 100644--- a/alembic/versions/18e300709530_add_instructions_field_to_sources.py+++ b/alembic/versions/18e300709530_add_instructions_field_to_sources.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "18e300709530"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("sources", sa.Column("instructions", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("sources", "instructions")# ### end Alembic commands ###diff --git a/alembic/versions/1af251a42c06_fix_files_agents_constraints.py b/alembic/versions/1af251a42c06_fix_files_agents_constraints.pyindex b5b40eee3..d95d79e31 100644--- a/alembic/versions/1af251a42c06_fix_files_agents_constraints.py+++ b/alembic/versions/1af251a42c06_fix_files_agents_constraints.py@@ -9,6 +9,7 @@ Create Date: 2025-06-30 11:50:42.200885from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "1af251a42c06"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_files_agents_agent_file_name", table_name="files_agents")op.drop_index("ix_files_agents_file_id_agent_id", table_name="files_agents")@@ -31,6 +36,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("uq_file_agent", "files_agents", type_="unique")op.drop_constraint("uq_agent_filename", "files_agents", type_="unique")diff --git a/alembic/versions/1c6b6a38b713_add_pip_requirements_to_tools.py b/alembic/versions/1c6b6a38b713_add_pip_requirements_to_tools.pyindex 52a481985..a4eff890e 100644--- a/alembic/versions/1c6b6a38b713_add_pip_requirements_to_tools.py+++ b/alembic/versions/1c6b6a38b713_add_pip_requirements_to_tools.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "1c6b6a38b713"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("tools", sa.Column("pip_requirements", sa.JSON(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("tools", "pip_requirements")# ### 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..010623635 100644--- a/alembic/versions/1c8880d671ee_make_an_blocks_agents_mapping_table.py+++ b/alembic/versions/1c8880d671ee_make_an_blocks_agents_mapping_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "1c8880d671ee"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_unique_constraint("unique_block_id_label", "block", ["id", "label"])@@ -46,6 +51,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("unique_block_id_label", "block", type_="unique")op.drop_table("blocks_agents")diff --git a/alembic/versions/1dc0fee72dea_add_block_related_indexes.py b/alembic/versions/1dc0fee72dea_add_block_related_indexes.pyindex 89c7d7396..489a14ff0 100644--- a/alembic/versions/1dc0fee72dea_add_block_related_indexes.py+++ b/alembic/versions/1dc0fee72dea_add_block_related_indexes.py@@ -9,6 +9,7 @@ Create Date: 2025-05-12 17:06:32.055091from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "1dc0fee72dea"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade():+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# add index for blocks_agents tableop.create_index("ix_blocks_agents_block_label_agent_id", "blocks_agents", ["block_label", "agent_id"], unique=False)@@ -29,6 +34,10 @@ def upgrade():def downgrade():+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_index("ix_blocks_agents_block_label_agent_id", table_name="blocks_agents")op.drop_index("ix_blocks_block_label", table_name="blocks_agents")op.drop_index("ix_agents_tags_agent_id_tag", table_name="agents_tags")diff --git a/alembic/versions/1e553a664210_add_metadata_to_tools.py b/alembic/versions/1e553a664210_add_metadata_to_tools.pyindex 51b6da205..dd902830f 100644--- a/alembic/versions/1e553a664210_add_metadata_to_tools.py+++ b/alembic/versions/1e553a664210_add_metadata_to_tools.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "1e553a664210"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("tools", sa.Column("metadata_", sa.JSON(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("tools", "metadata_")# ### end Alembic commands ###diff --git a/alembic/versions/220856bbf43b_add_read_only_column.py b/alembic/versions/220856bbf43b_add_read_only_column.pyindex a8a962def..ed4bdb39d 100644--- a/alembic/versions/220856bbf43b_add_read_only_column.py+++ b/alembic/versions/220856bbf43b_add_read_only_column.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "220856bbf43b"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# add default value of `False`op.add_column("block", sa.Column("read_only", sa.Boolean(), nullable=True))op.execute(@@ -32,4 +37,8 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_column("block", "read_only")diff --git a/alembic/versions/22a6e413d89c_remove_module_field_on_tool.py b/alembic/versions/22a6e413d89c_remove_module_field_on_tool.pyindex 8d05aabea..1bab710e6 100644--- a/alembic/versions/22a6e413d89c_remove_module_field_on_tool.py+++ b/alembic/versions/22a6e413d89c_remove_module_field_on_tool.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "22a6e413d89c"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("tools", "module")# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("tools", sa.Column("module", sa.VARCHAR(), autoincrement=False, nullable=True))# ### end Alembic commands ###diff --git a/alembic/versions/25fc99e97839_fix_alembic_check_warnings.py b/alembic/versions/25fc99e97839_fix_alembic_check_warnings.pyindex 47566a8a6..d1cb27f40 100644--- a/alembic/versions/25fc99e97839_fix_alembic_check_warnings.py+++ b/alembic/versions/25fc99e97839_fix_alembic_check_warnings.py@@ -9,6 +9,7 @@ Create Date: 2025-01-16 16:48:21.000000from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "25fc99e97839"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Remove indices from job_messagesop.drop_index("ix_job_messages_created_at", table_name="job_messages")op.drop_index("ix_job_messages_job_id", table_name="job_messages")@@ -31,6 +36,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Remove the foreign key constraintop.drop_constraint("fk_job_messages_message_id", "job_messages", type_="foreignkey")diff --git a/alembic/versions/28b8765bdd0a_add_support_for_structured_outputs_in_.py b/alembic/versions/28b8765bdd0a_add_support_for_structured_outputs_in_.pyindex e5bcab080..a76a8d008 100644--- a/alembic/versions/28b8765bdd0a_add_support_for_structured_outputs_in_.py+++ b/alembic/versions/28b8765bdd0a_add_support_for_structured_outputs_in_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "28b8765bdd0a"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("agents", sa.Column("response_format", sa.JSON(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("agents", "response_format")# ### end Alembic commands ###diff --git a/alembic/versions/2c059cad97cc_create_sqlite_baseline_schema.py b/alembic/versions/2c059cad97cc_create_sqlite_baseline_schema.pynew file mode 100644index 000000000..36410d7b8--- /dev/null+++ b/alembic/versions/2c059cad97cc_create_sqlite_baseline_schema.py@@ -0,0 +1,798 @@+"""create_sqlite_baseline_schema++Revision ID: 2c059cad97cc+Revises: 495f3f474131+Create Date: 2025-07-16 14:34:21.280233++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op+from letta.settings import settings++# revision identifiers, used by Alembic.+revision: str = "2c059cad97cc"+down_revision: Union[str, None] = "495f3f474131"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # Only run this migration for SQLite+ if settings.letta_pg_uri_no_default:+ return++ # Create the exact schema that matches the current PostgreSQL state+ # This is a snapshot of the schema at the time of this migration+ # Based on the schema provided by Andy++ # Organizations table+ op.create_table(+ "organizations",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("privileged_tools", sa.Boolean(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ )++ # Agents table+ op.create_table(+ "agents",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("description", sa.String(), nullable=True),+ sa.Column("message_ids", sa.JSON(), nullable=True),+ sa.Column("system", sa.String(), nullable=True),+ sa.Column("agent_type", sa.String(), nullable=True),+ sa.Column("llm_config", sa.JSON(), nullable=True),+ sa.Column("embedding_config", sa.JSON(), nullable=True),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.Column("tool_rules", sa.JSON(), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("project_id", sa.String(), nullable=True),+ sa.Column("template_id", sa.String(), nullable=True),+ sa.Column("base_template_id", sa.String(), nullable=True),+ sa.Column("message_buffer_autoclear", sa.Boolean(), nullable=False),+ sa.Column("enable_sleeptime", sa.Boolean(), nullable=True),+ sa.Column("response_format", sa.JSON(), nullable=True),+ sa.Column("last_run_completion", sa.DateTime(timezone=True), nullable=True),+ sa.Column("last_run_duration_ms", sa.Integer(), nullable=True),+ sa.Column("timezone", sa.String(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ )+ op.create_index("ix_agents_created_at", "agents", ["created_at", "id"])++ # Block history table (created before block table so block can reference it)+ op.create_table(+ "block_history",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("description", sa.Text(), nullable=True),+ sa.Column("label", sa.String(), nullable=False),+ sa.Column("value", sa.Text(), nullable=False),+ sa.Column("limit", sa.BigInteger(), nullable=False),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.Column("actor_type", sa.String(), nullable=True),+ sa.Column("actor_id", sa.String(), nullable=True),+ sa.Column("block_id", sa.String(), nullable=False),+ sa.Column("sequence_number", sa.Integer(), nullable=False),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ # Note: block_id foreign key will be added later since block table doesn't exist yet+ )+ op.create_index("ix_block_history_block_id_sequence", "block_history", ["block_id", "sequence_number"], unique=True)++ # Block table+ op.create_table(+ "block",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("value", sa.String(), nullable=False),+ sa.Column("limit", sa.Integer(), nullable=False),+ sa.Column("template_name", sa.String(), nullable=True),+ sa.Column("label", sa.String(), nullable=False),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.Column("description", sa.String(), nullable=True),+ sa.Column("is_template", sa.Boolean(), nullable=False),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("current_history_entry_id", sa.String(), nullable=True),+ sa.Column("version", sa.Integer(), server_default="1", nullable=False),+ sa.Column("read_only", sa.Boolean(), nullable=False),+ sa.Column("preserve_on_migration", sa.Boolean(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["current_history_entry_id"], ["block_history.id"], name="fk_block_current_history_entry"),+ sa.UniqueConstraint("id", "label", name="unique_block_id_label"),+ )+ op.create_index("created_at_label_idx", "block", ["created_at", "label"])+ op.create_index("ix_block_current_history_entry_id", "block", ["current_history_entry_id"])++ # Note: Foreign key constraint for block_history.block_id cannot be added in SQLite after table creation+ # This will be enforced at the ORM level++ # Sources table+ op.create_table(+ "sources",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("embedding_config", sa.JSON(), nullable=False),+ sa.Column("description", sa.String(), nullable=True),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("instructions", sa.String(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("name", "organization_id", name="uq_source_name_organization"),+ )+ op.create_index("source_created_at_id_idx", "sources", ["created_at", "id"])++ # Files table+ op.create_table(+ "files",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("source_id", sa.String(), nullable=False),+ sa.Column("file_name", sa.String(), nullable=True),+ sa.Column("file_path", sa.String(), nullable=True),+ sa.Column("file_type", sa.String(), nullable=True),+ sa.Column("file_size", sa.Integer(), nullable=True),+ sa.Column("file_creation_date", sa.String(), nullable=True),+ sa.Column("file_last_modified_date", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("processing_status", sa.String(), nullable=False),+ sa.Column("error_message", sa.Text(), nullable=True),+ sa.Column("original_file_name", sa.String(), nullable=True),+ sa.Column("total_chunks", sa.Integer(), nullable=True),+ sa.Column("chunks_embedded", sa.Integer(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["source_id"], ["sources.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ )+ # Note: SQLite doesn't support expression indexes, so these are simplified+ op.create_index("ix_files_org_created", "files", ["organization_id"])+ op.create_index("ix_files_processing_status", "files", ["processing_status"])+ op.create_index("ix_files_source_created", "files", ["source_id"])++ # Users table+ op.create_table(+ "users",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ )++ # Jobs table+ op.create_table(+ "jobs",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("user_id", sa.String(), nullable=False),+ sa.Column("status", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("job_type", sa.String(), nullable=False),+ sa.Column("request_config", sa.JSON(), nullable=True),+ sa.Column("callback_url", sa.String(), nullable=True),+ sa.Column("callback_sent_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("callback_status_code", sa.Integer(), nullable=True),+ sa.Column("callback_error", sa.String(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),+ )+ op.create_index("ix_jobs_created_at", "jobs", ["created_at", "id"])++ # Tools table+ op.create_table(+ "tools",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("description", sa.String(), nullable=True),+ sa.Column("source_type", sa.String(), nullable=False),+ sa.Column("source_code", sa.String(), nullable=True),+ sa.Column("json_schema", sa.JSON(), nullable=True),+ sa.Column("tags", sa.JSON(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("return_char_limit", sa.Integer(), nullable=True),+ sa.Column("tool_type", sa.String(), nullable=False),+ sa.Column("args_json_schema", sa.JSON(), nullable=True),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.Column("pip_requirements", sa.JSON(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("name", "organization_id", name="uix_name_organization"),+ )+ op.create_index("ix_tools_created_at_name", "tools", ["created_at", "name"])++ # Additional tables based on Andy's schema++ # Agents tags table+ op.create_table(+ "agents_tags",+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("tag", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"]),+ sa.UniqueConstraint("agent_id", "tag", name="unique_agent_tag"),+ )+ op.create_index("ix_agents_tags_agent_id_tag", "agents_tags", ["agent_id", "tag"])++ # Sandbox configs table+ op.create_table(+ "sandbox_configs",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("type", sa.String(), nullable=False), # sandboxtype in PG+ sa.Column("config", sa.JSON(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("type", "organization_id", name="uix_type_organization"),+ )++ # Sandbox environment variables table+ op.create_table(+ "sandbox_environment_variables",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("key", sa.String(), nullable=False),+ sa.Column("value", sa.String(), nullable=False),+ sa.Column("description", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("sandbox_config_id", sa.String(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["sandbox_config_id"], ["sandbox_configs.id"]),+ sa.UniqueConstraint("key", "sandbox_config_id", name="uix_key_sandbox_config"),+ )++ # Blocks agents table+ op.create_table(+ "blocks_agents",+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("block_id", sa.String(), nullable=False),+ sa.Column("block_label", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"]),+ sa.ForeignKeyConstraint(["block_id", "block_label"], ["block.id", "block.label"], deferrable=True, initially="DEFERRED"),+ sa.UniqueConstraint("agent_id", "block_label", name="unique_label_per_agent"),+ sa.UniqueConstraint("agent_id", "block_id", name="unique_agent_block"),+ )+ op.create_index("ix_blocks_agents_block_label_agent_id", "blocks_agents", ["block_label", "agent_id"])+ op.create_index("ix_blocks_block_label", "blocks_agents", ["block_label"])++ # Tools agents table+ op.create_table(+ "tools_agents",+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("tool_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["tool_id"], ["tools.id"], ondelete="CASCADE"),+ sa.UniqueConstraint("agent_id", "tool_id", name="unique_agent_tool"),+ )++ # Sources agents table+ op.create_table(+ "sources_agents",+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("source_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["source_id"], ["sources.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("agent_id", "source_id"),+ )++ # Agent passages table (using BLOB for vectors in SQLite)+ op.create_table(+ "agent_passages",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("text", sa.String(), nullable=False),+ sa.Column("embedding_config", sa.JSON(), nullable=False),+ sa.Column("metadata_", sa.JSON(), nullable=False),+ sa.Column("embedding", sa.BLOB(), nullable=True), # CommonVector becomes BLOB in SQLite+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ )+ # Note: agent_passages_org_idx is not created for SQLite as it's expected to be different+ op.create_index("agent_passages_created_at_id_idx", "agent_passages", ["created_at", "id"])+ op.create_index("ix_agent_passages_org_agent", "agent_passages", ["organization_id", "agent_id"])++ # Source passages table (using BLOB for vectors in SQLite)+ op.create_table(+ "source_passages",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("text", sa.String(), nullable=False),+ sa.Column("embedding_config", sa.JSON(), nullable=False),+ sa.Column("metadata_", sa.JSON(), nullable=False),+ sa.Column("embedding", sa.BLOB(), nullable=True), # CommonVector becomes BLOB in SQLite+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.Column("file_name", sa.String(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["file_id"], ["files.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["source_id"], ["sources.id"], ondelete="CASCADE"),+ )+ # Note: source_passages_org_idx is not created for SQLite as it's expected to be different+ op.create_index("source_passages_created_at_id_idx", "source_passages", ["created_at", "id"])++ # Message sequence is handled by the sequence_id field in messages table++ # Messages table+ op.create_table(+ "messages",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("role", sa.String(), nullable=False),+ sa.Column("text", sa.String(), nullable=True),+ sa.Column("model", sa.String(), nullable=True),+ sa.Column("name", sa.String(), nullable=True),+ sa.Column("tool_calls", sa.JSON(), nullable=False),+ sa.Column("tool_call_id", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("step_id", sa.String(), nullable=True),+ sa.Column("otid", sa.String(), nullable=True),+ sa.Column("tool_returns", sa.JSON(), nullable=True),+ sa.Column("group_id", sa.String(), nullable=True),+ sa.Column("content", sa.JSON(), nullable=True),+ sa.Column("sequence_id", sa.BigInteger(), nullable=False),+ sa.Column("sender_id", sa.String(), nullable=True),+ sa.Column("batch_item_id", sa.String(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["step_id"], ["steps.id"], ondelete="SET NULL"),+ sa.UniqueConstraint("sequence_id", name="uq_messages_sequence_id"),+ )+ op.create_index("ix_messages_agent_created_at", "messages", ["agent_id", "created_at"])+ op.create_index("ix_messages_created_at", "messages", ["created_at", "id"])+ op.create_index("ix_messages_agent_sequence", "messages", ["agent_id", "sequence_id"])+ op.create_index("ix_messages_org_agent", "messages", ["organization_id", "agent_id"])++ # Create sequence table for SQLite message sequence_id generation+ op.create_table(+ "message_sequence",+ sa.Column("id", sa.Integer(), nullable=False),+ sa.Column("next_val", sa.Integer(), nullable=False, server_default="1"),+ sa.PrimaryKeyConstraint("id"),+ )++ # Initialize the sequence table with the next available sequence_id+ op.execute("INSERT INTO message_sequence (id, next_val) VALUES (1, 1)")++ # Now create the rest of the tables that might reference messages/steps++ # Add missing tables and columns identified from alembic check++ # Identities table+ op.create_table(+ "identities",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("identifier_key", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("identity_type", sa.String(), nullable=False),+ sa.Column("project_id", sa.String(), nullable=True),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("properties", sa.JSON(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("identifier_key", "project_id", "organization_id", name="unique_identifier_key_project_id_organization_id"),+ )++ # MCP Server table+ op.create_table(+ "mcp_server",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("server_name", sa.String(), nullable=False),+ sa.Column("server_type", sa.String(), nullable=False),+ sa.Column("server_url", sa.String(), nullable=True),+ sa.Column("stdio_config", sa.JSON(), nullable=True),+ sa.Column("token", sa.String(), nullable=True),+ sa.Column("custom_headers", sa.JSON(), nullable=True),+ sa.Column("organization_id", sa.String(), nullable=False),+ sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("(FALSE)"), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("_created_by_id", sa.String(), nullable=True),+ sa.Column("_last_updated_by_id", sa.String(), nullable=True),+ sa.Column("metadata_", sa.JSON(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("server_name", "organization_id", name="uix_name_organization_mcp_server"),+ )++ # Providers table+ op.create_table(+ "providers",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("name", sa.String(), nullable=False),+ sa.Column("api_key", sa.String(), nullable=True),+ sa.Column("access_key", sa.String(), nullable=True),+ sa.Column("region", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("provider_type", sa.String(), nullable=True),+ sa.Column("base_url", sa.String(), nullable=True),+ sa.Column("provider_category", sa.String(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("name", "organization_id", name="unique_name_organization_id"),+ )++ # Agent environment variables table+ op.create_table(+ "agent_environment_variables",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("key", sa.String(), nullable=False),+ sa.Column("value", sa.String(), nullable=False),+ sa.Column("description", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.UniqueConstraint("key", "agent_id", name="uix_key_agent"),+ )+ op.create_index("idx_agent_environment_variables_agent_id", "agent_environment_variables", ["agent_id"])++ # Groups table+ op.create_table(+ "groups",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("description", sa.String(), nullable=False),+ sa.Column("manager_type", sa.String(), nullable=False),+ sa.Column("manager_agent_id", sa.String(), nullable=True),+ sa.Column("termination_token", sa.String(), nullable=True),+ sa.Column("max_turns", sa.Integer(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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_ids", sa.JSON(), nullable=False),+ sa.Column("sleeptime_agent_frequency", sa.Integer(), nullable=True),+ sa.Column("turns_counter", sa.Integer(), nullable=True),+ sa.Column("last_processed_message_id", sa.String(), nullable=True),+ sa.Column("max_message_buffer_length", sa.Integer(), nullable=True),+ sa.Column("min_message_buffer_length", sa.Integer(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["manager_agent_id"], ["agents.id"], ondelete="RESTRICT"),+ )++ # Steps table+ op.create_table(+ "steps",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("job_id", sa.String(), nullable=True),+ sa.Column("completion_tokens", sa.Integer(), nullable=False, default=0),+ sa.Column("prompt_tokens", sa.Integer(), nullable=False, default=0),+ sa.Column("total_tokens", sa.Integer(), nullable=False, default=0),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("origin", sa.String(), nullable=True),+ sa.Column("organization_id", sa.String(), nullable=True),+ sa.Column("provider_id", sa.String(), nullable=True),+ sa.Column("provider_name", sa.String(), nullable=True),+ sa.Column("model", sa.String(), nullable=True),+ sa.Column("context_window_limit", sa.Integer(), nullable=True),+ sa.Column("completion_tokens_details", sa.JSON(), nullable=True),+ sa.Column("tags", sa.JSON(), nullable=True),+ sa.Column("tid", sa.String(), nullable=True),+ sa.Column("model_endpoint", sa.String(), nullable=True),+ sa.Column("trace_id", sa.String(), nullable=True),+ sa.Column("agent_id", sa.String(), nullable=True),+ sa.Column("provider_category", sa.String(), nullable=True),+ sa.Column("feedback", sa.String(), nullable=True),+ sa.Column("project_id", sa.String(), nullable=True),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["job_id"], ["jobs.id"], ondelete="SET NULL"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"], ondelete="RESTRICT"),+ sa.ForeignKeyConstraint(["provider_id"], ["providers.id"], ondelete="RESTRICT"),+ )++ # Note: Foreign key constraint for block.current_history_entry_id -> block_history.id+ # would need to be added here, but SQLite doesn't support ALTER TABLE ADD CONSTRAINT+ # This will be handled by the ORM at runtime++ # Add missing columns to existing tables++ # All missing columns have been added to the table definitions above++ # step_id was already added in the messages table creation above+ # op.add_column('messages', sa.Column('step_id', sa.String(), nullable=True))+ # op.create_foreign_key('fk_messages_step_id', 'messages', 'steps', ['step_id'], ['id'], ondelete='SET NULL')++ # Add index to source_passages for file_id+ op.create_index("source_passages_file_id_idx", "source_passages", ["file_id"])++ # Unique constraint for sources was added during table creation above++ # Create remaining association tables++ # Identities agents table+ op.create_table(+ "identities_agents",+ sa.Column("identity_id", sa.String(), nullable=False),+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["identity_id"], ["identities.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("identity_id", "agent_id"),+ )++ # Identities blocks table+ op.create_table(+ "identities_blocks",+ sa.Column("identity_id", sa.String(), nullable=False),+ sa.Column("block_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["identity_id"], ["identities.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["block_id"], ["block.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("identity_id", "block_id"),+ )++ # Files agents table+ op.create_table(+ "files_agents",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("file_id", sa.String(), nullable=False),+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.Column("source_id", sa.String(), nullable=False),+ sa.Column("is_open", sa.Boolean(), nullable=False),+ sa.Column("visible_content", sa.Text(), nullable=True),+ sa.Column("last_accessed_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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_name", sa.String(), nullable=False),+ sa.PrimaryKeyConstraint("id", "file_id", "agent_id"),+ sa.ForeignKeyConstraint(["file_id"], ["files.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["source_id"], ["sources.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.UniqueConstraint("file_id", "agent_id", name="uq_file_agent"),+ sa.UniqueConstraint("agent_id", "file_name", name="uq_agent_filename"),+ )+ op.create_index("ix_agent_filename", "files_agents", ["agent_id", "file_name"])+ op.create_index("ix_file_agent", "files_agents", ["file_id", "agent_id"])++ # Groups agents table+ op.create_table(+ "groups_agents",+ sa.Column("group_id", sa.String(), nullable=False),+ sa.Column("agent_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["group_id"], ["groups.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("group_id", "agent_id"),+ )++ # Groups blocks table+ op.create_table(+ "groups_blocks",+ sa.Column("group_id", sa.String(), nullable=False),+ sa.Column("block_id", sa.String(), nullable=False),+ sa.ForeignKeyConstraint(["group_id"], ["groups.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["block_id"], ["block.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("group_id", "block_id"),+ )++ # LLM batch job table+ op.create_table(+ "llm_batch_job",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("status", sa.String(), nullable=False),+ sa.Column("llm_provider", sa.String(), nullable=False),+ sa.Column("create_batch_response", sa.JSON(), nullable=False),+ sa.Column("latest_polling_response", sa.JSON(), nullable=True),+ sa.Column("last_polled_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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("letta_batch_job_id", sa.String(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["letta_batch_job_id"], ["jobs.id"], ondelete="CASCADE"),+ )+ op.create_index("ix_llm_batch_job_created_at", "llm_batch_job", ["created_at"])+ op.create_index("ix_llm_batch_job_status", "llm_batch_job", ["status"])++ # LLM batch items table+ op.create_table(+ "llm_batch_items",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("llm_config", sa.JSON(), nullable=False),+ sa.Column("request_status", sa.String(), nullable=False),+ sa.Column("step_status", sa.String(), nullable=False),+ sa.Column("step_state", sa.JSON(), nullable=False),+ sa.Column("batch_request_result", sa.JSON(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.Column("llm_batch_id", sa.String(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ sa.ForeignKeyConstraint(["agent_id"], ["agents.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["llm_batch_id"], ["llm_batch_job.id"], ondelete="CASCADE"),+ )+ op.create_index("ix_llm_batch_items_agent_id", "llm_batch_items", ["agent_id"])+ op.create_index("ix_llm_batch_items_llm_batch_id", "llm_batch_items", ["llm_batch_id"])+ op.create_index("ix_llm_batch_items_status", "llm_batch_items", ["request_status"])++ # Job messages table+ op.create_table(+ "job_messages",+ sa.Column("id", sa.Integer(), primary_key=True),+ sa.Column("job_id", sa.String(), nullable=False),+ sa.Column("message_id", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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(["job_id"], ["jobs.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),+ sa.UniqueConstraint("job_id", "message_id", name="unique_job_message"),+ )++ # File contents table+ op.create_table(+ "file_contents",+ sa.Column("file_id", sa.String(), nullable=False),+ sa.Column("text", sa.Text(), nullable=False),+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("file_id", "id"),+ sa.ForeignKeyConstraint(["file_id"], ["files.id"], ondelete="CASCADE"),+ sa.UniqueConstraint("file_id", name="uq_file_contents_file_id"),+ )++ # Provider traces table+ op.create_table(+ "provider_traces",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("request_json", sa.JSON(), nullable=False),+ sa.Column("response_json", sa.JSON(), nullable=False),+ sa.Column("step_id", sa.String(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=True),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("(CURRENT_TIMESTAMP)"), 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.PrimaryKeyConstraint("id"),+ sa.ForeignKeyConstraint(["organization_id"], ["organizations.id"]),+ )+ op.create_index("ix_step_id", "provider_traces", ["step_id"])++ # Complete the SQLite schema alignment by adding any remaining missing elements+ try:+ # Unique constraints for files_agents are already created with correct names in table definition above++ # Foreign key for files_agents.source_id is already created in table definition above+ # Foreign key for messages.step_id is already created in table definition above+ pass++ except Exception:+ # Some operations may fail if the column/constraint already exists+ # This is expected in some cases and we can continue+ pass++ # Note: The remaining alembic check differences are expected for SQLite:+ # 1. Type differences (BLOB vs CommonVector) - Expected and handled by ORM+ # 2. Foreign key constraint differences - SQLite handles these at runtime+ # 3. Index differences - SQLite doesn't support all PostgreSQL index features+ # 4. Some constraint naming differences - Cosmetic differences+ #+ # These differences do not affect functionality as the ORM handles the abstraction+ # between SQLite and PostgreSQL appropriately.+++def downgrade() -> None:+ # Only run this migration for SQLite+ if settings.letta_pg_uri_no_default:+ return++ # SQLite downgrade is not supported+ raise NotImplementedError("SQLite downgrade is not supported. Use a fresh database instead.")diff --git a/alembic/versions/2cceb07c2384_add_content_parts_to_message.py b/alembic/versions/2cceb07c2384_add_content_parts_to_message.pyindex 1914418c5..c5e704c6f 100644--- a/alembic/versions/2cceb07c2384_add_content_parts_to_message.py+++ b/alembic/versions/2cceb07c2384_add_content_parts_to_message.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom alembic import opfrom letta.orm.custom_columns import MessageContentColumn+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "2cceb07c2384"@@ -21,12 +22,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("messages", sa.Column("content", MessageContentColumn(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("messages", "content")# ### end Alembic commands ###diff --git a/alembic/versions/2f4ede6ae33b_add_otid_and_tool_return_to_message.py b/alembic/versions/2f4ede6ae33b_add_otid_and_tool_return_to_message.pyindex 90ae0b0e9..3e43ad10a 100644--- a/alembic/versions/2f4ede6ae33b_add_otid_and_tool_return_to_message.py+++ b/alembic/versions/2f4ede6ae33b_add_otid_and_tool_return_to_message.py@@ -12,6 +12,7 @@ import sqlalchemy as saimport letta.ormfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "2f4ede6ae33b"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("messages", sa.Column("otid", sa.String(), nullable=True))op.add_column("messages", sa.Column("tool_returns", letta.orm.custom_columns.ToolReturnColumn(), nullable=True))@@ -28,6 +33,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("messages", "tool_returns")op.drop_column("messages", "otid")diff --git a/alembic/versions/341068089f14_add_preserve_on_migration_to_block.py b/alembic/versions/341068089f14_add_preserve_on_migration_to_block.pyindex c36d9b00b..2a7116a60 100644--- a/alembic/versions/341068089f14_add_preserve_on_migration_to_block.py+++ b/alembic/versions/341068089f14_add_preserve_on_migration_to_block.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "341068089f14"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("block", sa.Column("preserve_on_migration", sa.Boolean(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("block", "preserve_on_migration")# ### end Alembic commands ###diff --git a/alembic/versions/348214cbc081_add_org_agent_id_indices.py b/alembic/versions/348214cbc081_add_org_agent_id_indices.pyindex 9bf7575b7..7956115cd 100644--- a/alembic/versions/348214cbc081_add_org_agent_id_indices.py+++ b/alembic/versions/348214cbc081_add_org_agent_id_indices.py@@ -9,6 +9,7 @@ Create Date: 2025-05-28 22:43:18.509397from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "348214cbc081"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_index("ix_agent_passages_org_agent", "agent_passages", ["organization_id", "agent_id"], unique=False)op.create_index("ix_messages_org_agent", "messages", ["organization_id", "agent_id"], unique=False)@@ -25,6 +30,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_messages_org_agent", table_name="messages")op.drop_index("ix_agent_passages_org_agent", table_name="agent_passages")diff --git a/alembic/versions/373dabcba6cf_add_byok_fields_and_unique_constraint.py b/alembic/versions/373dabcba6cf_add_byok_fields_and_unique_constraint.pyindex 3b94ceddb..6dac8e64f 100644--- a/alembic/versions/373dabcba6cf_add_byok_fields_and_unique_constraint.py+++ b/alembic/versions/373dabcba6cf_add_byok_fields_and_unique_constraint.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "373dabcba6cf"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("providers", sa.Column("provider_type", sa.String(), nullable=True))op.add_column("providers", sa.Column("base_url", sa.String(), nullable=True))@@ -28,6 +33,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("unique_name_organization_id", "providers", type_="unique")op.drop_column("providers", "base_url")diff --git a/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.py b/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.pyindex 4f9b746d5..85a334612 100644--- a/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.py+++ b/alembic/versions/3c683a662c82_migrate_jobs_to_the_orm.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "3c683a662c82"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("jobs", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))op.add_column("jobs", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))@@ -34,6 +39,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint(None, "jobs", type_="foreignkey")op.alter_column("jobs", "user_id", existing_type=sa.VARCHAR(), nullable=True)diff --git a/alembic/versions/400501b04bf0_add_per_agent_environment_variables.py b/alembic/versions/400501b04bf0_add_per_agent_environment_variables.pyindex 584e1e4c8..1d42155f8 100644--- a/alembic/versions/400501b04bf0_add_per_agent_environment_variables.py+++ b/alembic/versions/400501b04bf0_add_per_agent_environment_variables.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "400501b04bf0"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("agent_environment_variables",@@ -46,6 +51,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("agent_environment_variables")# ### end Alembic commands ###diff --git a/alembic/versions/416b9d2db10b_repurpose_jobusagestatistics_for_new_.py b/alembic/versions/416b9d2db10b_repurpose_jobusagestatistics_for_new_.pyindex 332fdb3f7..1f296a7cf 100644--- a/alembic/versions/416b9d2db10b_repurpose_jobusagestatistics_for_new_.py+++ b/alembic/versions/416b9d2db10b_repurpose_jobusagestatistics_for_new_.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "416b9d2db10b"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! #### Rename the tableop.rename_table("job_usage_statistics", "steps")@@ -74,6 +79,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! #### Remove step_id from messages first to avoid foreign key conflictsop.drop_constraint("fk_messages_step_id", "messages", type_="foreignkey")diff --git a/alembic/versions/46699adc71a7_add_unique_constraint_to_source_names_.py b/alembic/versions/46699adc71a7_add_unique_constraint_to_source_names_.pyindex d61cbc6fc..3578932de 100644--- a/alembic/versions/46699adc71a7_add_unique_constraint_to_source_names_.py+++ b/alembic/versions/46699adc71a7_add_unique_constraint_to_source_names_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "46699adc71a7"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("files", sa.Column("original_file_name", sa.String(), nullable=True))@@ -62,6 +67,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("uq_source_name_organization", "sources", type_="unique")op.drop_column("files", "original_file_name")diff --git a/alembic/versions/47d2277e530d_add_total_chunks_and_chunks_embedded_to_.py b/alembic/versions/47d2277e530d_add_total_chunks_and_chunks_embedded_to_.pyindex 194d2acf5..f3a40d257 100644--- a/alembic/versions/47d2277e530d_add_total_chunks_and_chunks_embedded_to_.py+++ b/alembic/versions/47d2277e530d_add_total_chunks_and_chunks_embedded_to_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "47d2277e530d"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("files", sa.Column("total_chunks", sa.Integer(), nullable=True))op.add_column("files", sa.Column("chunks_embedded", sa.Integer(), nullable=True))@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("files", "chunks_embedded")op.drop_column("files", "total_chunks")diff --git a/alembic/versions/495f3f474131_write_source_id_directly_to_files_agents.py b/alembic/versions/495f3f474131_write_source_id_directly_to_files_agents.pyindex 9319e99c4..bb5e9dd96 100644--- a/alembic/versions/495f3f474131_write_source_id_directly_to_files_agents.py+++ b/alembic/versions/495f3f474131_write_source_id_directly_to_files_agents.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "495f3f474131"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! #### Step 1: Add the column as nullable firstop.add_column("files_agents", sa.Column("source_id", sa.String(), nullable=True))@@ -46,6 +51,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint(None, "files_agents", type_="foreignkey")op.drop_column("files_agents", "source_id")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..0bd56ebe4 100644--- a/alembic/versions/4e88e702f85e_drop_api_tokens_table_in_oss.py+++ b/alembic/versions/4e88e702f85e_drop_api_tokens_table_in_oss.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "4e88e702f85e"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("tokens_idx_key", table_name="tokens")op.drop_index("tokens_idx_user", table_name="tokens")@@ -28,6 +33,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("tokens",diff --git a/alembic/versions/51999513bcf1_steps_feedback_field.py b/alembic/versions/51999513bcf1_steps_feedback_field.pyindex d48afadb4..d20f248d0 100644--- a/alembic/versions/51999513bcf1_steps_feedback_field.py+++ b/alembic/versions/51999513bcf1_steps_feedback_field.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "51999513bcf1"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("steps", sa.Column("feedback", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("steps", "feedback")# ### end Alembic commands ###diff --git a/alembic/versions/549eff097c71_update_identities_unique_constraint_and_.py b/alembic/versions/549eff097c71_update_identities_unique_constraint_and_.pyindex 97a725435..45073c792 100644--- a/alembic/versions/549eff097c71_update_identities_unique_constraint_and_.py+++ b/alembic/versions/549eff097c71_update_identities_unique_constraint_and_.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "549eff097c71"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! #### Update unique constraint on identities tableop.drop_constraint("unique_identifier_pid_org_id", "identities", type_="unique")@@ -62,6 +67,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! #### Add back the old columns to agentsop.add_column("agents", sa.Column("identity_id", sa.String(), nullable=True))diff --git a/alembic/versions/54dec07619c4_divide_passage_table_into_.py b/alembic/versions/54dec07619c4_divide_passage_table_into_.pyindex e164a997b..6dcc0d1b6 100644--- a/alembic/versions/54dec07619c4_divide_passage_table_into_.py+++ b/alembic/versions/54dec07619c4_divide_passage_table_into_.py@@ -14,6 +14,7 @@ from sqlalchemy.dialects import postgresqlfrom alembic import opfrom letta.orm.custom_columns import EmbeddingConfigColumn+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "54dec07619c4"@@ -23,6 +24,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("agent_passages",@@ -79,6 +84,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### 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"])diff --git a/alembic/versions/54f2311edb62_add_args_schema_to_tools.py b/alembic/versions/54f2311edb62_add_args_schema_to_tools.pyindex 1b5f332e6..163a4e887 100644--- a/alembic/versions/54f2311edb62_add_args_schema_to_tools.py+++ b/alembic/versions/54f2311edb62_add_args_schema_to_tools.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "54f2311edb62"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("tools", sa.Column("args_json_schema", sa.JSON(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("tools", "args_json_schema")# ### end Alembic commands ###diff --git a/alembic/versions/56254216524f_add_custom_headers_to_mcp_server.py b/alembic/versions/56254216524f_add_custom_headers_to_mcp_server.pyindex 62331ccba..80c57532f 100644--- a/alembic/versions/56254216524f_add_custom_headers_to_mcp_server.py+++ b/alembic/versions/56254216524f_add_custom_headers_to_mcp_server.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "56254216524f"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("mcp_server", sa.Column("custom_headers", sa.JSON(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("mcp_server", "custom_headers")# ### end Alembic commands ###diff --git a/alembic/versions/5987401b40ae_refactor_agent_memory.py b/alembic/versions/5987401b40ae_refactor_agent_memory.pyindex 889e9425b..741644e2f 100644--- a/alembic/versions/5987401b40ae_refactor_agent_memory.py+++ b/alembic/versions/5987401b40ae_refactor_agent_memory.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "5987401b40ae"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("agents", "tools", new_column_name="tool_names")op.drop_column("agents", "memory")@@ -28,6 +33,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("agents", "tool_names", new_column_name="tools")op.add_column("agents", sa.Column("memory", postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))diff --git a/alembic/versions/60ed28ee7138_add_project_id_to_step_model.py b/alembic/versions/60ed28ee7138_add_project_id_to_step_model.pyindex a6e234445..aa0817d83 100644--- a/alembic/versions/60ed28ee7138_add_project_id_to_step_model.py+++ b/alembic/versions/60ed28ee7138_add_project_id_to_step_model.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "60ed28ee7138"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("steps", sa.Column("project_id", sa.String(), nullable=True))op.execute(@@ -36,6 +41,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("steps", "project_id")# ### end Alembic commands ###diff --git a/alembic/versions/614c4e53b66e_add_unique_constraint_to_file_id_and_.py b/alembic/versions/614c4e53b66e_add_unique_constraint_to_file_id_and_.pyindex 9d726a351..8d8813d14 100644--- a/alembic/versions/614c4e53b66e_add_unique_constraint_to_file_id_and_.py+++ b/alembic/versions/614c4e53b66e_add_unique_constraint_to_file_id_and_.py@@ -9,6 +9,7 @@ Create Date: 2025-06-02 17:03:58.879839from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "614c4e53b66e"@@ -18,12 +19,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_unique_constraint("uq_files_agents_file_agent", "files_agents", ["file_id", "agent_id"])# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("uq_files_agents_file_agent", "files_agents", type_="unique")# ### end Alembic commands ###diff --git a/alembic/versions/61ee53ec45a5_add_index_on_source_passages_for_files.py b/alembic/versions/61ee53ec45a5_add_index_on_source_passages_for_files.pyindex 29200f476..a9ae8a397 100644--- a/alembic/versions/61ee53ec45a5_add_index_on_source_passages_for_files.py+++ b/alembic/versions/61ee53ec45a5_add_index_on_source_passages_for_files.py@@ -9,6 +9,7 @@ Create Date: 2025-06-20 11:10:02.744914from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "61ee53ec45a5"@@ -18,12 +19,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_index("source_passages_file_id_idx", "source_passages", ["file_id"], unique=False)# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("source_passages_file_id_idx", table_name="source_passages")# ### end Alembic commands ###diff --git a/alembic/versions/6c53224a7a58_add_provider_category_to_steps.py b/alembic/versions/6c53224a7a58_add_provider_category_to_steps.pyindex 891f427f4..bf06a6c98 100644--- a/alembic/versions/6c53224a7a58_add_provider_category_to_steps.py+++ b/alembic/versions/6c53224a7a58_add_provider_category_to_steps.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "6c53224a7a58"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("steps", sa.Column("provider_category", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("steps", "provider_category")# ### end Alembic commands ###diff --git a/alembic/versions/6fbe9cace832_adding_indexes_to_models.py b/alembic/versions/6fbe9cace832_adding_indexes_to_models.pyindex 6331fed76..5c01f445a 100644--- a/alembic/versions/6fbe9cace832_adding_indexes_to_models.py+++ b/alembic/versions/6fbe9cace832_adding_indexes_to_models.py@@ -9,6 +9,7 @@ Create Date: 2025-01-23 11:02:59.534372from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "6fbe9cace832"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_index("agent_passages_created_at_id_idx", "agent_passages", ["created_at", "id"], unique=False)op.create_index("ix_agents_created_at", "agents", ["created_at", "id"], unique=False)@@ -31,6 +36,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_tools_created_at_name", table_name="tools")op.drop_index("source_created_at_id_idx", table_name="sources")diff --git a/alembic/versions/6fe79c0525f2_enable_sleeptime_agent_fields.py b/alembic/versions/6fe79c0525f2_enable_sleeptime_agent_fields.pyindex 5cff137ef..8d6cda1dc 100644--- a/alembic/versions/6fe79c0525f2_enable_sleeptime_agent_fields.py+++ b/alembic/versions/6fe79c0525f2_enable_sleeptime_agent_fields.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "6fe79c0525f2"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("agents", sa.Column("enable_sleeptime", sa.Boolean(), nullable=True))op.alter_column("groups", "background_agents_interval", new_column_name="background_agents_frequency")@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("groups", "background_agents_frequency", new_column_name="background_agents_interval")op.drop_column("agents", "enable_sleeptime")diff --git a/alembic/versions/74f2ede29317_add_background_group_support.py b/alembic/versions/74f2ede29317_add_background_group_support.pyindex a7657ec05..3bc98636f 100644--- a/alembic/versions/74f2ede29317_add_background_group_support.py+++ b/alembic/versions/74f2ede29317_add_background_group_support.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "74f2ede29317"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("groups", sa.Column("background_agents_interval", sa.Integer(), nullable=True))op.add_column("groups", sa.Column("turns_counter", sa.Integer(), nullable=True))@@ -36,6 +41,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("groups_blocks")op.drop_column("groups", "last_processed_message_id")diff --git a/alembic/versions/7778731d15e2_added_jobusagestatistics_table.py b/alembic/versions/7778731d15e2_added_jobusagestatistics_table.pyindex 92c3302d2..66a306822 100644--- a/alembic/versions/7778731d15e2_added_jobusagestatistics_table.py+++ b/alembic/versions/7778731d15e2_added_jobusagestatistics_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "7778731d15e2"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Create job_usage_statistics tableop.create_table("job_usage_statistics",@@ -45,6 +50,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Drop indexesop.drop_index("ix_job_usage_statistics_created_at", "job_usage_statistics")op.drop_index("ix_job_usage_statistics_job_id", "job_usage_statistics")diff --git a/alembic/versions/77de976590ae_add_groups_for_multi_agent.py b/alembic/versions/77de976590ae_add_groups_for_multi_agent.pyindex fdf446e2a..6180746af 100644--- a/alembic/versions/77de976590ae_add_groups_for_multi_agent.py+++ b/alembic/versions/77de976590ae_add_groups_for_multi_agent.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "77de976590ae"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("groups",@@ -55,6 +60,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("messages", "group_id")op.drop_table("groups_agents")diff --git a/alembic/versions/7980d239ea08_add_stateless_option_for_agentstate.py b/alembic/versions/7980d239ea08_add_stateless_option_for_agentstate.pyindex 9693940d7..0a3a0e69b 100644--- a/alembic/versions/7980d239ea08_add_stateless_option_for_agentstate.py+++ b/alembic/versions/7980d239ea08_add_stateless_option_for_agentstate.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "7980d239ea08"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Add the column with a temporary nullable=True so we can backfillop.add_column("agents", sa.Column("message_buffer_autoclear", sa.Boolean(), nullable=True))@@ -31,6 +36,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("agents", "message_buffer_autoclear")# ### end Alembic commands ###diff --git a/alembic/versions/7b189006c97d_rename_batch_id_to_llm_batch_id_on_llm_.py b/alembic/versions/7b189006c97d_rename_batch_id_to_llm_batch_id_on_llm_.pyindex e75e06387..b9e2b1585 100644--- a/alembic/versions/7b189006c97d_rename_batch_id_to_llm_batch_id_on_llm_.py+++ b/alembic/versions/7b189006c97d_rename_batch_id_to_llm_batch_id_on_llm_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "7b189006c97d"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("llm_batch_items", sa.Column("llm_batch_id", sa.String(), nullable=False))op.drop_index("ix_llm_batch_items_batch_id", table_name="llm_batch_items")@@ -31,6 +36,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("llm_batch_items", sa.Column("batch_id", sa.VARCHAR(), autoincrement=False, nullable=False))op.drop_constraint(None, "llm_batch_items", type_="foreignkey")diff --git a/alembic/versions/7f652fdd3dba_change_jobmessage_unique_constraint_to_.py b/alembic/versions/7f652fdd3dba_change_jobmessage_unique_constraint_to_.pyindex b1be20b11..89c9b05ee 100644--- a/alembic/versions/7f652fdd3dba_change_jobmessage_unique_constraint_to_.py+++ b/alembic/versions/7f652fdd3dba_change_jobmessage_unique_constraint_to_.py@@ -9,6 +9,7 @@ Create Date: 2025-01-13 14:36:13.626344from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "7f652fdd3dba"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Drop the old unique constraintop.drop_constraint("uq_job_messages_message_id", "job_messages", type_="unique")@@ -26,6 +31,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Drop the new composite constraintop.drop_constraint("unique_job_message", "job_messages", type_="unique")diff --git a/alembic/versions/878607e41ca4_add_provider_category.py b/alembic/versions/878607e41ca4_add_provider_category.pyindex fb914c67d..48d0db9ba 100644--- a/alembic/versions/878607e41ca4_add_provider_category.py+++ b/alembic/versions/878607e41ca4_add_provider_category.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "878607e41ca4"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("providers", sa.Column("provider_category", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("providers", "provider_category")# ### end Alembic commands ###diff --git a/alembic/versions/88f9432739a9_add_jobtype_to_job_table.py b/alembic/versions/88f9432739a9_add_jobtype_to_job_table.pyindex 1c0090d96..91301f7ea 100644--- a/alembic/versions/88f9432739a9_add_jobtype_to_job_table.py+++ b/alembic/versions/88f9432739a9_add_jobtype_to_job_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "88f9432739a9"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Add job_type column with default valueop.add_column("jobs", sa.Column("job_type", sa.String(), nullable=True))@@ -31,5 +36,9 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Remove the job_type columnop.drop_column("jobs", "job_type")diff --git a/alembic/versions/8d70372ad130_adding_jobmessages_table.py b/alembic/versions/8d70372ad130_adding_jobmessages_table.pyindex 6df8c8621..2c9c0a5ad 100644--- a/alembic/versions/8d70372ad130_adding_jobmessages_table.py+++ b/alembic/versions/8d70372ad130_adding_jobmessages_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "8d70372ad130"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.create_table("job_messages",sa.Column("id", sa.Integer(), nullable=False),@@ -42,6 +47,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_index("ix_job_messages_created_at", "job_messages")op.drop_index("ix_job_messages_job_id", "job_messages")op.drop_table("job_messages")diff --git a/alembic/versions/90bb156e71df_rename_sleeptime_agent_frequency.py b/alembic/versions/90bb156e71df_rename_sleeptime_agent_frequency.pyindex b80f183e6..43b7f5fca 100644--- a/alembic/versions/90bb156e71df_rename_sleeptime_agent_frequency.py+++ b/alembic/versions/90bb156e71df_rename_sleeptime_agent_frequency.py@@ -9,6 +9,7 @@ Create Date: 2025-04-03 17:20:26.218596from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "90bb156e71df"@@ -18,12 +19,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("groups", "background_agents_frequency", new_column_name="sleeptime_agent_frequency")# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("groups", "sleeptime_agent_frequency", new_column_name="background_agents_frequency")# ### end Alembic commands ###diff --git a/alembic/versions/90fd814d0cda_add_callback_error_field_to_jobs.py b/alembic/versions/90fd814d0cda_add_callback_error_field_to_jobs.pyindex 4f45e7395..dba8736fe 100644--- a/alembic/versions/90fd814d0cda_add_callback_error_field_to_jobs.py+++ b/alembic/versions/90fd814d0cda_add_callback_error_field_to_jobs.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "90fd814d0cda"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("jobs", sa.Column("callback_error", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("jobs", "callback_error")# ### end Alembic commands ###diff --git a/alembic/versions/915b68780108_add_providers_data_to_orm.py b/alembic/versions/915b68780108_add_providers_data_to_orm.pyindex 973b8dbb3..3db4dd6f4 100644--- a/alembic/versions/915b68780108_add_providers_data_to_orm.py+++ b/alembic/versions/915b68780108_add_providers_data_to_orm.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "915b68780108"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("providers",@@ -42,6 +47,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("providers")# ### end Alembic commands ###diff --git a/alembic/versions/9556081ce65b_add_bedrock_creds_to_byok.py b/alembic/versions/9556081ce65b_add_bedrock_creds_to_byok.pyindex 93d5c68f2..77430d9ca 100644--- a/alembic/versions/9556081ce65b_add_bedrock_creds_to_byok.py+++ b/alembic/versions/9556081ce65b_add_bedrock_creds_to_byok.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "9556081ce65b"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("providers", sa.Column("access_key", sa.String(), nullable=True))op.add_column("providers", sa.Column("region", sa.String(), nullable=True))@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("providers", "region")op.drop_column("providers", "access_key")diff --git a/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.py b/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.pyindex 73254e39e..c84730d27 100644--- a/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.py+++ b/alembic/versions/95badb46fdf9_migrate_messages_to_the_orm.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "95badb46fdf9"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("messages", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))op.add_column("messages", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))@@ -48,6 +53,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("messages", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=False))op.drop_constraint(None, "messages", type_="foreignkey")diff --git a/alembic/versions/9758adf8fdd3_add_run_completion_and_duration_to_.py b/alembic/versions/9758adf8fdd3_add_run_completion_and_duration_to_.pyindex 5702c542c..529e40715 100644--- a/alembic/versions/9758adf8fdd3_add_run_completion_and_duration_to_.py+++ b/alembic/versions/9758adf8fdd3_add_run_completion_and_duration_to_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "9758adf8fdd3"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("agents", sa.Column("last_run_completion", sa.DateTime(timezone=True), nullable=True))op.add_column("agents", sa.Column("last_run_duration_ms", sa.Integer(), nullable=True))@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("agents", "last_run_duration_ms")op.drop_column("agents", "last_run_completion")diff --git a/alembic/versions/9792f94e961d_add_file_processing_status_to_.py b/alembic/versions/9792f94e961d_add_file_processing_status_to_.pyindex 340e7990b..52859bfba 100644--- a/alembic/versions/9792f94e961d_add_file_processing_status_to_.py+++ b/alembic/versions/9792f94e961d_add_file_processing_status_to_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "9792f94e961d"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Step 1: Create constraintop.create_unique_constraint("uq_file_contents_file_id", "file_contents", ["file_id"])@@ -40,6 +45,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_files_source_created", table_name="files")op.drop_index("ix_files_processing_status", table_name="files")diff --git a/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.py b/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.pyindex 21f6a3961..82d8073f6 100644--- a/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.py+++ b/alembic/versions/9a505cc7eca9_create_a_baseline_migrations.py@@ -14,6 +14,7 @@ from sqlalchemy.dialects import postgresqlimport letta.ormfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "9a505cc7eca9"@@ -23,6 +24,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.create_table("agent_source_mapping",sa.Column("id", sa.String(), nullable=False),@@ -173,6 +178,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_table("users")op.drop_table("tools")op.drop_index("tokens_idx_user", table_name="tokens")diff --git a/alembic/versions/9ecbdbaa409f_add_table_to_store_mcp_servers.py b/alembic/versions/9ecbdbaa409f_add_table_to_store_mcp_servers.pyindex 8fc4ba9b1..eb2a1487a 100644--- a/alembic/versions/9ecbdbaa409f_add_table_to_store_mcp_servers.py+++ b/alembic/versions/9ecbdbaa409f_add_table_to_store_mcp_servers.py@@ -12,6 +12,7 @@ import sqlalchemy as saimport lettafrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "9ecbdbaa409f"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("mcp_server",@@ -46,6 +51,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("mcp_server")# ### end Alembic commands ###diff --git a/alembic/versions/a113caac453e_add_identities_table.py b/alembic/versions/a113caac453e_add_identities_table.pyindex 7c4d41408..8d83aafd5 100644--- a/alembic/versions/a113caac453e_add_identities_table.py+++ b/alembic/versions/a113caac453e_add_identities_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "a113caac453e"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Create identities tableop.create_table("identities",@@ -58,6 +63,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# First remove the foreign key constraint and column from agentsop.drop_constraint("fk_agents_identity_id", "agents", type_="foreignkey")op.drop_column("agents", "identity_id")diff --git a/alembic/versions/a3047a624130_add_identifier_key_to_agents.py b/alembic/versions/a3047a624130_add_identifier_key_to_agents.pyindex abeaeef59..320eefc82 100644--- a/alembic/versions/a3047a624130_add_identifier_key_to_agents.py+++ b/alembic/versions/a3047a624130_add_identifier_key_to_agents.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "a3047a624130"@@ -20,8 +21,16 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.add_column("agents", sa.Column("identifier_key", sa.String(), nullable=True))def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_column("agents", "identifier_key")diff --git a/alembic/versions/a3c7d62e08ca_add_callback_data_to_jobs_table.py b/alembic/versions/a3c7d62e08ca_add_callback_data_to_jobs_table.pyindex 994160efd..cdc7985f8 100644--- a/alembic/versions/a3c7d62e08ca_add_callback_data_to_jobs_table.py+++ b/alembic/versions/a3c7d62e08ca_add_callback_data_to_jobs_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "a3c7d62e08ca"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("jobs", sa.Column("callback_url", sa.String(), nullable=True))op.add_column("jobs", sa.Column("callback_sent_at", sa.DateTime(), nullable=True))@@ -28,6 +33,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("jobs", "callback_status_code")op.drop_column("jobs", "callback_sent_at")diff --git a/alembic/versions/a66510f83fc2_add_ordered_agent_ids_to_groups.py b/alembic/versions/a66510f83fc2_add_ordered_agent_ids_to_groups.pyindex b769627b3..6d41a3703 100644--- a/alembic/versions/a66510f83fc2_add_ordered_agent_ids_to_groups.py+++ b/alembic/versions/a66510f83fc2_add_ordered_agent_ids_to_groups.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "a66510f83fc2"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("groups", sa.Column("agent_ids", sa.JSON(), nullable=False))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("groups", "agent_ids")# ### end Alembic commands ###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..3e2a4ad88 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@@ -12,6 +12,7 @@ import sqlalchemy as safrom alembic import opfrom letta.constants import FUNCTION_RETURN_CHAR_LIMIT+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "a91994b9752f"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("tools", sa.Column("return_char_limit", sa.Integer(), nullable=True))@@ -34,6 +39,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("tools", "return_char_limit")# ### end Alembic commands ###diff --git a/alembic/versions/b183663c6769_add_trace_id_to_steps_table.py b/alembic/versions/b183663c6769_add_trace_id_to_steps_table.pyindex 5f69f4929..25861a0e5 100644--- a/alembic/versions/b183663c6769_add_trace_id_to_steps_table.py+++ b/alembic/versions/b183663c6769_add_trace_id_to_steps_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "b183663c6769"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("steps", sa.Column("trace_id", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("steps", "trace_id")# ### end Alembic commands ###diff --git a/alembic/versions/b6d7ca024aa9_add_agents_tags_table.py b/alembic/versions/b6d7ca024aa9_add_agents_tags_table.pyindex 2aec8a09f..c542994bf 100644--- a/alembic/versions/b6d7ca024aa9_add_agents_tags_table.py+++ b/alembic/versions/b6d7ca024aa9_add_agents_tags_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "b6d7ca024aa9"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("agents_tags",@@ -47,6 +52,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("agents_tags")# ### end Alembic commands ###diff --git a/alembic/versions/bdddd421ec41_add_privileged_tools_to_organization.py b/alembic/versions/bdddd421ec41_add_privileged_tools_to_organization.pyindex 2d6191ca1..5fb09eed0 100644--- a/alembic/versions/bdddd421ec41_add_privileged_tools_to_organization.py+++ b/alembic/versions/bdddd421ec41_add_privileged_tools_to_organization.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "bdddd421ec41"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Step 1: Add `privileged_tools` column with nullable=Trueop.add_column("organizations", sa.Column("privileged_tools", sa.Boolean(), nullable=True))@@ -36,4 +41,8 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_column("organizations", "privileged_tools")diff --git a/alembic/versions/bff040379479_add_block_history_tables.py b/alembic/versions/bff040379479_add_block_history_tables.pyindex 80c6cb331..f89797439 100644--- a/alembic/versions/bff040379479_add_block_history_tables.py+++ b/alembic/versions/bff040379479_add_block_history_tables.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "bff040379479"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("block_history",@@ -55,6 +60,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("fk_block_current_history_entry", "block", type_="foreignkey")op.drop_index(op.f("ix_block_current_history_entry_id"), table_name="block")diff --git a/alembic/versions/c0ef3ff26306_add_token_to_mcp_server.py b/alembic/versions/c0ef3ff26306_add_token_to_mcp_server.pyindex 3cf30846e..f11b70b63 100644--- a/alembic/versions/c0ef3ff26306_add_token_to_mcp_server.py+++ b/alembic/versions/c0ef3ff26306_add_token_to_mcp_server.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c0ef3ff26306"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("mcp_server", sa.Column("token", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("mcp_server", "token")# ### end Alembic commands ###diff --git a/alembic/versions/c3b1da3d1157_add_sender_id_to_message.py b/alembic/versions/c3b1da3d1157_add_sender_id_to_message.pyindex bd59a1188..df9454d33 100644--- a/alembic/versions/c3b1da3d1157_add_sender_id_to_message.py+++ b/alembic/versions/c3b1da3d1157_add_sender_id_to_message.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c3b1da3d1157"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("messages", sa.Column("sender_id", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("messages", "sender_id")# ### end Alembic commands ###diff --git a/alembic/versions/c56081a05371_add_buffer_length_min_max_for_voice_.py b/alembic/versions/c56081a05371_add_buffer_length_min_max_for_voice_.pyindex 44f9a87f6..09ba1a884 100644--- a/alembic/versions/c56081a05371_add_buffer_length_min_max_for_voice_.py+++ b/alembic/versions/c56081a05371_add_buffer_length_min_max_for_voice_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c56081a05371"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("groups", sa.Column("max_message_buffer_length", sa.Integer(), nullable=True))op.add_column("groups", sa.Column("min_message_buffer_length", sa.Integer(), nullable=True))@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("groups", "min_message_buffer_length")op.drop_column("groups", "max_message_buffer_length")diff --git a/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.py b/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.pyindex b6d2e6ba8..fdd8fc257 100644--- a/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.py+++ b/alembic/versions/c5d964280dff_add_passages_orm_drop_legacy_passages_.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c5d964280dff"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### 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))@@ -56,6 +61,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### 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")diff --git a/alembic/versions/c7ac45f69849_add_timezone_to_agents_table.py b/alembic/versions/c7ac45f69849_add_timezone_to_agents_table.pyindex 3f11a1022..04b457725 100644--- a/alembic/versions/c7ac45f69849_add_timezone_to_agents_table.py+++ b/alembic/versions/c7ac45f69849_add_timezone_to_agents_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c7ac45f69849"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("agents", sa.Column("timezone", sa.String(), nullable=True, default="UTC"))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("agents", "timezone")# ### end Alembic commands ###diff --git a/alembic/versions/c85a3d07c028_move_files_to_orm.py b/alembic/versions/c85a3d07c028_move_files_to_orm.pyindex b05d79303..c0255a86a 100644--- a/alembic/versions/c85a3d07c028_move_files_to_orm.py+++ b/alembic/versions/c85a3d07c028_move_files_to_orm.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c85a3d07c028"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("files", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))op.add_column("files", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))@@ -44,6 +49,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("files", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=False))op.drop_constraint(None, "files", type_="foreignkey")diff --git a/alembic/versions/c96263433aef_add_file_name_to_source_passages.py b/alembic/versions/c96263433aef_add_file_name_to_source_passages.pyindex 9f24dcfba..18bd52620 100644--- a/alembic/versions/c96263433aef_add_file_name_to_source_passages.py+++ b/alembic/versions/c96263433aef_add_file_name_to_source_passages.py@@ -10,6 +10,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "c96263433aef"@@ -19,6 +20,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Add the new columnop.add_column("source_passages", sa.Column("file_name", sa.String(), nullable=True))@@ -37,4 +42,8 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+op.drop_column("source_passages", "file_name")diff --git a/alembic/versions/cc8dc340836d_add_support_for_request_and_response_.py b/alembic/versions/cc8dc340836d_add_support_for_request_and_response_.pyindex 7ce2c0dcc..36a79dcfc 100644--- a/alembic/versions/cc8dc340836d_add_support_for_request_and_response_.py+++ b/alembic/versions/cc8dc340836d_add_support_for_request_and_response_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "cc8dc340836d"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("provider_traces",@@ -44,6 +49,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_step_id", table_name="provider_traces")op.drop_table("provider_traces")diff --git a/alembic/versions/cce9a6174366_add_stop_reasons_to_steps_and_message_.py b/alembic/versions/cce9a6174366_add_stop_reasons_to_steps_and_message_.pynew file mode 100644index 000000000..14ac1cdd8--- /dev/null+++ b/alembic/versions/cce9a6174366_add_stop_reasons_to_steps_and_message_.py@@ -0,0 +1,42 @@+"""add stop reasons to steps and message error flag++Revision ID: cce9a6174366+Revises: 2c059cad97cc+Create Date: 2025-07-10 13:56:17.383612++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "cce9a6174366"+down_revision: Union[str, None] = "2c059cad97cc"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.add_column("messages", sa.Column("is_err", sa.Boolean(), nullable=True))++ # manually added to handle non-table creation enums+ stopreasontype = sa.Enum(+ "end_turn", "error", "invalid_tool_call", "max_steps", "no_tool_call", "tool_rule", "cancelled", name="stopreasontype"+ )+ stopreasontype.create(op.get_bind())+ op.add_column("steps", sa.Column("stop_reason", stopreasontype, nullable=True))+ # ### end Alembic commands ###+++def downgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.drop_column("steps", "stop_reason")+ op.drop_column("messages", "is_err")++ stopreasontype = sa.Enum(name="stopreasontype")+ stopreasontype.drop(op.get_bind())+ # ### end Alembic commands ###diff --git a/alembic/versions/cda66b6cb0d6_move_sources_to_orm.py b/alembic/versions/cda66b6cb0d6_move_sources_to_orm.pyindex f46bef6b4..7ada943ae 100644--- a/alembic/versions/cda66b6cb0d6_move_sources_to_orm.py+++ b/alembic/versions/cda66b6cb0d6_move_sources_to_orm.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "cda66b6cb0d6"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("sources", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))op.add_column("sources", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))@@ -51,6 +56,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("sources", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=False))op.drop_constraint(None, "sources", type_="foreignkey")diff --git a/alembic/versions/cdb3db091113_remove_unique_name_restriction_on_agents.py b/alembic/versions/cdb3db091113_remove_unique_name_restriction_on_agents.pyindex 839401190..f8713b437 100644--- a/alembic/versions/cdb3db091113_remove_unique_name_restriction_on_agents.py+++ b/alembic/versions/cdb3db091113_remove_unique_name_restriction_on_agents.py@@ -9,6 +9,7 @@ Create Date: 2025-01-10 15:36:08.728539from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "cdb3db091113"@@ -18,12 +19,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("unique_org_agent_name", "agents", type_="unique")# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_unique_constraint("unique_org_agent_name", "agents", ["organization_id", "name"])# ### end Alembic commands ###diff --git a/alembic/versions/cdd4a1c11aee_add_file_name_to_fileagent_association_.py b/alembic/versions/cdd4a1c11aee_add_file_name_to_fileagent_association_.pyindex 164803d50..f808cdcf7 100644--- a/alembic/versions/cdd4a1c11aee_add_file_name_to_fileagent_association_.py+++ b/alembic/versions/cdd4a1c11aee_add_file_name_to_fileagent_association_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "cdd4a1c11aee"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("file_contents",@@ -55,6 +60,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("uq_files_agents_agent_file_name", "files_agents", type_="unique")op.drop_index("ix_files_agents_agent_file_name", table_name="files_agents")diff --git a/alembic/versions/d05669b60ebe_migrate_agents_to_orm.py b/alembic/versions/d05669b60ebe_migrate_agents_to_orm.pyindex d03652c85..5fb1352b7 100644--- a/alembic/versions/d05669b60ebe_migrate_agents_to_orm.py+++ b/alembic/versions/d05669b60ebe_migrate_agents_to_orm.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "d05669b60ebe"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("sources_agents",@@ -96,6 +101,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("tools_agents",diff --git a/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.py b/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.pyindex 83c5f2df4..95c5fbe45 100644--- a/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.py+++ b/alembic/versions/d14ae606614c_move_organizations_users_tools_to_orm.py@@ -13,6 +13,7 @@ from sqlalchemy.dialects import postgresqlimport lettafrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "d14ae606614c"@@ -22,6 +23,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Delete all toolsop.execute("DELETE FROM tools")@@ -60,6 +65,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("users", sa.Column("policies_accepted", sa.BOOLEAN(), autoincrement=False, nullable=False))op.add_column("users", sa.Column("org_id", sa.VARCHAR(), autoincrement=False, nullable=True))diff --git a/alembic/versions/d211df879a5f_add_agent_id_to_steps.py b/alembic/versions/d211df879a5f_add_agent_id_to_steps.pyindex d857fca47..6d5e57ad0 100644--- a/alembic/versions/d211df879a5f_add_agent_id_to_steps.py+++ b/alembic/versions/d211df879a5f_add_agent_id_to_steps.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "d211df879a5f"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("steps", sa.Column("agent_id", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("steps", "agent_id")# ### end Alembic commands ###diff --git a/alembic/versions/d6632deac81d_add_composite_index_to_messages_table.py b/alembic/versions/d6632deac81d_add_composite_index_to_messages_table.pyindex 68ceec88f..2deb10f88 100644--- a/alembic/versions/d6632deac81d_add_composite_index_to_messages_table.py+++ b/alembic/versions/d6632deac81d_add_composite_index_to_messages_table.py@@ -9,6 +9,7 @@ Create Date: 2024-12-18 13:38:56.511701from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "d6632deac81d"@@ -18,12 +19,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_index("ix_messages_agent_created_at", "messages", ["agent_id", "created_at"], unique=False)# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("ix_messages_agent_created_at", table_name="messages")# ### end Alembic commands ###diff --git a/alembic/versions/dd049fbec729_add_index_on_agent_id_for_agent_env_var.py b/alembic/versions/dd049fbec729_add_index_on_agent_id_for_agent_env_var.pyindex e995caeed..fd4e567fa 100644--- a/alembic/versions/dd049fbec729_add_index_on_agent_id_for_agent_env_var.py+++ b/alembic/versions/dd049fbec729_add_index_on_agent_id_for_agent_env_var.py@@ -9,6 +9,7 @@ Create Date: 2025-05-23 17:41:48.235405from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "dd049fbec729"@@ -18,12 +19,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_index("idx_agent_environment_variables_agent_id", "agent_environment_variables", ["agent_id"], unique=False)# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_index("idx_agent_environment_variables_agent_id", table_name="agent_environment_variables")# ### end Alembic commands ###diff --git a/alembic/versions/dfafcf8210ca_add_model_endpoint_to_steps_table.py b/alembic/versions/dfafcf8210ca_add_model_endpoint_to_steps_table.pyindex df3b42789..a4502932d 100644--- a/alembic/versions/dfafcf8210ca_add_model_endpoint_to_steps_table.py+++ b/alembic/versions/dfafcf8210ca_add_model_endpoint_to_steps_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "dfafcf8210ca"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("steps", sa.Column("model_endpoint", sa.String(), nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("steps", "model_endpoint")# ### end Alembic commands ###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..8a8b65660 100644--- a/alembic/versions/e1a625072dbf_tweak_created_at_field_for_messages.py+++ b/alembic/versions/e1a625072dbf_tweak_created_at_field_for_messages.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionfrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "e1a625072dbf"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("messages", "created_at", existing_type=postgresql.TIMESTAMP(timezone=True), nullable=True)# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("messages", "created_at", existing_type=postgresql.TIMESTAMP(timezone=True), nullable=False)# ### end Alembic commands ###diff --git a/alembic/versions/e20573fe9b86_add_tool_types.py b/alembic/versions/e20573fe9b86_add_tool_types.pyindex 2bd64f2f2..deff43689 100644--- a/alembic/versions/e20573fe9b86_add_tool_types.py+++ b/alembic/versions/e20573fe9b86_add_tool_types.py@@ -14,6 +14,7 @@ from sqlalchemy.dialects import postgresqlfrom alembic import opfrom letta.constants import BASE_MEMORY_TOOLS, BASE_TOOLSfrom letta.orm.enums import ToolType+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "e20573fe9b86"@@ -23,6 +24,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Step 1: Add the column as nullable with no defaultop.add_column("tools", sa.Column("tool_type", sa.String(), nullable=True))@@ -64,6 +69,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# Revert the changes made during the upgradeop.alter_column("tools", "json_schema", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False)op.drop_column("tools", "tool_type")diff --git a/alembic/versions/e78b4e82db30_add_cascading_deletes_for_sources_to_.py b/alembic/versions/e78b4e82db30_add_cascading_deletes_for_sources_to_.pyindex dd59f2a04..3afa28b6c 100644--- a/alembic/versions/e78b4e82db30_add_cascading_deletes_for_sources_to_.py+++ b/alembic/versions/e78b4e82db30_add_cascading_deletes_for_sources_to_.py@@ -9,6 +9,7 @@ Create Date: 2024-12-20 16:30:17.095888from typing import Sequence, Unionfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "e78b4e82db30"@@ -18,6 +19,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("sources_agents_agent_id_fkey", "sources_agents", type_="foreignkey")op.drop_constraint("sources_agents_source_id_fkey", "sources_agents", type_="foreignkey")@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint(None, "sources_agents", type_="foreignkey")op.drop_constraint(None, "sources_agents", type_="foreignkey")diff --git a/alembic/versions/e991d2e3b428_add_monotonically_increasing_ids_to_.py b/alembic/versions/e991d2e3b428_add_monotonically_increasing_ids_to_.pyindex 3f028c715..2b2370ef9 100644--- a/alembic/versions/e991d2e3b428_add_monotonically_increasing_ids_to_.py+++ b/alembic/versions/e991d2e3b428_add_monotonically_increasing_ids_to_.py@@ -12,6 +12,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "e991d2e3b428"@@ -38,6 +39,10 @@ def print_flush(message):def upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+"""Adds sequence_id, backfills data, adds constraints and index."""print_flush(f"\n--- Starting upgrade for revision {revision} ---")@@ -118,6 +123,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+"""Reverses the changes made in the upgrade function."""print_flush(f"\n--- Starting downgrade from revision {revision} ---")diff --git a/alembic/versions/f2f78d62005c_add_letta_batch_job_id_to_llm_batch_job.py b/alembic/versions/f2f78d62005c_add_letta_batch_job_id_to_llm_batch_job.pyindex f0eb84540..5309d0faf 100644--- a/alembic/versions/f2f78d62005c_add_letta_batch_job_id_to_llm_batch_job.py+++ b/alembic/versions/f2f78d62005c_add_letta_batch_job_id_to_llm_batch_job.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "f2f78d62005c"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("llm_batch_job", sa.Column("letta_batch_job_id", sa.String(), nullable=False))op.create_foreign_key(None, "llm_batch_job", "jobs", ["letta_batch_job_id"], ["id"], ondelete="CASCADE")@@ -27,6 +32,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint(None, "llm_batch_job", type_="foreignkey")op.drop_column("llm_batch_job", "letta_batch_job_id")diff --git a/alembic/versions/f595e0e8013e_adding_request_config_to_job_table.py b/alembic/versions/f595e0e8013e_adding_request_config_to_job_table.pyindex d53a30a23..ce798112e 100644--- a/alembic/versions/f595e0e8013e_adding_request_config_to_job_table.py+++ b/alembic/versions/f595e0e8013e_adding_request_config_to_job_table.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "f595e0e8013e"@@ -20,12 +21,20 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("jobs", sa.Column("request_config", sa.JSON, nullable=True))# ### end Alembic commands ###def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("jobs", "request_config")# ### end Alembic commands ###diff --git a/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.py b/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.pyindex 9e7fa270c..7e1b0305b 100644--- a/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.py+++ b/alembic/versions/f7507eab4bb9_migrate_blocks_to_orm_model.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "f7507eab4bb9"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("block", sa.Column("is_template", sa.Boolean(), nullable=True))# Populate `is_template` column@@ -58,6 +63,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("block", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=True))op.add_column("block", sa.Column("template", sa.BOOLEAN(), autoincrement=False, nullable=True))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..40d646704 100644--- a/alembic/versions/f81ceea2c08d_create_sandbox_config_and_sandbox_env_.py+++ b/alembic/versions/f81ceea2c08d_create_sandbox_config_and_sandbox_env_.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "f81ceea2c08d"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.create_table("sandbox_configs",@@ -67,6 +72,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_table("sandbox_environment_variables")op.drop_table("sandbox_configs")diff --git a/alembic/versions/f895232c144a_backfill_composio_tools.py b/alembic/versions/f895232c144a_backfill_composio_tools.pyindex a1c08c71e..defc23672 100644--- a/alembic/versions/f895232c144a_backfill_composio_tools.py+++ b/alembic/versions/f895232c144a_backfill_composio_tools.py@@ -10,6 +10,7 @@ from typing import Sequence, Unionfrom alembic import opfrom letta.orm.enums import ToolType+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "f895232c144a"@@ -19,6 +20,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! #### Define the value for EXTERNAL_COMPOSIOexternal_composio_value = ToolType.EXTERNAL_COMPOSIO.value@@ -36,6 +41,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###custom_value = ToolType.CUSTOM.valuediff --git a/alembic/versions/f922ca16e42c_add_project_and_template_id_to_agent.py b/alembic/versions/f922ca16e42c_add_project_and_template_id_to_agent.pyindex e2f6d9ba9..169a6d775 100644--- a/alembic/versions/f922ca16e42c_add_project_and_template_id_to_agent.py+++ b/alembic/versions/f922ca16e42c_add_project_and_template_id_to_agent.py@@ -11,6 +11,7 @@ from typing import Sequence, Unionimport sqlalchemy as safrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "f922ca16e42c"@@ -20,6 +21,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.add_column("agents", sa.Column("project_id", sa.String(), nullable=True))op.add_column("agents", sa.Column("template_id", sa.String(), nullable=True))@@ -28,6 +33,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_column("agents", "base_template_id")op.drop_column("agents", "template_id")diff --git a/alembic/versions/fdcdafdb11cf_identity_properties_jsonb_to_json.py b/alembic/versions/fdcdafdb11cf_identity_properties_jsonb_to_json.pyindex c249f8807..b553ecdcb 100644--- a/alembic/versions/fdcdafdb11cf_identity_properties_jsonb_to_json.py+++ b/alembic/versions/fdcdafdb11cf_identity_properties_jsonb_to_json.py@@ -12,6 +12,7 @@ import sqlalchemy as safrom sqlalchemy.dialects import postgresqlfrom alembic import op+from letta.settings import settings# revision identifiers, used by Alembic.revision: str = "fdcdafdb11cf"@@ -21,6 +22,10 @@ depends_on: Union[str, Sequence[str], None] = Nonedef upgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.alter_column("identities",@@ -41,6 +46,10 @@ def upgrade() -> None:def downgrade() -> None:+ # Skip this migration for SQLite+ if not settings.letta_pg_uri_no_default:+ return+# ### commands auto generated by Alembic - please adjust! ###op.drop_constraint("unique_identifier_key_project_id_organization_id", "identities", type_="unique")op.create_unique_constraint(diff --git a/letta/__init__.py b/letta/__init__.pyindex 20087c448..c78496a64 100644--- a/letta/__init__.py+++ b/letta/__init__.py@@ -5,7 +5,7 @@ try:__version__ = version("letta")except PackageNotFoundError:# Fallback for development installations- __version__ = "0.8.15"+ __version__ = "0.8.16"if os.environ.get("LETTA_VERSION"):__version__ = os.environ["LETTA_VERSION"]diff --git a/letta/agent.py b/letta/agent.pyindex 87b083c5e..c68a08914 100644--- a/letta/agent.py+++ b/letta/agent.py@@ -1304,12 +1304,11 @@ class Agent(BaseAgent):async def get_context_window_from_tiktoken_async(self) -> ContextWindowOverview:"""Get the context window of the agent"""# Grab the in-context messages- # conversion of messages to OpenAI dict format, which is passed to the token counter- (in_context_messages, passage_manager_size, message_manager_size) = await asyncio.gather(- self.message_manager.get_messages_by_ids_async(message_ids=self.agent_state.message_ids, actor=self.user),- self.passage_manager.agent_passage_size_async(actor=self.user, agent_id=self.agent_state.id),- self.message_manager.size_async(actor=self.user, agent_id=self.agent_state.id),+ in_context_messages = await self.message_manager.get_messages_by_ids_async(+ message_ids=self.agent_state.message_ids, actor=self.user)++ # conversion of messages to OpenAI dict format, which is passed to the token counterin_context_messages_openai = [m.to_openai_dict() for m in in_context_messages]# Extract system, memory and external summary@@ -1396,6 +1395,15 @@ class Agent(BaseAgent):)assert isinstance(num_tokens_used_total, int)+ passage_manager_size = await self.passage_manager.agent_passage_size_async(+ agent_id=self.agent_state.id,+ actor=self.user,+ )+ message_manager_size = await self.message_manager.size_async(+ agent_id=self.agent_state.id,+ actor=self.user,+ )+return ContextWindowOverview(# context window breakdown (in messages)num_messages=len(in_context_messages),@@ -1426,12 +1434,11 @@ class Agent(BaseAgent):model = self.agent_state.llm_config.model if self.agent_state.llm_config.model_endpoint_type == "anthropic" else None# Grab the in-context messages- # conversion of messages to anthropic dict format, which is passed to the token counter- (in_context_messages, passage_manager_size, message_manager_size) = await asyncio.gather(- self.message_manager.get_messages_by_ids_async(message_ids=self.agent_state.message_ids, actor=self.user),- self.passage_manager.agent_passage_size_async(actor=self.user, agent_id=self.agent_state.id),- self.message_manager.size_async(actor=self.user, agent_id=self.agent_state.id),+ in_context_messages = await self.message_manager.get_messages_by_ids_async(+ message_ids=self.agent_state.message_ids, actor=self.user)++ # conversion of messages to anthropic dict format, which is passed to the token counterin_context_messages_anthropic = [m.to_anthropic_dict() for m in in_context_messages]# Extract system, memory and external summary@@ -1546,6 +1553,15 @@ class Agent(BaseAgent):)assert isinstance(num_tokens_used_total, int)+ passage_manager_size = await self.passage_manager.agent_passage_size_async(+ agent_id=self.agent_state.id,+ actor=self.user,+ )+ message_manager_size = await self.message_manager.size_async(+ agent_id=self.agent_state.id,+ actor=self.user,+ )+return ContextWindowOverview(# context window breakdown (in messages)num_messages=len(in_context_messages),@@ -1625,7 +1641,7 @@ class Agent(BaseAgent):# Get the MCPClient from the server's handle# TODO these don't get raised properlyif not self.mcp_clients:- raise ValueError(f"No MCP client available to use")+ raise ValueError("No MCP client available to use")if server_name not in self.mcp_clients:raise ValueError(f"Unknown MCP server name: {server_name}")mcp_client = self.mcp_clients[server_name]diff --git a/letta/agents/helpers.py b/letta/agents/helpers.pyindex b49303e6f..422574363 100644--- a/letta/agents/helpers.py+++ b/letta/agents/helpers.py@@ -235,5 +235,5 @@ def _pop_heartbeat(tool_args: dict) -> bool:def _build_rule_violation_result(tool_name: str, valid: list[str], solver: ToolRulesSolver) -> ToolExecutionResult:hint_lines = solver.guess_rule_violation(tool_name)hint_txt = ("\n** Hint: Possible rules that were violated:\n" + "\n".join(f"\t- {h}" for h in hint_lines)) if hint_lines else ""- msg = f"[ToolConstraintError] Cannot call {tool_name}, " f"valid tools include: {valid}.{hint_txt}"+ msg = f"[ToolConstraintError] Cannot call {tool_name}, valid tools include: {valid}.{hint_txt}"return ToolExecutionResult(status="error", func_return=msg)diff --git a/letta/agents/letta_agent.py b/letta/agents/letta_agent.pyindex 7ab25738a..3c7960bce 100644--- a/letta/agents/letta_agent.py+++ b/letta/agents/letta_agent.py@@ -1,4 +1,3 @@-import asyncioimport jsonimport uuidfrom collections.abc import AsyncGenerator@@ -44,6 +43,7 @@ from letta.schemas.llm_config import LLMConfigfrom letta.schemas.message import Message, MessageCreatefrom letta.schemas.openai.chat_completion_response import ToolCall, UsageStatisticsfrom letta.schemas.provider_trace import ProviderTraceCreate+from letta.schemas.step import StepProgressionfrom letta.schemas.tool_execution_result import ToolExecutionResultfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.schemas.user import User@@ -239,100 +239,164 @@ class LettaAgent(BaseAgent):agent_step_span = tracer.start_span("agent_step", start_time=step_start)agent_step_span.set_attributes({"step_id": step_id})- request_data, response_data, current_in_context_messages, new_in_context_messages, valid_tool_names = (- await self._build_and_request_from_llm(- current_in_context_messages,- new_in_context_messages,- agent_state,- llm_client,- tool_rules_solver,- agent_step_span,+ step_progression = StepProgression.START+ should_continue = False+ try:+ request_data, response_data, current_in_context_messages, new_in_context_messages, valid_tool_names = (+ await self._build_and_request_from_llm(+ current_in_context_messages,+ new_in_context_messages,+ agent_state,+ llm_client,+ tool_rules_solver,+ agent_step_span,+ ))- )- in_context_messages = current_in_context_messages + new_in_context_messages-- log_event("agent.stream_no_tokens.llm_response.received") # [3^]-- response = llm_client.convert_response_to_chat_completion(response_data, in_context_messages, agent_state.llm_config)-- # update usage- usage.step_count += 1- usage.completion_tokens += response.usage.completion_tokens- usage.prompt_tokens += response.usage.prompt_tokens- usage.total_tokens += response.usage.total_tokens- MetricRegistry().message_output_tokens.record(- response.usage.completion_tokens, dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model})- )+ in_context_messages = current_in_context_messages + new_in_context_messages- if not response.choices[0].message.tool_calls:- # TODO: make into a real error- raise ValueError("No tool calls found in response, model must make a tool call")- tool_call = response.choices[0].message.tool_calls[0]- if response.choices[0].message.reasoning_content:- reasoning = [- ReasoningContent(- reasoning=response.choices[0].message.reasoning_content,- is_native=True,- signature=response.choices[0].message.reasoning_content_signature,- )- ]- elif response.choices[0].message.omitted_reasoning_content:- reasoning = [OmittedReasoningContent()]- elif response.choices[0].message.content:- reasoning = [TextContent(text=response.choices[0].message.content)] # reasoning placed into content for legacy reasons- else:- self.logger.info("No reasoning content found.")- reasoning = None-- persisted_messages, should_continue, stop_reason = await self._handle_ai_response(- tool_call,- valid_tool_names,- agent_state,- tool_rules_solver,- response.usage,- reasoning_content=reasoning,- step_id=step_id,- initial_messages=initial_messages,- agent_step_span=agent_step_span,- is_final_step=(i == max_steps - 1),- )+ step_progression = StepProgression.RESPONSE_RECEIVED+ log_event("agent.stream_no_tokens.llm_response.received") # [3^]- # TODO (cliandy): handle message contexts with larger refactor and dedupe logic- new_message_idx = len(initial_messages) if initial_messages else 0- self.response_messages.extend(persisted_messages[new_message_idx:])- new_in_context_messages.extend(persisted_messages[new_message_idx:])- initial_messages = None- log_event("agent.stream_no_tokens.llm_response.processed") # [4^]+ response = llm_client.convert_response_to_chat_completion(response_data, in_context_messages, agent_state.llm_config)- # log step time- now = get_utc_timestamp_ns()- step_ns = now - step_start- agent_step_span.add_event(name="step_ms", attributes={"duration_ms": ns_to_ms(step_ns)})- agent_step_span.end()+ # update usage+ usage.step_count += 1+ usage.completion_tokens += response.usage.completion_tokens+ usage.prompt_tokens += response.usage.prompt_tokens+ usage.total_tokens += response.usage.total_tokens+ MetricRegistry().message_output_tokens.record(+ response.usage.completion_tokens, dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model})+ )- # Log LLM Trace- await self.telemetry_manager.create_provider_trace_async(- actor=self.actor,- provider_trace_create=ProviderTraceCreate(- request_json=request_data,- response_json=response_data,+ if not response.choices[0].message.tool_calls:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.no_tool_call.value)+ raise ValueError("No tool calls found in response, model must make a tool call")+ tool_call = response.choices[0].message.tool_calls[0]+ if response.choices[0].message.reasoning_content:+ reasoning = [+ ReasoningContent(+ reasoning=response.choices[0].message.reasoning_content,+ is_native=True,+ signature=response.choices[0].message.reasoning_content_signature,+ )+ ]+ elif response.choices[0].message.omitted_reasoning_content:+ reasoning = [OmittedReasoningContent()]+ elif response.choices[0].message.content:+ reasoning = [TextContent(text=response.choices[0].message.content)] # reasoning placed into content for legacy reasons+ else:+ self.logger.info("No reasoning content found.")+ reasoning = None++ persisted_messages, should_continue, stop_reason = await self._handle_ai_response(+ tool_call,+ valid_tool_names,+ agent_state,+ tool_rules_solver,+ response.usage,+ reasoning_content=reasoning,step_id=step_id,- organization_id=self.actor.organization_id,- ),- )+ initial_messages=initial_messages,+ agent_step_span=agent_step_span,+ is_final_step=(i == max_steps - 1),+ )+ step_progression = StepProgression.STEP_LOGGED++ # TODO (cliandy): handle message contexts with larger refactor and dedupe logic+ new_message_idx = len(initial_messages) if initial_messages else 0+ self.response_messages.extend(persisted_messages[new_message_idx:])+ new_in_context_messages.extend(persisted_messages[new_message_idx:])+ initial_messages = None+ log_event("agent.stream_no_tokens.llm_response.processed") # [4^]++ # log step time+ now = get_utc_timestamp_ns()+ step_ns = now - step_start+ agent_step_span.add_event(name="step_ms", attributes={"duration_ms": ns_to_ms(step_ns)})+ agent_step_span.end()++ # Log LLM Trace+ await self.telemetry_manager.create_provider_trace_async(+ actor=self.actor,+ provider_trace_create=ProviderTraceCreate(+ request_json=request_data,+ response_json=response_data,+ step_id=step_id,+ organization_id=self.actor.organization_id,+ ),+ )+ step_progression = StepProgression.LOGGED_TRACE- # stream step- # TODO: improve TTFT- filter_user_messages = [m for m in persisted_messages if m.role != "user"]- letta_messages = Message.to_letta_messages_from_list(- filter_user_messages, use_assistant_message=use_assistant_message, reverse=False- )+ # stream step+ # TODO: improve TTFT+ filter_user_messages = [m for m in persisted_messages if m.role != "user"]+ letta_messages = Message.to_letta_messages_from_list(+ filter_user_messages, use_assistant_message=use_assistant_message, reverse=False+ )- for message in letta_messages:- if include_return_message_types is None or message.message_type in include_return_message_types:- yield f"data: {message.model_dump_json()}\n\n"+ for message in letta_messages:+ if include_return_message_types is None or message.message_type in include_return_message_types:+ yield f"data: {message.model_dump_json()}\n\n"- MetricRegistry().step_execution_time_ms_histogram.record(get_utc_timestamp_ns() - step_start, get_ctx_attributes())+ MetricRegistry().step_execution_time_ms_histogram.record(get_utc_timestamp_ns() - step_start, get_ctx_attributes())+ step_progression = StepProgression.FINISHED+ except Exception as e:+ # Handle any unexpected errors during step processing+ self.logger.error(f"Error during step processing: {e}")++ # This indicates we failed after we decided to stop stepping, which indicates a bug with our flow.+ if not stop_reason:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)+ elif stop_reason.stop_reason in (StopReasonType.end_turn, StopReasonType.max_steps, StopReasonType.tool_rule):+ self.logger.error("Error occurred during step processing, with valid stop reason: %s", stop_reason.stop_reason)+ elif stop_reason.stop_reason not in (StopReasonType.no_tool_call, StopReasonType.invalid_tool_call):+ raise ValueError(f"Invalid Stop Reason: {stop_reason}")++ # Send error stop reason to client and re-raise+ yield f"data: {stop_reason.model_dump_json()}\n\n", 500+ raise++ # Update step if it needs to be updated+ finally:+ if settings.track_stop_reason:+ self.logger.info("Running final update. Step Progression: %s", step_progression)+ try:+ if step_progression < StepProgression.STEP_LOGGED:+ await self.step_manager.log_step_async(+ actor=self.actor,+ agent_id=agent_state.id,+ provider_name=agent_state.llm_config.model_endpoint_type,+ provider_category=agent_state.llm_config.provider_category or "base",+ model=agent_state.llm_config.model,+ model_endpoint=agent_state.llm_config.model_endpoint,+ context_window_limit=agent_state.llm_config.context_window,+ usage=UsageStatistics(completion_tokens=0, prompt_tokens=0, total_tokens=0),+ provider_id=None,+ job_id=self.current_run_id if self.current_run_id else None,+ step_id=step_id,+ project_id=agent_state.project_id,+ stop_reason=stop_reason,+ )+ if step_progression <= StepProgression.RESPONSE_RECEIVED:+ # TODO (cliandy): persist response if we get it back+ if settings.track_errored_messages:+ for message in initial_messages:+ message.is_err = True+ message.step_id = step_id+ await self.message_manager.create_many_messages_async(initial_messages, actor=self.actor)+ elif step_progression <= StepProgression.LOGGED_TRACE:+ if stop_reason is None:+ self.logger.error("Error in step after logging step")+ stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)+ await self.step_manager.update_step_stop_reason(self.actor, step_id, stop_reason.stop_reason)+ elif step_progression == StepProgression.FINISHED and not should_continue:+ if stop_reason is None:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.end_turn.value)+ await self.step_manager.update_step_stop_reason(self.actor, step_id, stop_reason.stop_reason)+ else:+ self.logger.error("Invalid StepProgression value")+ except Exception as e:+ self.logger.error("Failed to update step: %s", e)if not should_continue:break@@ -397,17 +461,6 @@ class LettaAgent(BaseAgent):stop_reason = Noneusage = LettaUsageStatistics()for i in range(max_steps):- # Check for job cancellation at the start of each step- if await self._check_run_cancellation():- stop_reason = LettaStopReason(stop_reason=StopReasonType.cancelled.value)- logger.info(f"Agent execution cancelled for run {self.current_run_id}")- break-- step_id = generate_step_id()- step_start = get_utc_timestamp_ns()- agent_step_span = tracer.start_span("agent_step", start_time=step_start)- agent_step_span.set_attributes({"step_id": step_id})-# If dry run, build request data and return it without making LLM callif dry_run:request_data, valid_tool_names = await self._create_llm_request_data_async(@@ -418,84 +471,159 @@ class LettaAgent(BaseAgent):)return request_data- request_data, response_data, current_in_context_messages, new_in_context_messages, valid_tool_names = (- await self._build_and_request_from_llm(- current_in_context_messages, new_in_context_messages, agent_state, llm_client, tool_rules_solver, agent_step_span- )- )- in_context_messages = current_in_context_messages + new_in_context_messages-- log_event("agent.step.llm_response.received") # [3^]+ # Check for job cancellation at the start of each step+ if await self._check_run_cancellation():+ stop_reason = LettaStopReason(stop_reason=StopReasonType.cancelled.value)+ logger.info(f"Agent execution cancelled for run {self.current_run_id}")+ break- response = llm_client.convert_response_to_chat_completion(response_data, in_context_messages, agent_state.llm_config)+ step_id = generate_step_id()+ step_start = get_utc_timestamp_ns()+ agent_step_span = tracer.start_span("agent_step", start_time=step_start)+ agent_step_span.set_attributes({"step_id": step_id})- usage.step_count += 1- usage.completion_tokens += response.usage.completion_tokens- usage.prompt_tokens += response.usage.prompt_tokens- usage.total_tokens += response.usage.total_tokens- usage.run_ids = [run_id] if run_id else None- MetricRegistry().message_output_tokens.record(- response.usage.completion_tokens, dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model})- )+ step_progression = StepProgression.START+ should_continue = False- if not response.choices[0].message.tool_calls:- # TODO: make into a real error- raise ValueError("No tool calls found in response, model must make a tool call")- tool_call = response.choices[0].message.tool_calls[0]- if response.choices[0].message.reasoning_content:- reasoning = [- ReasoningContent(- reasoning=response.choices[0].message.reasoning_content,- is_native=True,- signature=response.choices[0].message.reasoning_content_signature,+ try:+ request_data, response_data, current_in_context_messages, new_in_context_messages, valid_tool_names = (+ await self._build_and_request_from_llm(+ current_in_context_messages, new_in_context_messages, agent_state, llm_client, tool_rules_solver, agent_step_span)- ]- elif response.choices[0].message.content:- reasoning = [TextContent(text=response.choices[0].message.content)] # reasoning placed into content for legacy reasons- elif response.choices[0].message.omitted_reasoning_content:- reasoning = [OmittedReasoningContent()]- else:- self.logger.info("No reasoning content found.")- reasoning = None-- persisted_messages, should_continue, stop_reason = await self._handle_ai_response(- tool_call,- valid_tool_names,- agent_state,- tool_rules_solver,- response.usage,- reasoning_content=reasoning,- step_id=step_id,- initial_messages=initial_messages,- agent_step_span=agent_step_span,- is_final_step=(i == max_steps - 1),- run_id=run_id,- )- new_message_idx = len(initial_messages) if initial_messages else 0- self.response_messages.extend(persisted_messages[new_message_idx:])- new_in_context_messages.extend(persisted_messages[new_message_idx:])+ )+ in_context_messages = current_in_context_messages + new_in_context_messages- initial_messages = None- log_event("agent.step.llm_response.processed") # [4^]+ step_progression = StepProgression.RESPONSE_RECEIVED+ log_event("agent.step.llm_response.received") # [3^]- # log step time- now = get_utc_timestamp_ns()- step_ns = now - step_start- agent_step_span.add_event(name="step_ms", attributes={"duration_ms": ns_to_ms(step_ns)})- agent_step_span.end()+ response = llm_client.convert_response_to_chat_completion(response_data, in_context_messages, agent_state.llm_config)- # Log LLM Trace- await self.telemetry_manager.create_provider_trace_async(- actor=self.actor,- provider_trace_create=ProviderTraceCreate(- request_json=request_data,- response_json=response_data,+ usage.step_count += 1+ usage.completion_tokens += response.usage.completion_tokens+ usage.prompt_tokens += response.usage.prompt_tokens+ usage.total_tokens += response.usage.total_tokens+ usage.run_ids = [run_id] if run_id else None+ MetricRegistry().message_output_tokens.record(+ response.usage.completion_tokens, dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model})+ )++ if not response.choices[0].message.tool_calls:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.no_tool_call.value)+ raise ValueError("No tool calls found in response, model must make a tool call")+ tool_call = response.choices[0].message.tool_calls[0]+ if response.choices[0].message.reasoning_content:+ reasoning = [+ ReasoningContent(+ reasoning=response.choices[0].message.reasoning_content,+ is_native=True,+ signature=response.choices[0].message.reasoning_content_signature,+ )+ ]+ elif response.choices[0].message.content:+ reasoning = [TextContent(text=response.choices[0].message.content)] # reasoning placed into content for legacy reasons+ elif response.choices[0].message.omitted_reasoning_content:+ reasoning = [OmittedReasoningContent()]+ else:+ self.logger.info("No reasoning content found.")+ reasoning = None++ persisted_messages, should_continue, stop_reason = await self._handle_ai_response(+ tool_call,+ valid_tool_names,+ agent_state,+ tool_rules_solver,+ response.usage,+ reasoning_content=reasoning,step_id=step_id,- organization_id=self.actor.organization_id,- ),- )+ initial_messages=initial_messages,+ agent_step_span=agent_step_span,+ is_final_step=(i == max_steps - 1),+ run_id=run_id,+ )+ step_progression = StepProgression.STEP_LOGGED++ new_message_idx = len(initial_messages) if initial_messages else 0+ self.response_messages.extend(persisted_messages[new_message_idx:])+ new_in_context_messages.extend(persisted_messages[new_message_idx:])++ initial_messages = None+ log_event("agent.step.llm_response.processed") # [4^]++ # log step time+ now = get_utc_timestamp_ns()+ step_ns = now - step_start+ agent_step_span.add_event(name="step_ms", attributes={"duration_ms": ns_to_ms(step_ns)})+ agent_step_span.end()++ # Log LLM Trace+ await self.telemetry_manager.create_provider_trace_async(+ actor=self.actor,+ provider_trace_create=ProviderTraceCreate(+ request_json=request_data,+ response_json=response_data,+ step_id=step_id,+ organization_id=self.actor.organization_id,+ ),+ )- MetricRegistry().step_execution_time_ms_histogram.record(get_utc_timestamp_ns() - step_start, get_ctx_attributes())+ step_progression = StepProgression.LOGGED_TRACE+ MetricRegistry().step_execution_time_ms_histogram.record(get_utc_timestamp_ns() - step_start, get_ctx_attributes())+ step_progression = StepProgression.FINISHED++ except Exception as e:+ # Handle any unexpected errors during step processing+ self.logger.error(f"Error during step processing: {e}")++ # This indicates we failed after we decided to stop stepping, which indicates a bug with our flow.+ if not stop_reason:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)+ elif stop_reason.stop_reason in (StopReasonType.end_turn, StopReasonType.max_steps, StopReasonType.tool_rule):+ self.logger.error("Error occurred during step processing, with valid stop reason: %s", stop_reason.stop_reason)+ elif stop_reason.stop_reason not in (StopReasonType.no_tool_call, StopReasonType.invalid_tool_call):+ raise ValueError(f"Invalid Stop Reason: {stop_reason}")+ raise++ # Update step if it needs to be updated+ finally:+ if settings.track_stop_reason:+ self.logger.info("Running final update. Step Progression: %s", step_progression)+ try:+ if step_progression < StepProgression.STEP_LOGGED:+ await self.step_manager.log_step_async(+ actor=self.actor,+ agent_id=agent_state.id,+ provider_name=agent_state.llm_config.model_endpoint_type,+ provider_category=agent_state.llm_config.provider_category or "base",+ model=agent_state.llm_config.model,+ model_endpoint=agent_state.llm_config.model_endpoint,+ context_window_limit=agent_state.llm_config.context_window,+ usage=UsageStatistics(completion_tokens=0, prompt_tokens=0, total_tokens=0),+ provider_id=None,+ job_id=self.current_run_id if self.current_run_id else None,+ step_id=step_id,+ project_id=agent_state.project_id,+ stop_reason=stop_reason,+ )+ if step_progression <= StepProgression.RESPONSE_RECEIVED:+ # TODO (cliandy): persist response if we get it back+ if settings.track_errored_messages:+ for message in initial_messages:+ message.is_err = True+ message.step_id = step_id+ await self.message_manager.create_many_messages_async(initial_messages, actor=self.actor)+ elif step_progression <= StepProgression.LOGGED_TRACE:+ if stop_reason is None:+ self.logger.error("Error in step after logging step")+ stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)+ await self.step_manager.update_step_stop_reason(self.actor, step_id, stop_reason.stop_reason)+ elif step_progression == StepProgression.FINISHED and not should_continue:+ if stop_reason is None:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.end_turn.value)+ await self.step_manager.update_step_stop_reason(self.actor, step_id, stop_reason.stop_reason)+ else:+ self.logger.error("Invalid StepProgression value")+ except Exception as e:+ self.logger.error("Failed to update step: %s", e)if not should_continue:break@@ -577,6 +705,7 @@ class LettaAgent(BaseAgent):request_span.set_attributes({f"llm_config.{k}": v for k, v in agent_state.llm_config.model_dump().items() if v is not None})for i in range(max_steps):+ step_id = generate_step_id()# Check for job cancellation at the start of each stepif await self._check_run_cancellation():stop_reason = LettaStopReason(stop_reason=StopReasonType.cancelled.value)@@ -584,163 +713,230 @@ class LettaAgent(BaseAgent):yield f"data: {stop_reason.model_dump_json()}\n\n"break- step_id = generate_step_id()step_start = get_utc_timestamp_ns()agent_step_span = tracer.start_span("agent_step", start_time=step_start)agent_step_span.set_attributes({"step_id": step_id})- (- request_data,- stream,- current_in_context_messages,- new_in_context_messages,- valid_tool_names,- provider_request_start_timestamp_ns,- ) = await self._build_and_request_from_llm_streaming(- first_chunk,- agent_step_span,- request_start_timestamp_ns,- current_in_context_messages,- new_in_context_messages,- agent_state,- llm_client,- tool_rules_solver,- )- log_event("agent.stream.llm_response.received") # [3^]-- # TODO: THIS IS INCREDIBLY UGLY- # TODO: THERE ARE MULTIPLE COPIES OF THE LLM_CONFIG EVERYWHERE THAT ARE GETTING MANIPULATED- if agent_state.llm_config.model_endpoint_type in [ProviderType.anthropic, ProviderType.bedrock]:- interface = AnthropicStreamingInterface(- use_assistant_message=use_assistant_message,- put_inner_thoughts_in_kwarg=agent_state.llm_config.put_inner_thoughts_in_kwargs,- )- elif agent_state.llm_config.model_endpoint_type == ProviderType.openai:- interface = OpenAIStreamingInterface(- use_assistant_message=use_assistant_message,- put_inner_thoughts_in_kwarg=agent_state.llm_config.put_inner_thoughts_in_kwargs,- )- else:- raise ValueError(f"Streaming not supported for {agent_state.llm_config}")-- async for chunk in interface.process(- stream,- ttft_span=request_span,- provider_request_start_timestamp_ns=provider_request_start_timestamp_ns,- ):- # Measure time to first token- if first_chunk and request_span is not None:- now = get_utc_timestamp_ns()- ttft_ns = now - request_start_timestamp_ns- request_span.add_event(name="time_to_first_token_ms", attributes={"ttft_ms": ns_to_ms(ttft_ns)})- metric_attributes = get_ctx_attributes()- metric_attributes["model.name"] = agent_state.llm_config.model- MetricRegistry().ttft_ms_histogram.record(ns_to_ms(ttft_ns), metric_attributes)- first_chunk = False-- if include_return_message_types is None or chunk.message_type in include_return_message_types:- # filter down returned data- yield f"data: {chunk.model_dump_json()}\n\n"-- stream_end_time_ns = get_utc_timestamp_ns()-- # update usage- usage.step_count += 1- usage.completion_tokens += interface.output_tokens- usage.prompt_tokens += interface.input_tokens- usage.total_tokens += interface.input_tokens + interface.output_tokens- MetricRegistry().message_output_tokens.record(- interface.output_tokens, dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model})- )-- # log LLM request time- llm_request_ms = ns_to_ms(stream_end_time_ns - provider_request_start_timestamp_ns)- agent_step_span.add_event(name="llm_request_ms", attributes={"duration_ms": llm_request_ms})- MetricRegistry().llm_execution_time_ms_histogram.record(- llm_request_ms,- dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model}),- )-- # Process resulting stream content+ step_progression = StepProgression.START+ should_continue = Falsetry:- tool_call = interface.get_tool_call_object()- except ValueError as e:- stop_reason = LettaStopReason(stop_reason=StopReasonType.no_tool_call.value)- yield f"data: {stop_reason.model_dump_json()}\n\n"- raise e- except Exception as e:- stop_reason = LettaStopReason(stop_reason=StopReasonType.invalid_tool_call.value)- yield f"data: {stop_reason.model_dump_json()}\n\n"- raise e- reasoning_content = interface.get_reasoning_content()- persisted_messages, should_continue, stop_reason = await self._handle_ai_response(- tool_call,- valid_tool_names,- agent_state,- tool_rules_solver,- UsageStatistics(- completion_tokens=interface.output_tokens,- prompt_tokens=interface.input_tokens,- total_tokens=interface.input_tokens + interface.output_tokens,- ),- reasoning_content=reasoning_content,- pre_computed_assistant_message_id=interface.letta_message_id,- step_id=step_id,- initial_messages=initial_messages,- agent_step_span=agent_step_span,- is_final_step=(i == max_steps - 1),- )- new_message_idx = len(initial_messages) if initial_messages else 0- self.response_messages.extend(persisted_messages[new_message_idx:])- new_in_context_messages.extend(persisted_messages[new_message_idx:])+ (+ request_data,+ stream,+ current_in_context_messages,+ new_in_context_messages,+ valid_tool_names,+ provider_request_start_timestamp_ns,+ ) = await self._build_and_request_from_llm_streaming(+ first_chunk,+ agent_step_span,+ request_start_timestamp_ns,+ current_in_context_messages,+ new_in_context_messages,+ agent_state,+ llm_client,+ tool_rules_solver,+ )- initial_messages = None+ step_progression = StepProgression.STREAM_RECEIVED+ log_event("agent.stream.llm_response.received") # [3^]- # log total step time- now = get_utc_timestamp_ns()- step_ns = now - step_start- agent_step_span.add_event(name="step_ms", attributes={"duration_ms": ns_to_ms(step_ns)})- agent_step_span.end()+ # TODO: THIS IS INCREDIBLY UGLY+ # TODO: THERE ARE MULTIPLE COPIES OF THE LLM_CONFIG EVERYWHERE THAT ARE GETTING MANIPULATED+ if agent_state.llm_config.model_endpoint_type in [ProviderType.anthropic, ProviderType.bedrock]:+ interface = AnthropicStreamingInterface(+ use_assistant_message=use_assistant_message,+ put_inner_thoughts_in_kwarg=agent_state.llm_config.put_inner_thoughts_in_kwargs,+ )+ elif agent_state.llm_config.model_endpoint_type == ProviderType.openai:+ interface = OpenAIStreamingInterface(+ use_assistant_message=use_assistant_message,+ put_inner_thoughts_in_kwarg=agent_state.llm_config.put_inner_thoughts_in_kwargs,+ )+ else:+ raise ValueError(f"Streaming not supported for {agent_state.llm_config}")++ async for chunk in interface.process(+ stream,+ ttft_span=request_span,+ provider_request_start_timestamp_ns=provider_request_start_timestamp_ns,+ ):+ # Measure time to first token+ if first_chunk and request_span is not None:+ now = get_utc_timestamp_ns()+ ttft_ns = now - request_start_timestamp_ns+ request_span.add_event(name="time_to_first_token_ms", attributes={"ttft_ms": ns_to_ms(ttft_ns)})+ metric_attributes = get_ctx_attributes()+ metric_attributes["model.name"] = agent_state.llm_config.model+ MetricRegistry().ttft_ms_histogram.record(ns_to_ms(ttft_ns), metric_attributes)+ first_chunk = False++ if include_return_message_types is None or chunk.message_type in include_return_message_types:+ # filter down returned data+ yield f"data: {chunk.model_dump_json()}\n\n"++ stream_end_time_ns = get_utc_timestamp_ns()++ # update usage+ usage.step_count += 1+ usage.completion_tokens += interface.output_tokens+ usage.prompt_tokens += interface.input_tokens+ usage.total_tokens += interface.input_tokens + interface.output_tokens+ MetricRegistry().message_output_tokens.record(+ interface.output_tokens, dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model})+ )- # TODO (cliandy): the stream POST request span has ended at this point, we should tie this to the stream- # log_event("agent.stream.llm_response.processed") # [4^]+ # log LLM request time+ llm_request_ms = ns_to_ms(stream_end_time_ns - provider_request_start_timestamp_ns)+ agent_step_span.add_event(name="llm_request_ms", attributes={"duration_ms": llm_request_ms})+ MetricRegistry().llm_execution_time_ms_histogram.record(+ llm_request_ms,+ dict(get_ctx_attributes(), **{"model.name": agent_state.llm_config.model}),+ )- # Log LLM Trace- # TODO (cliandy): we are piecing together the streamed response here. Content here does not match the actual response schema.- await self.telemetry_manager.create_provider_trace_async(- actor=self.actor,- provider_trace_create=ProviderTraceCreate(- request_json=request_data,- response_json={- "content": {- "tool_call": tool_call.model_dump_json(),- "reasoning": [content.model_dump_json() for content in reasoning_content],- },- "id": interface.message_id,- "model": interface.model,- "role": "assistant",- # "stop_reason": "",- # "stop_sequence": None,- "type": "message",- "usage": {"input_tokens": interface.input_tokens, "output_tokens": interface.output_tokens},- },+ # Process resulting stream content+ try:+ tool_call = interface.get_tool_call_object()+ except ValueError as e:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.no_tool_call.value)+ raise e+ except Exception as e:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.invalid_tool_call.value)+ raise e+ reasoning_content = interface.get_reasoning_content()+ persisted_messages, should_continue, stop_reason = await self._handle_ai_response(+ tool_call,+ valid_tool_names,+ agent_state,+ tool_rules_solver,+ UsageStatistics(+ completion_tokens=interface.output_tokens,+ prompt_tokens=interface.input_tokens,+ total_tokens=interface.input_tokens + interface.output_tokens,+ ),+ reasoning_content=reasoning_content,+ pre_computed_assistant_message_id=interface.letta_message_id,step_id=step_id,- organization_id=self.actor.organization_id,- ),- )+ initial_messages=initial_messages,+ agent_step_span=agent_step_span,+ is_final_step=(i == max_steps - 1),+ )+ step_progression = StepProgression.STEP_LOGGED++ new_message_idx = len(initial_messages) if initial_messages else 0+ self.response_messages.extend(persisted_messages[new_message_idx:])+ new_in_context_messages.extend(persisted_messages[new_message_idx:])++ initial_messages = None++ # log total step time+ now = get_utc_timestamp_ns()+ step_ns = now - step_start+ agent_step_span.add_event(name="step_ms", attributes={"duration_ms": ns_to_ms(step_ns)})+ agent_step_span.end()++ # TODO (cliandy): the stream POST request span has ended at this point, we should tie this to the stream+ # log_event("agent.stream.llm_response.processed") # [4^]++ # Log LLM Trace+ # We are piecing together the streamed response here.+ # Content here does not match the actual response schema as streams come in chunks.+ await self.telemetry_manager.create_provider_trace_async(+ actor=self.actor,+ provider_trace_create=ProviderTraceCreate(+ request_json=request_data,+ response_json={+ "content": {+ "tool_call": tool_call.model_dump_json(),+ "reasoning": [content.model_dump_json() for content in reasoning_content],+ },+ "id": interface.message_id,+ "model": interface.model,+ "role": "assistant",+ # "stop_reason": "",+ # "stop_sequence": None,+ "type": "message",+ "usage": {+ "input_tokens": interface.input_tokens,+ "output_tokens": interface.output_tokens,+ },+ },+ step_id=step_id,+ organization_id=self.actor.organization_id,+ ),+ )+ step_progression = StepProgression.LOGGED_TRACE- tool_return = [msg for msg in persisted_messages if msg.role == "tool"][-1].to_letta_messages()[0]- if not (use_assistant_message and tool_return.name == "send_message"):- # Apply message type filtering if specified- if include_return_message_types is None or tool_return.message_type in include_return_message_types:- yield f"data: {tool_return.model_dump_json()}\n\n"+ # yields tool response as this is handled from Letta and not the response from the LLM provider+ tool_return = [msg for msg in persisted_messages if msg.role == "tool"][-1].to_letta_messages()[0]+ if not (use_assistant_message and tool_return.name == "send_message"):+ # Apply message type filtering if specified+ if include_return_message_types is None or tool_return.message_type in include_return_message_types:+ yield f"data: {tool_return.model_dump_json()}\n\n"- # TODO (cliandy): consolidate and expand with trace- MetricRegistry().step_execution_time_ms_histogram.record(get_utc_timestamp_ns() - step_start, get_ctx_attributes())+ # TODO (cliandy): consolidate and expand with trace+ MetricRegistry().step_execution_time_ms_histogram.record(get_utc_timestamp_ns() - step_start, get_ctx_attributes())+ step_progression = StepProgression.FINISHED++ except Exception as e:+ # Handle any unexpected errors during step processing+ self.logger.error(f"Error during step processing: {e}")++ # This indicates we failed after we decided to stop stepping, which indicates a bug with our flow.+ if not stop_reason:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)+ elif stop_reason.stop_reason in (StopReasonType.end_turn, StopReasonType.max_steps, StopReasonType.tool_rule):+ self.logger.error("Error occurred during step processing, with valid stop reason: %s", stop_reason.stop_reason)+ elif stop_reason.stop_reason not in (StopReasonType.no_tool_call, StopReasonType.invalid_tool_call):+ raise ValueError(f"Invalid Stop Reason: {stop_reason}")++ # Send error stop reason to client and re-raise with expected response code+ yield f"data: {stop_reason.model_dump_json()}\n\n", 500+ raise++ # Update step if it needs to be updated+ finally:+ if settings.track_stop_reason:+ self.logger.info("Running final update. Step Progression: %s", step_progression)+ try:+ if step_progression < StepProgression.STEP_LOGGED:+ await self.step_manager.log_step_async(+ actor=self.actor,+ agent_id=agent_state.id,+ provider_name=agent_state.llm_config.model_endpoint_type,+ provider_category=agent_state.llm_config.provider_category or "base",+ model=agent_state.llm_config.model,+ model_endpoint=agent_state.llm_config.model_endpoint,+ context_window_limit=agent_state.llm_config.context_window,+ usage=UsageStatistics(completion_tokens=0, prompt_tokens=0, total_tokens=0),+ provider_id=None,+ job_id=self.current_run_id if self.current_run_id else None,+ step_id=step_id,+ project_id=agent_state.project_id,+ stop_reason=stop_reason,+ )+ if step_progression <= StepProgression.STREAM_RECEIVED:+ if first_chunk and settings.track_errored_messages:+ for message in initial_messages:+ message.is_err = True+ message.step_id = step_id+ await self.message_manager.create_many_messages_async(initial_messages, actor=self.actor)+ elif step_progression <= StepProgression.LOGGED_TRACE:+ if stop_reason is None:+ self.logger.error("Error in step after logging step")+ stop_reason = LettaStopReason(stop_reason=StopReasonType.error.value)+ await self.step_manager.update_step_stop_reason(self.actor, step_id, stop_reason.stop_reason)+ elif step_progression == StepProgression.FINISHED and not should_continue:+ if stop_reason is None:+ stop_reason = LettaStopReason(stop_reason=StopReasonType.end_turn.value)+ await self.step_manager.update_step_stop_reason(self.actor, step_id, stop_reason.stop_reason)+ else:+ self.logger.error("Invalid StepProgression value")+ except Exception as e:+ self.logger.error("Failed to update step: %s", e)if not should_continue:break-# Extend the in context message idsif not agent_state.message_buffer_autoclear:await self._rebuild_context_window(@@ -919,7 +1115,7 @@ class LettaAgent(BaseAgent):in_context_messages=in_context_messages,new_letta_messages=new_letta_messages,)- await self.agent_manager.set_in_context_messages_async(+ await self.agent_manager.update_message_ids_async(agent_id=self.agent_id,message_ids=[m.id for m in new_in_context_messages],actor=self.actor,@@ -936,7 +1132,7 @@ class LettaAgent(BaseAgent):new_in_context_messages, updated = await self.summarizer.summarize(in_context_messages=in_context_messages, new_letta_messages=[], force=True)- return await self.agent_manager.set_in_context_messages_async(+ return await self.agent_manager.update_message_ids_async(agent_id=self.agent_id, message_ids=[m.id for m in new_in_context_messages], actor=self.actor)@@ -948,18 +1144,17 @@ class LettaAgent(BaseAgent):agent_state: AgentState,tool_rules_solver: ToolRulesSolver,) -> tuple[dict, list[str]]:- self.num_messages, self.num_archival_memories = await asyncio.gather(- (- self.message_manager.size_async(actor=self.actor, agent_id=agent_state.id)- if self.num_messages is None- else asyncio.sleep(0, result=self.num_messages)- ),- (- self.passage_manager.agent_passage_size_async(actor=self.actor, agent_id=agent_state.id)- if self.num_archival_memories is None- else asyncio.sleep(0, result=self.num_archival_memories)- ),- )+ if not self.num_messages:+ self.num_messages = await self.message_manager.size_async(+ agent_id=agent_state.id,+ actor=self.actor,+ )+ if not self.num_archival_memories:+ self.num_archival_memories = await self.passage_manager.agent_passage_size_async(+ agent_id=agent_state.id,+ actor=self.actor,+ )+in_context_messages = await self._rebuild_memory_async(in_context_messages,agent_state,@@ -1108,6 +1303,7 @@ class LettaAgent(BaseAgent):job_id=run_id if run_id else self.current_run_id,step_id=step_id,project_id=agent_state.project_id,+ stop_reason=stop_reason,)tool_call_messages = create_letta_messages_from_llm_response(diff --git a/letta/agents/letta_agent_batch.py b/letta/agents/letta_agent_batch.pyindex 456633d4a..3bca27f4a 100644--- a/letta/agents/letta_agent_batch.py+++ b/letta/agents/letta_agent_batch.py@@ -100,7 +100,6 @@ async def execute_tool_wrapper(params: ToolExecutionParams) -> tuple[str, ToolEx# TODO: Limitations -># TODO: Only works with anthropic for nowclass LettaAgentBatch(BaseAgent):-def __init__(self,message_manager: MessageManager,@@ -516,7 +515,7 @@ class LettaAgentBatch(BaseAgent):for agent_id, new_msgs in msg_map.items():ast = ctx.agent_state_map[agent_id]if not ast.message_buffer_autoclear:- await self.agent_manager.set_in_context_messages_async(+ await self.agent_manager.update_message_ids_async(agent_id=agent_id,message_ids=ast.message_ids + [m.id for m in new_msgs],actor=self.actor,diff --git a/letta/agents/voice_agent.py b/letta/agents/voice_agent.pyindex 0c77626ec..9e30cb544 100644--- a/letta/agents/voice_agent.py+++ b/letta/agents/voice_agent.py@@ -1,4 +1,3 @@-import asyncioimport jsonimport uuidfrom datetime import datetime, timedelta, timezone@@ -299,7 +298,7 @@ class VoiceAgent(BaseAgent):in_context_messages=in_context_messages, new_letta_messages=new_letta_messages)- await self.agent_manager.set_in_context_messages_async(+ await self.agent_manager.update_message_ids_async(agent_id=self.agent_id, message_ids=[m.id for m in new_in_context_messages], actor=self.actor)@@ -308,18 +307,17 @@ class VoiceAgent(BaseAgent):in_context_messages: List[Message],agent_state: AgentState,) -> List[Message]:- self.num_messages, self.num_archival_memories = await asyncio.gather(- (- self.message_manager.size_async(actor=self.actor, agent_id=agent_state.id)- if self.num_messages is None- else asyncio.sleep(0, result=self.num_messages)- ),- (- self.passage_manager.agent_passage_size_async(actor=self.actor, agent_id=agent_state.id)- if self.num_archival_memories is None- else asyncio.sleep(0, result=self.num_archival_memories)- ),- )+ if not self.num_messages:+ self.num_messages = await self.message_manager.size_async(+ agent_id=agent_state.id,+ actor=self.actor,+ )+ if not self.num_archival_memories:+ self.num_archival_memories = await self.passage_manager.agent_passage_size_async(+ agent_id=agent_state.id,+ actor=self.actor,+ )+return await super()._rebuild_memory_async(in_context_messages, agent_state, num_messages=self.num_messages, num_archival_memories=self.num_archival_memories)@@ -379,19 +377,19 @@ class VoiceAgent(BaseAgent):"type": ["array", "null"],"items": {"type": "string"},"description": (- "Extra keywords (e.g., order ID, place name). " "Use *null* when the utterance is already specific."+ "Extra keywords (e.g., order ID, place name). Use *null* when the utterance is already specific."),},"start_minutes_ago": {"type": ["integer", "null"],"description": (- "Newer bound of the time window, in minutes ago. " "Use *null* if no lower bound is needed."+ "Newer bound of the time window, in minutes ago. Use *null* if no lower bound is needed."),},"end_minutes_ago": {"type": ["integer", "null"],"description": (- "Older bound of the time window, in minutes ago. " "Use *null* if no upper bound is needed."+ "Older bound of the time window, in minutes ago. Use *null* if no upper bound is needed."),},},diff --git a/letta/client/client.py b/letta/client/client.pyindex d2aadcbce..1d5c81e73 100644--- a/letta/client/client.py+++ b/letta/client/client.py@@ -568,8 +568,8 @@ class RESTClient(AbstractClient):tool_names += BASE_MEMORY_TOOLStool_ids += [self.get_tool_id(tool_name=name) for name in tool_names]- assert embedding_config or self._default_embedding_config, f"Embedding config must be provided"- assert llm_config or self._default_llm_config, f"LLM config must be provided"+ assert embedding_config or self._default_embedding_config, "Embedding config must be provided"+ assert llm_config or self._default_llm_config, "LLM config must be provided"# TODO: This should not happen here, we need to have clear separation between create/add blocks# TODO: This is insanely hacky and a result of allowing free-floating blocks@@ -1392,7 +1392,7 @@ class RESTClient(AbstractClient):Returns:source (Source): Created source"""- assert embedding_config or self._default_embedding_config, f"Must specify embedding_config for source"+ assert embedding_config or self._default_embedding_config, "Must specify embedding_config for source"source_create = SourceCreate(name=name, embedding_config=embedding_config or self._default_embedding_config)payload = source_create.model_dump()response = requests.post(f"{self.base_url}/{self.api_prefix}/sources", json=payload, headers=self.headers)diff --git a/letta/constants.py b/letta/constants.pyindex 05711ab3b..33c9745f3 100644--- a/letta/constants.py+++ b/letta/constants.py@@ -378,3 +378,8 @@ PINECONE_MAX_RETRY_ATTEMPTS = 3PINECONE_RETRY_BASE_DELAY = 1.0 # secondsPINECONE_RETRY_MAX_DELAY = 60.0 # secondsPINECONE_RETRY_BACKOFF_FACTOR = 2.0+PINECONE_THROTTLE_DELAY = 0.75 # seconds base delay between batches++# builtin web search+WEB_SEARCH_MODEL_ENV_VAR_NAME = "LETTA_BUILTIN_WEBSEARCH_OPENAI_MODEL_NAME"+WEB_SEARCH_MODEL_ENV_VAR_DEFAULT_VALUE = "gpt-4.1-mini-2025-04-14"diff --git a/letta/embeddings.py b/letta/embeddings.pyindex 541815770..dffcd5716 100644--- a/letta/embeddings.py+++ b/letta/embeddings.py@@ -190,7 +190,6 @@ class GoogleEmbeddings:class GoogleVertexEmbeddings:-def __init__(self, model: str, project_id: str, region: str):from google import genai@@ -203,7 +202,6 @@ class GoogleVertexEmbeddings:class OpenAIEmbeddings:-def __init__(self, api_key: str, model: str, base_url: str):if base_url:self.client = OpenAI(api_key=api_key, base_url=base_url)diff --git a/letta/errors.py b/letta/errors.pyindex 1e2f013f1..c3b218fce 100644--- a/letta/errors.py+++ b/letta/errors.py@@ -219,3 +219,11 @@ class HandleNotFoundError(LettaError):message=f"Handle {handle} not found, must be one of {available_handles}",code=ErrorCode.NOT_FOUND,)+++class AgentFileExportError(Exception):+ """Exception raised during agent file export operations"""+++class AgentFileImportError(Exception):+ """Exception raised during agent file import operations"""diff --git a/letta/functions/function_sets/base.py b/letta/functions/function_sets/base.pyindex ad91fb1f0..0ceafd085 100644--- a/letta/functions/function_sets/base.py+++ b/letta/functions/function_sets/base.py@@ -42,7 +42,7 @@ def conversation_search(self: "Agent", query: str, page: Optional[int] = 0) -> Otry:page = int(page)except:- raise ValueError(f"'page' argument must be an integer")+ raise ValueError("'page' argument must be an integer")count = RETRIEVAL_QUERY_DEFAULT_PAGE_SIZE# TODO: add paging by page number. currently cursor only works with strings.# original: start=page * count@@ -55,7 +55,7 @@ def conversation_search(self: "Agent", query: str, page: Optional[int] = 0) -> Ototal = len(messages)num_pages = math.ceil(total / count) - 1 # 0 indexif len(messages) == 0:- results_str = f"No results found."+ results_str = "No results found."else:results_pref = f"Showing {len(messages)} of {total} results (page {page}/{num_pages}):"results_formatted = [message.content[0].text for message in messages]@@ -103,7 +103,7 @@ def archival_memory_search(self: "Agent", query: str, page: Optional[int] = 0, stry:page = int(page)except:- raise ValueError(f"'page' argument must be an integer")+ raise ValueError("'page' argument must be an integer")count = RETRIEVAL_QUERY_DEFAULT_PAGE_SIZEtry:diff --git a/letta/functions/helpers.py b/letta/functions/helpers.pyindex 161bef963..dc1a3b0b9 100644--- a/letta/functions/helpers.py+++ b/letta/functions/helpers.py@@ -23,7 +23,6 @@ from letta.settings import settings# TODO needed?def generate_mcp_tool_wrapper(mcp_tool_name: str) -> tuple[str, str]:-wrapper_function_str = f"""\def {mcp_tool_name}(**kwargs):raise RuntimeError("Something went wrong - we should never be using the persisted source code for MCP. Please reach out to Letta team")@@ -46,7 +45,7 @@ def generate_langchain_tool_wrapper(_assert_all_classes_are_imported(tool, additional_imports_module_attr_map)tool_instantiation = f"tool = {generate_imported_tool_instantiation_call_str(tool)}"- run_call = f"return tool._run(**kwargs)"+ run_call = "return tool._run(**kwargs)"func_name = humps.decamelize(tool_name)# Combine all parts into the wrapper function@@ -240,7 +239,7 @@ async def async_execute_send_message_to_agent(try:server.agent_manager.get_agent_by_id(agent_id=other_agent_id, actor=sender_agent.user)except NoResultFound:- raise ValueError(f"Target agent {other_agent_id} either does not exist or is not in org " f"({sender_agent.user.organization_id}).")+ raise ValueError(f"Target agent {other_agent_id} either does not exist or is not in org ({sender_agent.user.organization_id}).")# 2. Use your async retry logicreturn await _async_send_message_with_retries(diff --git a/letta/groups/sleeptime_multi_agent.py b/letta/groups/sleeptime_multi_agent.pyindex 3ab0adc24..b207219c9 100644--- a/letta/groups/sleeptime_multi_agent.py+++ b/letta/groups/sleeptime_multi_agent.py@@ -20,7 +20,6 @@ from letta.services.message_manager import MessageManagerclass SleeptimeMultiAgent(Agent):-def __init__(self,interface: AgentInterface,diff --git a/letta/helpers/composio_helpers.py b/letta/helpers/composio_helpers.pyindex 7a142f7c5..1e6e31d61 100644--- a/letta/helpers/composio_helpers.py+++ b/letta/helpers/composio_helpers.py@@ -10,7 +10,7 @@ def get_composio_api_key(actor: User, logger: Optional[Logger] = None) -> Optionapi_keys = SandboxConfigManager().list_sandbox_env_vars_by_key(key="COMPOSIO_API_KEY", actor=actor)if not api_keys:if logger:- logger.debug(f"No API keys found for Composio. Defaulting to the environment variable...")+ logger.debug("No API keys found for Composio. Defaulting to the environment variable...")if tool_settings.composio_api_key:return tool_settings.composio_api_keyelse:@@ -26,7 +26,7 @@ async def get_composio_api_key_async(actor: User, logger: Optional[Logger] = Nonapi_keys = await SandboxConfigManager().list_sandbox_env_vars_by_key_async(key="COMPOSIO_API_KEY", actor=actor)if not api_keys:if logger:- logger.debug(f"No API keys found for Composio. Defaulting to the environment variable...")+ logger.debug("No API keys found for Composio. Defaulting to the environment variable...")if tool_settings.composio_api_key:return tool_settings.composio_api_keyelse:diff --git a/letta/helpers/converters.py b/letta/helpers/converters.pyindex 53ee1565e..b855001fd 100644--- a/letta/helpers/converters.py+++ b/letta/helpers/converters.py@@ -245,7 +245,7 @@ def deserialize_message_content(data: Optional[List[Dict]]) -> List[MessageConteif content_type == MessageContentType.text:content = TextContent(**item)elif content_type == MessageContentType.image:- assert item["source"]["type"] == ImageSourceType.letta, f'Invalid image source type: {item["source"]["type"]}'+ assert item["source"]["type"] == ImageSourceType.letta, f"Invalid image source type: {item['source']['type']}"content = ImageContent(**item)elif content_type == MessageContentType.tool_call:content = ToolCallContent(**item)diff --git a/letta/helpers/pinecone_utils.py b/letta/helpers/pinecone_utils.pyindex 7caa52808..e014061b6 100644--- a/letta/helpers/pinecone_utils.py+++ b/letta/helpers/pinecone_utils.py@@ -31,6 +31,7 @@ from letta.constants import (PINECONE_RETRY_BASE_DELAY,PINECONE_RETRY_MAX_DELAY,PINECONE_TEXT_FIELD_NAME,+ PINECONE_THROTTLE_DELAY,)from letta.log import get_loggerfrom letta.schemas.user import User@@ -256,6 +257,13 @@ async def upsert_records_to_pinecone_index(records: List[dict], actor: User):logger.debug(f"[Pinecone] Upserting batch {batch_num}/{total_batches} with {len(batch)} records")await dense_index.upsert_records(actor.organization_id, batch)+ # throttle between batches (except the last one)+ if batch_num < total_batches:+ jitter = random.uniform(0, PINECONE_THROTTLE_DELAY * 0.2) # ±20% jitter+ throttle_delay = PINECONE_THROTTLE_DELAY + jitter+ logger.debug(f"[Pinecone] Throttling for {throttle_delay:.3f}s before next batch")+ await asyncio.sleep(throttle_delay)+logger.info(f"[Pinecone] Successfully upserted all {len(records)} records in {total_batches} batches")diff --git a/letta/helpers/tool_rule_solver.py b/letta/helpers/tool_rule_solver.pyindex e9a2dd71f..acf7c2dd0 100644--- a/letta/helpers/tool_rule_solver.py+++ b/letta/helpers/tool_rule_solver.py@@ -1,4 +1,4 @@-from typing import List, Optional, Set, Union+from typing import List, Optional, Unionfrom pydantic import BaseModel, Field@@ -107,25 +107,20 @@ class ToolRulesSolver(BaseModel):self.tool_call_history.clear()def get_allowed_tool_names(- self, available_tools: Set[str], error_on_empty: bool = False, last_function_response: Optional[str] = None+ self, available_tools: set[str], error_on_empty: bool = True, last_function_response: str | None = None) -> List[str]:- """Get a list of tool names allowed based on the last tool called."""+ """Get a list of tool names allowed based on the last tool called.++ The logic is as follows:+ 1. if there are no previous tool calls and we have InitToolRules, those are the only options for the first tool call+ 2. else we take the intersection of the Parent/Child/Conditional/MaxSteps as the options+ 3. Continue/Terminal/RequiredBeforeExit rules are applied in the agent loop flow, not to restrict tools+ """# TODO: This piece of code here is quite ugly and deserves a refactor- # TODO: There's some weird logic encoded here:- # TODO: -> This only takes into consideration Init, and a set of Child/Conditional/MaxSteps tool rules- # TODO: -> Init tool rules outputs are treated additively, Child/Conditional/MaxSteps are intersection based# TODO: -> Tool rules should probably be refactored to take in a set of tool names?- # If no tool has been called yet, return InitToolRules additively- if not self.tool_call_history:- if self.init_tool_rules:- # If there are init tool rules, only return those defined in the init tool rules- return [rule.tool_name for rule in self.init_tool_rules]- else:- # Otherwise, return all tools besides those constrained by parent tool rules- available_tools = available_tools - set.union(set(), *(set(rule.children) for rule in self.parent_tool_rules))- return list(available_tools)+ if not self.tool_call_history and self.init_tool_rules:+ return [rule.tool_name for rule in self.init_tool_rules]else:- # Collect valid tools from all child-based rulesvalid_tool_sets = []for rule in self.child_based_tool_rules + self.parent_tool_rules:tools = rule.get_valid_tools(self.tool_call_history, available_tools, last_function_response)@@ -151,11 +146,11 @@ class ToolRulesSolver(BaseModel):"""Check if the tool is defined as a continue tool in the tool rules."""return any(rule.tool_name == tool_name for rule in self.continue_tool_rules)- def has_required_tools_been_called(self, available_tools: Set[str]) -> bool:+ def has_required_tools_been_called(self, available_tools: set[str]) -> bool:"""Check if all required-before-exit tools have been called."""return len(self.get_uncalled_required_tools(available_tools=available_tools)) == 0- def get_uncalled_required_tools(self, available_tools: Set[str]) -> List[str]:+ def get_uncalled_required_tools(self, available_tools: set[str]) -> List[str]:"""Get the list of required-before-exit tools that have not been called yet."""if not self.required_before_exit_tool_rules:return [] # No required tools means no uncalled toolsdiff --git a/letta/llm_api/aws_bedrock.py b/letta/llm_api/aws_bedrock.pyindex c395868da..539ce0fd4 100644--- a/letta/llm_api/aws_bedrock.py+++ b/letta/llm_api/aws_bedrock.py@@ -41,22 +41,36 @@ def get_bedrock_client(return bedrock-def bedrock_get_model_list(region_name: str) -> List[dict]:+def bedrock_get_model_list(+ region_name: str,+ access_key_id: Optional[str] = None,+ secret_access_key: Optional[str] = None,+) -> List[dict]:"""Get list of available models from Bedrock.Args:region_name: AWS region name+ access_key_id: Optional AWS access key ID+ secret_access_key: Optional AWS secret access key++ TODO: Implement model_provider and output_modality filteringmodel_provider: Optional provider name to filter models. If None, returns all models.output_modality: Output modality to filter models. Defaults to "text".Returns:List of model summaries+"""import boto3try:- bedrock = boto3.client("bedrock", region_name=region_name)+ bedrock = boto3.client(+ "bedrock",+ region_name=region_name,+ aws_access_key_id=access_key_id,+ aws_secret_access_key=secret_access_key,+ )response = bedrock.list_inference_profiles()return response["inferenceProfileSummaries"]except Exception as e:diff --git a/letta/llm_api/cohere.py b/letta/llm_api/cohere.pyindex 4a30d7968..eeabae7a3 100644--- a/letta/llm_api/cohere.py+++ b/letta/llm_api/cohere.py@@ -307,7 +307,7 @@ def cohere_chat_completions_request(data = chat_completion_request.model_dump(exclude_none=True)if "functions" in data:- raise ValueError(f"'functions' unexpected in Anthropic API payload")+ raise ValueError("'functions' unexpected in Anthropic API payload")# If tools == None, strip from the payloadif "tools" in data and data["tools"] is None:diff --git a/letta/llm_api/openai_client.py b/letta/llm_api/openai_client.pyindex 3b12095fe..c9561cc2f 100644--- a/letta/llm_api/openai_client.py+++ b/letta/llm_api/openai_client.py@@ -54,7 +54,7 @@ def accepts_developer_role(model: str) -> bool:See: https://community.openai.com/t/developer-role-not-accepted-for-o1-o1-mini-o3-mini/1110750/7"""- if is_openai_reasoning_model(model) and not "o1-mini" in model or "o1-preview" in model:+ if is_openai_reasoning_model(model) and "o1-mini" not in model or "o1-preview" in model:return Trueelse:return Falsediff --git a/letta/local_llm/grammars/gbnf_grammar_generator.py b/letta/local_llm/grammars/gbnf_grammar_generator.pyindex 8daeda5c6..536bf8e2e 100644--- a/letta/local_llm/grammars/gbnf_grammar_generator.py+++ b/letta/local_llm/grammars/gbnf_grammar_generator.py@@ -697,7 +697,7 @@ def generate_markdown_documentation(# Indenting the fields sectiondocumentation += f" {fields_prefix}:\n"else:- documentation += f" attributes:\n"+ documentation += " attributes:\n"if isclass(model) and issubclass(model, BaseModel):for name, field_type in model.__annotations__.items():# if name == "markdown_code_block":diff --git a/letta/local_llm/llm_chat_completion_wrappers/zephyr.py b/letta/local_llm/llm_chat_completion_wrappers/zephyr.pyindex 3b7fb72d5..8ee733aa8 100644--- a/letta/local_llm/llm_chat_completion_wrappers/zephyr.py+++ b/letta/local_llm/llm_chat_completion_wrappers/zephyr.py@@ -43,7 +43,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):# System instructions go firstassert messages[0]["role"] == "system"- prompt += f"<|system|>"+ prompt += "<|system|>"prompt += f"\n{messages[0]['content']}"# Next is the functions preamble@@ -52,7 +52,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):func_str = ""func_str += f"{schema['name']}:"func_str += f"\n description: {schema['description']}"- func_str += f"\n params:"+ func_str += "\n params:"for param_k, param_v in schema["parameters"]["properties"].items():# TODO we're ignoring typefunc_str += f"\n {param_k}: {param_v['description']}"@@ -60,8 +60,8 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):return func_str# prompt += f"\nPlease select the most suitable function and parameters from the list of available functions below, based on the user's input. Provide your response in JSON format."- prompt += f"\nPlease select the most suitable function and parameters from the list of available functions below, based on the ongoing conversation. Provide your response in JSON format."- prompt += f"\nAvailable functions:"+ prompt += "\nPlease select the most suitable function and parameters from the list of available functions below, based on the ongoing conversation. Provide your response in JSON format."+ prompt += "\nAvailable functions:"if function_documentation is not None:prompt += f"\n{function_documentation}"else:@@ -92,7 +92,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):prompt += f"\n<|user|>\n{message['content']}{IM_END_TOKEN}"# prompt += f"\nUSER: {message['content']}"elif message["role"] == "assistant":- prompt += f"\n<|assistant|>"+ prompt += "\n<|assistant|>"if message["content"] is not None:prompt += f"\n{message['content']}"# prompt += f"\nASSISTANT: {message['content']}"@@ -103,7 +103,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):elif message["role"] in ["function", "tool"]:# TODO find a good way to add this# prompt += f"\nASSISTANT: (function return) {message['content']}"- prompt += f"\n<|assistant|>"+ prompt += "\n<|assistant|>"prompt += f"\nFUNCTION RETURN: {message['content']}"# prompt += f"\nFUNCTION RETURN: {message['content']}"continue@@ -116,7 +116,7 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):if self.include_assistant_prefix:# prompt += f"\nASSISTANT:"- prompt += f"\n<|assistant|>"+ prompt += "\n<|assistant|>"if self.include_opening_brance_in_prefix:prompt += "\n{"@@ -214,9 +214,9 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):func_str = ""func_str += f"{schema['name']}:"func_str += f"\n description: {schema['description']}"- func_str += f"\n params:"+ func_str += "\n params:"if add_inner_thoughts:- func_str += f"\n inner_thoughts: Deep inner monologue private to you only."+ func_str += "\n inner_thoughts: Deep inner monologue private to you only."for param_k, param_v in schema["parameters"]["properties"].items():# TODO we're ignoring typefunc_str += f"\n {param_k}: {param_v['description']}"@@ -224,8 +224,8 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):return func_str# prompt += f"\nPlease select the most suitable function and parameters from the list of available functions below, based on the user's input. Provide your response in JSON format."- prompt += f"\nPlease select the most suitable function and parameters from the list of available functions below, based on the ongoing conversation. Provide your response in JSON format."- prompt += f"\nAvailable functions:"+ prompt += "\nPlease select the most suitable function and parameters from the list of available functions below, based on the ongoing conversation. Provide your response in JSON format."+ prompt += "\nAvailable functions:"if function_documentation is not None:prompt += f"\n{function_documentation}"else:@@ -259,10 +259,10 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):except:prompt += f"\n<|user|>\n{message['content']}{IM_END_TOKEN}"elif message["role"] == "assistant":- prompt += f"\n<|assistant|>"+ prompt += "\n<|assistant|>"# need to add the function call if there was oneinner_thoughts = message["content"]- if "function_call" in message and message["function_call"]:+ if message.get("function_call"):prompt += f"\n{create_function_call(message['function_call'], inner_thoughts=inner_thoughts)}"elif message["role"] in ["function", "tool"]:# TODO find a good way to add this@@ -277,7 +277,7 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):# prompt += "\n### RESPONSE"if self.include_assistant_prefix:- prompt += f"\n<|assistant|>"+ prompt += "\n<|assistant|>"if self.include_opening_brance_in_prefix:prompt += "\n{"diff --git a/letta/local_llm/utils.py b/letta/local_llm/utils.pyindex 09177c3ef..6027484dc 100644--- a/letta/local_llm/utils.py+++ b/letta/local_llm/utils.py@@ -76,7 +76,7 @@ def num_tokens_from_functions(functions: List[dict], model: str = "gpt-4"):except KeyError:from letta.utils import printd- printd(f"Warning: model not found. Using cl100k_base encoding.")+ printd("Warning: model not found. Using cl100k_base encoding.")encoding = tiktoken.get_encoding("cl100k_base")num_tokens = 0@@ -238,7 +238,6 @@ def num_tokens_from_messages(messages: List[dict], model: str = "gpt-4") -> int:num_tokens += tokens_per_messagefor key, value in message.items():try:-if isinstance(value, list) and key == "tool_calls":num_tokens += num_tokens_from_tool_calls(tool_calls=value, model=model)# special case for tool calling (list)diff --git a/letta/orm/agent.py b/letta/orm/agent.pyindex ce51d7292..44e8a6f06 100644--- a/letta/orm/agent.py+++ b/letta/orm/agent.py@@ -93,7 +93,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, AsyncAttrs):timezone: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="The timezone of the agent (for the context window).")# relationships- organization: Mapped["Organization"] = relationship("Organization", back_populates="agents")+ organization: Mapped["Organization"] = relationship("Organization", back_populates="agents", lazy="raise")tool_exec_environment_variables: Mapped[List["AgentEnvironmentVariable"]] = relationship("AgentEnvironmentVariable",back_populates="agent",@@ -128,7 +128,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, AsyncAttrs):groups: Mapped[List["Group"]] = relationship("Group",secondary="groups_agents",- lazy="selectin",+ lazy="raise",back_populates="agents",passive_deletes=True,)@@ -138,7 +138,7 @@ class Agent(SqlalchemyBase, OrganizationMixin, AsyncAttrs):viewonly=True,back_populates="manager_agent",)- batch_items: Mapped[List["LLMBatchItem"]] = relationship("LLMBatchItem", back_populates="agent", lazy="selectin")+ batch_items: Mapped[List["LLMBatchItem"]] = relationship("LLMBatchItem", back_populates="agent", lazy="raise")file_agents: Mapped[List["FileAgent"]] = relationship("FileAgent",back_populates="agent",diff --git a/letta/orm/block.py b/letta/orm/block.pyindex 994a04c4b..bbbb6dfc1 100644--- a/letta/orm/block.py+++ b/letta/orm/block.py@@ -55,11 +55,11 @@ class Block(OrganizationMixin, SqlalchemyBase):__mapper_args__ = {"version_id_col": version}# relationships- organization: Mapped[Optional["Organization"]] = relationship("Organization")+ organization: Mapped[Optional["Organization"]] = relationship("Organization", lazy="raise")agents: Mapped[List["Agent"]] = relationship("Agent",secondary="blocks_agents",- lazy="selectin",+ lazy="raise",passive_deletes=True, # Ensures SQLAlchemy doesn't fetch blocks_agents rows before deletingback_populates="core_memory",doc="Agents associated with this block.",@@ -67,14 +67,14 @@ class Block(OrganizationMixin, SqlalchemyBase):identities: Mapped[List["Identity"]] = relationship("Identity",secondary="identities_blocks",- lazy="selectin",+ lazy="raise",back_populates="blocks",passive_deletes=True,)groups: Mapped[List["Group"]] = relationship("Group",secondary="groups_blocks",- lazy="selectin",+ lazy="raise",back_populates="shared_blocks",passive_deletes=True,)diff --git a/letta/orm/files_agents.py b/letta/orm/files_agents.pyindex d8fd5c2f6..208501e3f 100644--- a/letta/orm/files_agents.py+++ b/letta/orm/files_agents.py@@ -96,7 +96,6 @@ class FileAgent(SqlalchemyBase, OrganizationMixin):visible_content += truncated_warningreturn PydanticBlock(- organization_id=self.organization_id,value=visible_content,label=self.file_name, # use denormalized file_name instead of self.file.file_nameread_only=True,diff --git a/letta/orm/identity.py b/letta/orm/identity.pyindex 5f6e56066..ac83e9528 100644--- a/letta/orm/identity.py+++ b/letta/orm/identity.py@@ -23,6 +23,8 @@ class Identity(SqlalchemyBase, OrganizationMixin):"organization_id",name="unique_identifier_key_project_id_organization_id",postgresql_nulls_not_distinct=True,+ # For SQLite compatibility, we'll need to handle the NULL case differently+ # in the service layer since SQLite doesn't support postgresql_nulls_not_distinct),)diff --git a/letta/orm/mcp_server.py b/letta/orm/mcp_server.pyindex 113b71837..55a2a6724 100644--- a/letta/orm/mcp_server.py+++ b/letta/orm/mcp_server.py@@ -50,5 +50,3 @@ class MCPServer(SqlalchemyBase, OrganizationMixin):metadata_: Mapped[Optional[dict]] = mapped_column(JSON, default=lambda: {}, doc="A dictionary of additional metadata for the MCP server.")- # relationships- # organization: Mapped["Organization"] = relationship("Organization", back_populates="mcp_server", lazy="selectin")diff --git a/letta/orm/message.py b/letta/orm/message.pyindex 41551fb5c..5e96790de 100644--- a/letta/orm/message.py+++ b/letta/orm/message.py@@ -11,7 +11,7 @@ from letta.schemas.letta_message_content import MessageContentfrom letta.schemas.letta_message_content import TextContent as PydanticTextContentfrom letta.schemas.message import Message as PydanticMessagefrom letta.schemas.message import ToolReturn-from letta.settings import settings+from letta.settings import DatabaseChoice, settingsclass Message(SqlalchemyBase, OrganizationMixin, AgentMixin):@@ -49,6 +49,9 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):nullable=True,doc="The id of the LLMBatchItem that this message is associated with",)+ is_err: Mapped[Optional[bool]] = mapped_column(+ nullable=True, doc="Whether this message is part of an error step. Used only for debugging purposes."+ )# Monotonically increasing sequence for efficient/correct listingsequence_id: Mapped[int] = mapped_column(@@ -59,7 +62,7 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):)# Relationships- organization: Mapped["Organization"] = relationship("Organization", back_populates="messages", lazy="selectin")+ organization: Mapped["Organization"] = relationship("Organization", back_populates="messages", lazy="raise")step: Mapped["Step"] = relationship("Step", back_populates="messages", lazy="selectin")# Job relationship@@ -78,7 +81,7 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):if self.text and not model.content:model.content = [PydanticTextContent(text=self.text)]# If there are no tool calls, set tool_calls to None- if len(self.tool_calls) == 0:+ if self.tool_calls is None or len(self.tool_calls) == 0:model.tool_calls = Nonereturn model@@ -86,16 +89,139 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):# listener[email protected]_for(Message, "before_insert")-def set_sequence_id_for_sqlite(mapper, connection, target):- # TODO: Kind of hacky, used to detect if we are using sqlite or not- if not settings.letta_pg_uri_no_default:- session = Session.object_session(target)[email protected]_for(Session, "before_flush")+def set_sequence_id_for_sqlite_bulk(session, flush_context, instances):+ # Handle bulk inserts for SQLite+ if settings.database_engine is DatabaseChoice.SQLITE:+ # Find all new Message objects that need sequence IDs+ new_messages = [obj for obj in session.new if isinstance(obj, Message) and obj.sequence_id is None]++ if new_messages:+ # Create a sequence table if it doesn't exist for atomic increments+ session.execute(+ text(+ """+ CREATE TABLE IF NOT EXISTS message_sequence (+ id INTEGER PRIMARY KEY,+ next_val INTEGER NOT NULL DEFAULT 1+ )+ """+ )+ )++ # Initialize the sequence table if empty+ session.execute(+ text(+ """+ INSERT OR IGNORE INTO message_sequence (id, next_val)+ SELECT 1, COALESCE(MAX(sequence_id), 0) + 1+ FROM messages+ """+ )+ )++ # Get the number of records being inserted+ records_count = len(new_messages)++ # Atomically reserve a range of sequence values for this batch+ result = session.execute(+ text(+ """+ UPDATE message_sequence+ SET next_val = next_val + :count+ WHERE id = 1+ RETURNING next_val - :count+ """+ ),+ {"count": records_count},+ )++ start_sequence_id = result.scalar()+ if start_sequence_id is None:+ # Fallback if RETURNING doesn't work (older SQLite versions)+ session.execute(+ text(+ """+ UPDATE message_sequence+ SET next_val = next_val + :count+ WHERE id = 1+ """+ ),+ {"count": records_count},+ )+ start_sequence_id = session.execute(+ text(+ """+ SELECT next_val - :count FROM message_sequence WHERE id = 1+ """+ ),+ {"count": records_count},+ ).scalar()++ # Assign sequential IDs to each record+ for i, obj in enumerate(new_messages):+ obj.sequence_id = start_sequence_id + i- if not hasattr(session, "_sequence_id_counter"):- # Initialize counter for this flush- max_seq = connection.scalar(text("SELECT MAX(sequence_id) FROM messages"))- session._sequence_id_counter = max_seq or 0- session._sequence_id_counter += 1- target.sequence_id = session._sequence_id_counter[email protected]_for(Message, "before_insert")+def set_sequence_id_for_sqlite(mapper, connection, target):+ if settings.database_engine is DatabaseChoice.SQLITE:+ # For SQLite, we need to generate sequence_id manually+ # Use a database-level atomic operation to avoid race conditions++ # Create a sequence table if it doesn't exist for atomic increments+ connection.execute(+ text(+ """+ CREATE TABLE IF NOT EXISTS message_sequence (+ id INTEGER PRIMARY KEY,+ next_val INTEGER NOT NULL DEFAULT 1+ )+ """+ )+ )++ # Initialize the sequence table if empty+ connection.execute(+ text(+ """+ INSERT OR IGNORE INTO message_sequence (id, next_val)+ SELECT 1, COALESCE(MAX(sequence_id), 0) + 1+ FROM messages+ """+ )+ )++ # Atomically get the next sequence value+ result = connection.execute(+ text(+ """+ UPDATE message_sequence+ SET next_val = next_val + 1+ WHERE id = 1+ RETURNING next_val - 1+ """+ )+ )++ sequence_id = result.scalar()+ if sequence_id is None:+ # Fallback if RETURNING doesn't work (older SQLite versions)+ connection.execute(+ text(+ """+ UPDATE message_sequence+ SET next_val = next_val + 1+ WHERE id = 1+ """+ )+ )+ sequence_id = connection.execute(+ text(+ """+ SELECT next_val - 1 FROM message_sequence WHERE id = 1+ """+ )+ ).scalar()++ target.sequence_id = sequence_iddiff --git a/letta/orm/organization.py b/letta/orm/organization.pyindex f5f65cb92..4f78ec895 100644--- a/letta/orm/organization.py+++ b/letta/orm/organization.py@@ -6,18 +6,17 @@ from letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.organization import Organization as PydanticOrganizationif TYPE_CHECKING:+ from letta.orm import Sourcefrom letta.orm.agent import Agent- from letta.orm.agent_passage import AgentPassagefrom letta.orm.block import Blockfrom letta.orm.group import Groupfrom letta.orm.identity import Identity- from letta.orm.llm_batch_item import LLMBatchItem+ from letta.orm.llm_batch_items import LLMBatchItemfrom letta.orm.llm_batch_job import LLMBatchJobfrom letta.orm.message import Message+ from letta.orm.passage import AgentPassage, SourcePassagefrom letta.orm.provider import Provider- from letta.orm.sandbox_config import AgentEnvironmentVariable, SandboxConfig- from letta.orm.sandbox_environment_variable import SandboxEnvironmentVariable- from letta.orm.source_passage import SourcePassage+ from letta.orm.sandbox_config import AgentEnvironmentVariable, SandboxConfig, SandboxEnvironmentVariablefrom letta.orm.tool import Toolfrom letta.orm.user import User@@ -48,6 +47,7 @@ class Organization(SqlalchemyBase):# relationshipsagents: Mapped[List["Agent"]] = relationship("Agent", back_populates="organization", cascade="all, delete-orphan")+ sources: Mapped[List["Source"]] = relationship("Source", 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"diff --git a/letta/orm/passage.py b/letta/orm/passage.pyindex 868f8a67d..1a6c48a28 100644--- a/letta/orm/passage.py+++ b/letta/orm/passage.py@@ -9,7 +9,7 @@ from letta.orm.custom_columns import CommonVector, EmbeddingConfigColumnfrom letta.orm.mixins import AgentMixin, FileMixin, OrganizationMixin, SourceMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.passage import Passage as PydanticPassage-from letta.settings import settings+from letta.settings import DatabaseChoice, settingsconfig = LettaConfig()@@ -29,7 +29,7 @@ class BasePassage(SqlalchemyBase, OrganizationMixin):metadata_: Mapped[dict] = mapped_column(JSON, doc="Additional metadata")# Vector embedding field based on database type- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:from pgvector.sqlalchemy import Vectorembedding = mapped_column(Vector(MAX_EMBEDDING_DIM))@@ -56,7 +56,7 @@ class SourcePassage(BasePassage, FileMixin, SourceMixin):@declared_attrdef __table_args__(cls):# TODO (cliandy): investigate if this is necessary, may be for SQLite compatability or do we need to add as well?- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:return (Index("source_passages_org_idx", "organization_id"),Index("source_passages_created_at_id_idx", "created_at", "id"),@@ -81,7 +81,7 @@ class AgentPassage(BasePassage, AgentMixin):@declared_attrdef __table_args__(cls):- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:return (Index("agent_passages_org_idx", "organization_id"),Index("ix_agent_passages_org_agent", "organization_id", "agent_id"),diff --git a/letta/orm/source.py b/letta/orm/source.pyindex f23c61e51..ff34462dd 100644--- a/letta/orm/source.py+++ b/letta/orm/source.py@@ -20,7 +20,7 @@ class Source(SqlalchemyBase, OrganizationMixin):__pydantic_model__ = PydanticSource__table_args__ = (- Index(f"source_created_at_id_idx", "created_at", "id"),+ Index("source_created_at_id_idx", "created_at", "id"),UniqueConstraint("name", "organization_id", name="uq_source_name_organization"),{"extend_existing": True},)diff --git a/letta/orm/sqlalchemy_base.py b/letta/orm/sqlalchemy_base.pyindex 368d5e300..f9ee74529 100644--- a/letta/orm/sqlalchemy_base.py+++ b/letta/orm/sqlalchemy_base.py@@ -5,7 +5,7 @@ from functools import wrapsfrom pprint import pformatfrom typing import TYPE_CHECKING, List, Literal, Optional, Tuple, Union-from sqlalchemy import Sequence, String, and_, delete, func, or_, select, text+from sqlalchemy import Sequence, String, and_, delete, func, or_, selectfrom sqlalchemy.exc import DBAPIError, IntegrityError, TimeoutErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import Mapped, Session, mapped_column@@ -15,6 +15,7 @@ from letta.log import get_loggerfrom letta.orm.base import Base, CommonSqlalchemyMetaMixinsfrom letta.orm.errors import DatabaseTimeoutError, ForeignKeyConstraintViolationError, NoResultFound, UniqueConstraintViolationErrorfrom letta.orm.sqlite_functions import adapt_array+from letta.settings import DatabaseChoiceif TYPE_CHECKING:from pydantic import BaseModel@@ -353,10 +354,12 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):if before_obj and after_obj:# Window-based query - get records between before and after- conditions = [- or_(cls.created_at < before_obj.created_at, and_(cls.created_at == before_obj.created_at, cls.id < before_obj.id)),- or_(cls.created_at > after_obj.created_at, and_(cls.created_at == after_obj.created_at, cls.id > after_obj.id)),- ]+ conditions.append(+ or_(cls.created_at < before_obj.created_at, and_(cls.created_at == before_obj.created_at, cls.id < before_obj.id))+ )+ conditions.append(+ or_(cls.created_at > after_obj.created_at, and_(cls.created_at == after_obj.created_at, cls.id > after_obj.id))+ )else:# Pure pagination queryif before_obj:@@ -393,7 +396,7 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):from letta.settings import settings- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:# PostgreSQL with pgvectorquery = query.order_by(cls.embedding.cosine_distance(query_embedding).asc())else:@@ -509,14 +512,9 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):query, query_conditions = cls._read_multiple_preprocess(identifiers, actor, access, access_type, check_is_deleted, **kwargs)if query is None:raise NoResultFound(f"{cls.__name__} not found with identifier {identifier}")- if is_postgresql_session(db_session):- await db_session.execute(text("SET LOCAL enable_seqscan = OFF"))- try:- result = await db_session.execute(query)- item = result.scalar_one_or_none()- finally:- if is_postgresql_session(db_session):- await db_session.execute(text("SET LOCAL enable_seqscan = ON"))++ result = await db_session.execute(query)+ item = result.scalar_one_or_none()if item is None:raise NoResultFound(f"{cls.__name__} not found with {', '.join(query_conditions if query_conditions else ['no conditions'])}")@@ -656,7 +654,13 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):self._handle_dbapi_error(e)@handle_db_timeout- async def create_async(self, db_session: "AsyncSession", actor: Optional["User"] = None, no_commit: bool = False) -> "SqlalchemyBase":+ async def create_async(+ self,+ db_session: "AsyncSession",+ actor: Optional["User"] = None,+ no_commit: bool = False,+ no_refresh: bool = False,+ ) -> "SqlalchemyBase":"""Async version of create function"""logger.debug(f"Creating {self.__class__.__name__} with ID: {self.id} with actor={actor}")@@ -668,7 +672,9 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):await db_session.flush() # no commit, just flush to get PKelse:await db_session.commit()- await db_session.refresh(self)++ if not no_refresh:+ await db_session.refresh(self)return selfexcept (DBAPIError, IntegrityError) as e:self._handle_dbapi_error(e)@@ -717,7 +723,12 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):@classmethod@handle_db_timeoutasync def batch_create_async(- cls, items: List["SqlalchemyBase"], db_session: "AsyncSession", actor: Optional["User"] = None+ cls,+ items: List["SqlalchemyBase"],+ db_session: "AsyncSession",+ actor: Optional["User"] = None,+ no_commit: bool = False,+ no_refresh: bool = False,) -> List["SqlalchemyBase"]:"""Async version of batch_create method.@@ -726,10 +737,13 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):items: List of model instances to createdb_session: AsyncSession sessionactor: Optional user performing the action+ no_commit: Whether to commit the transaction+ no_refresh: Whether to refresh the created objectsReturns:List of created model instances"""logger.debug(f"Async batch creating {len(items)} {cls.__name__} items with actor={actor}")+if not items:return []@@ -740,21 +754,22 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):try:db_session.add_all(items)- await db_session.flush() # Flush to generate IDs but don't commit yet-- # Collect IDs to fetch the complete objects after commit- item_ids = [item.id for item in items]-- await db_session.commit()-- # Re-query the objects to get them with relationships loaded- query = select(cls).where(cls.id.in_(item_ids))- if hasattr(cls, "created_at"):- query = query.order_by(cls.created_at)+ if no_commit:+ await db_session.flush()+ else:+ await db_session.commit()- result = await db_session.execute(query)- return list(result.scalars())+ if no_refresh:+ return items+ else:+ # Re-query the objects to get them with relationships loaded+ item_ids = [item.id for item in items]+ query = select(cls).where(cls.id.in_(item_ids))+ if hasattr(cls, "created_at"):+ query = query.order_by(cls.created_at)+ result = await db_session.execute(query)+ return list(result.scalars())except (DBAPIError, IntegrityError) as e:cls._handle_dbapi_error(e)@@ -854,20 +869,27 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):return self@handle_db_timeout- async def update_async(self, db_session: AsyncSession, actor: "User | None" = None, no_commit: bool = False) -> "SqlalchemyBase":+ async def update_async(+ self, db_session: "AsyncSession", actor: Optional["User"] = None, no_commit: bool = False, no_refresh: bool = False+ ) -> "SqlalchemyBase":"""Async version of update function"""- logger.debug(...)+ logger.debug(f"Updating {self.__class__.__name__} with ID: {self.id} with actor={actor}")+if actor:self._set_created_and_updated_by_fields(actor.id)self.set_updated_at()+ try:+ db_session.add(self)+ if no_commit:+ await db_session.flush()+ else:+ await db_session.commit()- db_session.add(self)- if no_commit:- await db_session.flush()- else:- await db_session.commit()- await db_session.refresh(self)- return self+ if not no_refresh:+ await db_session.refresh(self)+ return self+ except (DBAPIError, IntegrityError) as e:+ self._handle_dbapi_error(e)@classmethoddef _size_preprocess(diff --git a/letta/orm/step.py b/letta/orm/step.pyindex 85d2afae8..05da631c2 100644--- a/letta/orm/step.py+++ b/letta/orm/step.py@@ -5,6 +5,7 @@ from sqlalchemy import JSON, ForeignKey, Stringfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom letta.orm.sqlalchemy_base import SqlalchemyBase+from letta.schemas.letta_stop_reason import StopReasonTypefrom letta.schemas.step import Step as PydanticStepif TYPE_CHECKING:@@ -45,6 +46,7 @@ class Step(SqlalchemyBase):prompt_tokens: Mapped[int] = mapped_column(default=0, doc="Number of tokens in the prompt")total_tokens: Mapped[int] = mapped_column(default=0, doc="Total number of tokens processed by the agent")completion_tokens_details: Mapped[Optional[Dict]] = mapped_column(JSON, nullable=True, doc="metadata for the agent.")+ stop_reason: Mapped[Optional[StopReasonType]] = mapped_column(None, nullable=True, doc="The stop reason associated with this step.")tags: Mapped[Optional[List]] = mapped_column(JSON, doc="Metadata tags.")tid: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="Transaction ID that processed the step.")trace_id: Mapped[Optional[str]] = mapped_column(None, nullable=True, doc="The trace id of the agent step.")diff --git a/letta/otel/db_pool_monitoring.py b/letta/otel/db_pool_monitoring.pynew file mode 100644index 000000000..3d04f25fd--- /dev/null+++ b/letta/otel/db_pool_monitoring.py@@ -0,0 +1,308 @@+import time+from typing import Any++from sqlalchemy import Engine, PoolProxiedConnection, QueuePool, event+from sqlalchemy.engine.interfaces import DBAPIConnection+from sqlalchemy.ext.asyncio import AsyncEngine+from sqlalchemy.pool import ConnectionPoolEntry, Pool++from letta.helpers.datetime_helpers import get_utc_timestamp_ns, ns_to_ms+from letta.log import get_logger+from letta.otel.context import get_ctx_attributes++logger = get_logger(__name__)+++class DatabasePoolMonitor:+ """Monitor database connection pool metrics and events using SQLAlchemy event listeners."""++ def __init__(self):+ self._active_connections: dict[int, dict[str, Any]] = {}+ self._pool_stats: dict[str, dict[str, Any]] = {}++ def setup_monitoring(self, engine: Engine | AsyncEngine, engine_name: str = "default") -> None:+ """Set up connection pool monitoring for the given engine."""+ if not hasattr(engine, "pool"):+ logger.warning(f"Engine {engine_name} does not have a pool attribute")+ return++ try:+ self._setup_pool_listeners(engine.pool, engine_name)+ logger.info(f"Database pool monitoring initialized for engine: {engine_name}")+ except Exception as e:+ logger.error(f"Failed to setup pool monitoring for {engine_name}: {e}")++ def _setup_pool_listeners(self, pool: Pool, engine_name: str) -> None:+ """Set up event listeners for the connection pool."""++ @event.listens_for(pool, "connect")+ def on_connect(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry):+ """Called when a new connection is created."""+ connection_id = id(connection_record)++ self._active_connections[connection_id] = {+ "engine_name": engine_name,+ "created_at": time.time(),+ "checked_out_at": None,+ "checked_in_at": None,+ "checkout_count": 0,+ }++ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "connect",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ except Exception as e:+ logger.info(f"Failed to record connection event metric: {e}")++ @event.listens_for(pool, "first_connect")+ def on_first_connect(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry):+ """Called when the first connection is created."""+ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "first_connect",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ logger.info(f"First connection established for engine: {engine_name}")+ except Exception as e:+ logger.info(f"Failed to record first_connect event metric: {e}")++ @event.listens_for(pool, "checkout")+ def on_checkout(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, connection_proxy: PoolProxiedConnection):+ """Called when a connection is checked out from the pool."""+ connection_id = id(connection_record)+ checkout_start_ns = get_utc_timestamp_ns()++ if connection_id in self._active_connections:+ self._active_connections[connection_id]["checked_out_at_ns"] = checkout_start_ns+ self._active_connections[connection_id]["checkout_count"] += 1++ try:+ from letta.otel.metric_registry import MetricRegistry++ # Record current pool statistics+ pool_stats = self._get_pool_stats(pool)+ attrs = {+ "engine_name": engine_name,+ **get_ctx_attributes(),+ }++ MetricRegistry().db_pool_connections_checked_out_gauge.set(pool_stats["checked_out"], attributes=attrs)+ MetricRegistry().db_pool_connections_available_gauge.set(pool_stats["available"], attributes=attrs)+ MetricRegistry().db_pool_connections_total_gauge.set(pool_stats["total"], attributes=attrs)+ if pool_stats["overflow"] is not None:+ MetricRegistry().db_pool_connections_overflow_gauge.set(pool_stats["overflow"], attributes=attrs)++ # Record checkout event+ attrs["event"] = "checkout"+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)++ except Exception as e:+ logger.info(f"Failed to record checkout event metric: {e}")++ @event.listens_for(pool, "checkin")+ def on_checkin(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry):+ """Called when a connection is checked back into the pool."""+ connection_id = id(connection_record)+ checkin_time_ns = get_utc_timestamp_ns()++ if connection_id in self._active_connections:+ conn_info = self._active_connections[connection_id]+ conn_info["checkin_time_ns"] = checkin_time_ns++ # Calculate connection duration if we have checkout time+ if conn_info["checked_out_at_ns"]:+ duration_ms = ns_to_ms(checkin_time_ns - conn_info["checked_out_at_ns"])++ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_duration_ms_histogram.record(duration_ms, attributes=attrs)+ except Exception as e:+ logger.info(f"Failed to record connection duration metric: {e}")++ try:+ from letta.otel.metric_registry import MetricRegistry++ # Record current pool statistics after checkin+ pool_stats = self._get_pool_stats(pool)+ attrs = {+ "engine_name": engine_name,+ **get_ctx_attributes(),+ }++ MetricRegistry().db_pool_connections_checked_out_gauge.set(pool_stats["checked_out"], attributes=attrs)+ MetricRegistry().db_pool_connections_available_gauge.set(pool_stats["available"], attributes=attrs)++ # Record checkin event+ attrs["event"] = "checkin"+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)++ except Exception as e:+ logger.info(f"Failed to record checkin event metric: {e}")++ @event.listens_for(pool, "invalidate")+ def on_invalidate(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, exception):+ """Called when a connection is invalidated."""+ connection_id = id(connection_record)++ if connection_id in self._active_connections:+ del self._active_connections[connection_id]++ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "invalidate",+ "exception_type": type(exception).__name__ if exception else "unknown",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ MetricRegistry().db_pool_connection_errors_counter.add(1, attributes=attrs)+ except Exception as e:+ logger.info(f"Failed to record invalidate event metric: {e}")++ @event.listens_for(pool, "soft_invalidate")+ def on_soft_invalidate(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, exception):+ """Called when a connection is soft invalidated."""+ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "soft_invalidate",+ "exception_type": type(exception).__name__ if exception else "unknown",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ logger.debug(f"Connection soft invalidated for engine: {engine_name}")+ except Exception as e:+ logger.info(f"Failed to record soft_invalidate event metric: {e}")++ @event.listens_for(pool, "close")+ def on_close(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry):+ """Called when a connection is closed."""+ connection_id = id(connection_record)++ if connection_id in self._active_connections:+ del self._active_connections[connection_id]++ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "close",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ except Exception as e:+ logger.info(f"Failed to record close event metric: {e}")++ @event.listens_for(pool, "close_detached")+ def on_close_detached(dbapi_connection: DBAPIConnection):+ """Called when a detached connection is closed."""+ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "close_detached",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ logger.debug(f"Detached connection closed for engine: {engine_name}")+ except Exception as e:+ logger.info(f"Failed to record close_detached event metric: {e}")++ @event.listens_for(pool, "detach")+ def on_detach(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry):+ """Called when a connection is detached from the pool."""+ connection_id = id(connection_record)++ if connection_id in self._active_connections:+ self._active_connections[connection_id]["detached"] = True++ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "detach",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ logger.debug(f"Connection detached from pool for engine: {engine_name}")+ except Exception as e:+ logger.info(f"Failed to record detach event metric: {e}")++ @event.listens_for(pool, "reset")+ def on_reset(dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry):+ """Called when a connection is reset."""+ try:+ from letta.otel.metric_registry import MetricRegistry++ attrs = {+ "engine_name": engine_name,+ "event": "reset",+ **get_ctx_attributes(),+ }+ MetricRegistry().db_pool_connection_events_counter.add(1, attributes=attrs)+ logger.debug(f"Connection reset for engine: {engine_name}")+ except Exception as e:+ logger.info(f"Failed to record reset event metric: {e}")++ # Note: dispatch is not a listenable event, it's a method for custom events+ # If you need to track custom dispatch events, you would need to implement them separately++ # noinspection PyProtectedMember+ @staticmethod+ def _get_pool_stats(pool: Pool) -> dict[str, Any]:+ """Get current pool statistics."""+ stats = {+ "total": 0,+ "checked_out": 0,+ "available": 0,+ "overflow": None,+ }++ try:+ if not isinstance(pool, QueuePool):+ logger.info("Not currently supported for non-QueuePools")++ stats["total"] = pool._pool.maxsize+ stats["available"] = pool._pool.qsize()+ stats["overflow"] = pool._overflow+ stats["checked_out"] = stats["total"] - stats["available"]++ except Exception as e:+ logger.info(f"Failed to get pool stats: {e}")+ return stats+++# Global instance+_pool_monitor = DatabasePoolMonitor()+++def get_pool_monitor() -> DatabasePoolMonitor:+ """Get the global database pool monitor instance."""+ return _pool_monitor+++def setup_pool_monitoring(engine: Engine | AsyncEngine, engine_name: str = "default") -> None:+ """Set up connection pool monitoring for the given engine."""+ _pool_monitor.setup_monitoring(engine, engine_name)diff --git a/letta/otel/metric_registry.py b/letta/otel/metric_registry.pyindex f3069a9e7..add2e0ec3 100644--- a/letta/otel/metric_registry.py+++ b/letta/otel/metric_registry.py@@ -3,6 +3,7 @@ from functools import partialfrom opentelemetry import metricsfrom opentelemetry.metrics import Counter, Histogram+from opentelemetry.metrics._internal import Gaugefrom letta.helpers.singleton import singletonfrom letta.otel.metrics import get_letta_meter@@ -27,7 +28,7 @@ class MetricRegistry:agent_id -1:N -> tool_name"""- Instrument = Counter | Histogram+ Instrument = Counter | Histogram | Gauge_metrics: dict[str, Instrument] = field(default_factory=dict, init=False)_meter: metrics.Meter = field(init=False)@@ -180,3 +181,95 @@ class MetricRegistry:unit="By",),)++ # Database connection pool metrics+ # (includes engine_name)+ @property+ def db_pool_connections_total_gauge(self) -> Gauge:+ return self._get_or_create_metric(+ "gauge_db_pool_connections_total",+ partial(+ self._meter.create_gauge,+ name="gauge_db_pool_connections_total",+ description="Total number of connections in the database pool",+ unit="1",+ ),+ )++ # (includes engine_name)+ @property+ def db_pool_connections_checked_out_gauge(self) -> Gauge:+ return self._get_or_create_metric(+ "gauge_db_pool_connections_checked_out",+ partial(+ self._meter.create_gauge,+ name="gauge_db_pool_connections_checked_out",+ description="Number of connections currently checked out from the pool",+ unit="1",+ ),+ )++ # (includes engine_name)+ @property+ def db_pool_connections_available_gauge(self) -> Gauge:+ return self._get_or_create_metric(+ "gauge_db_pool_connections_available",+ partial(+ self._meter.create_gauge,+ name="gauge_db_pool_connections_available",+ description="Number of available connections in the pool",+ unit="1",+ ),+ )++ # (includes engine_name)+ @property+ def db_pool_connections_overflow_gauge(self) -> Gauge:+ return self._get_or_create_metric(+ "gauge_db_pool_connections_overflow",+ partial(+ self._meter.create_gauge,+ name="gauge_db_pool_connections_overflow",+ description="Number of overflow connections in the pool",+ unit="1",+ ),+ )++ # (includes engine_name)+ @property+ def db_pool_connection_duration_ms_histogram(self) -> Histogram:+ return self._get_or_create_metric(+ "hist_db_pool_connection_duration_ms",+ partial(+ self._meter.create_histogram,+ name="hist_db_pool_connection_duration_ms",+ description="Duration of database connection usage in milliseconds",+ unit="ms",+ ),+ )++ # (includes engine_name, event)+ @property+ def db_pool_connection_events_counter(self) -> Counter:+ return self._get_or_create_metric(+ "count_db_pool_connection_events",+ partial(+ self._meter.create_counter,+ name="count_db_pool_connection_events",+ description="Count of database connection pool events (connect, checkout, checkin, invalidate)",+ unit="1",+ ),+ )++ # (includes engine_name, exception_type)+ @property+ def db_pool_connection_errors_counter(self) -> Counter:+ return self._get_or_create_metric(+ "count_db_pool_connection_errors",+ partial(+ self._meter.create_counter,+ name="count_db_pool_connection_errors",+ description="Count of database connection pool errors",+ unit="1",+ ),+ )diff --git a/letta/otel/sqlalchemy_instrumentation.py b/letta/otel/sqlalchemy_instrumentation.pynew file mode 100644index 000000000..ccab73a16--- /dev/null+++ b/letta/otel/sqlalchemy_instrumentation.py@@ -0,0 +1,548 @@+import asyncio+import threading+import traceback+from contextlib import contextmanager+from functools import wraps+from typing import Any, Callable, Dict, List, Optional++from opentelemetry import trace+from opentelemetry.trace import Status, StatusCode+from sqlalchemy import Engine, event+from sqlalchemy.orm import Session+from sqlalchemy.orm.loading import load_on_ident, load_on_pk_identity+from sqlalchemy.orm.strategies import ImmediateLoader, JoinedLoader, LazyLoader, SelectInLoader, SubqueryLoader++_config = {+ "enabled": True,+ "sql_truncate_length": 1000,+ "monitor_joined_loading": True,+ "log_instrumentation_errors": True,+}++_instrumentation_state = {+ "engine_listeners": [],+ "session_listeners": [],+ "original_methods": {},+ "active": False,+}++_context = threading.local()+++def _get_tracer():+ """Get the OpenTelemetry tracer for SQLAlchemy instrumentation."""+ return trace.get_tracer("sqlalchemy_sync_instrumentation", "1.0.0")+++def _is_event_loop_running() -> bool:+ """Check if an asyncio event loop is running in the current thread."""+ try:+ loop = asyncio.get_running_loop()+ return loop.is_running()+ except RuntimeError:+ return False+++def _is_main_thread() -> bool:+ """Check if we're running on the main thread."""+ return threading.current_thread() is threading.main_thread()+++def _truncate_sql(sql: str, max_length: int = 1000) -> str:+ """Truncate SQL statement to specified length."""+ if len(sql) <= max_length:+ return sql+ return sql[: max_length - 3] + "..."+++def _create_sync_db_span(+ operation_type: str,+ sql_statement: Optional[str] = None,+ loader_type: Optional[str] = None,+ relationship_key: Optional[str] = None,+ is_joined: bool = False,+ additional_attrs: Optional[Dict[str, Any]] = None,+) -> Any:+ """+ Create an OpenTelemetry span for a synchronous database operation.++ Args:+ operation_type: Type of database operation+ sql_statement: SQL statement being executed+ loader_type: Type of SQLAlchemy loader (selectin, joined, lazy, etc.)+ relationship_key: Name of relationship attribute if applicable+ is_joined: Whether this is from joined loading+ additional_attrs: Additional attributes to add to the span++ Returns:+ OpenTelemetry span+ """+ if not _config["enabled"]:+ return None++ # Only create spans for potentially problematic operations+ if not _is_event_loop_running():+ return None++ tracer = _get_tracer()+ span = tracer.start_span("db_operation")++ # Set core attributes+ span.set_attribute("db.operation.type", operation_type)++ # SQL statement+ if sql_statement:+ span.set_attribute("db.statement", _truncate_sql(sql_statement, _config["sql_truncate_length"]))++ # Loader information+ if loader_type:+ span.set_attribute("sqlalchemy.loader.type", loader_type)+ span.set_attribute("sqlalchemy.loader.is_joined", is_joined)++ # Relationship information+ if relationship_key:+ span.set_attribute("sqlalchemy.relationship.key", relationship_key)++ # Additional attributes+ if additional_attrs:+ for key, value in additional_attrs.items():+ span.set_attribute(key, value)++ return span+++def _instrument_engine_events(engine: Engine) -> None:+ """Instrument SQLAlchemy engine events to detect sync operations."""++ # Check if this is an AsyncEngine and get its sync_engine if it is+ from sqlalchemy.ext.asyncio import AsyncEngine++ if isinstance(engine, AsyncEngine):+ engine = engine.sync_engine++ def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):+ """Track cursor execution start."""+ if not _config["enabled"]:+ return++ # Store context for the after event+ context._sync_instrumentation_span = _create_sync_db_span(+ operation_type="cursor_execute",+ sql_statement=statement,+ additional_attrs={+ "db.executemany": executemany,+ "db.connection.info": str(conn.info),+ },+ )++ def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):+ """Track cursor execution completion."""+ if not _config["enabled"]:+ return++ span = getattr(context, "_sync_instrumentation_span", None)+ if span:+ span.set_status(Status(StatusCode.OK))+ span.end()+ context._sync_instrumentation_span = None++ def handle_cursor_error(conn, cursor, statement, parameters, context, executemany):+ """Handle cursor execution errors."""+ if not _config["enabled"]:+ return++ span = getattr(context, "_sync_instrumentation_span", None)+ if span:+ span.set_status(Status(StatusCode.ERROR, "Database operation failed"))+ span.end()+ context._sync_instrumentation_span = None++ # Register engine events+ event.listen(engine, "before_cursor_execute", before_cursor_execute)+ event.listen(engine, "after_cursor_execute", after_cursor_execute)+ event.listen(engine, "handle_error", handle_cursor_error)++ # Store listeners for cleanup+ _instrumentation_state["engine_listeners"].extend(+ [+ (engine, "before_cursor_execute", before_cursor_execute),+ (engine, "after_cursor_execute", after_cursor_execute),+ (engine, "handle_error", handle_cursor_error),+ ]+ )+++def _instrument_loader_strategies() -> None:+ """Instrument SQLAlchemy loader strategies to detect lazy loading."""++ def create_loader_wrapper(loader_class: type, loader_type: str, is_joined: bool = False):+ """Create a wrapper for loader strategy methods."""++ def wrapper(original_method: Callable):+ @wraps(original_method)+ def instrumented_method(self, *args, **kwargs):+ # Extract relationship information if available+ relationship_key = getattr(self, "key", None)+ if hasattr(self, "parent_property"):+ relationship_key = getattr(self.parent_property, "key", relationship_key)++ span = _create_sync_db_span(+ operation_type="loader_strategy",+ loader_type=loader_type,+ relationship_key=relationship_key,+ is_joined=is_joined,+ additional_attrs={+ "sqlalchemy.loader.class": loader_class.__name__,+ "sqlalchemy.loader.method": original_method.__name__,+ },+ )++ try:+ result = original_method(self, *args, **kwargs)+ if span:+ span.set_status(Status(StatusCode.OK))+ return result+ except Exception as e:+ if span:+ span.set_status(Status(StatusCode.ERROR, str(e)))+ raise+ finally:+ if span:+ span.end()++ return instrumented_method++ return wrapper++ # Instrument different loader strategies+ loaders_to_instrument = [+ (SelectInLoader, "selectin", False),+ (JoinedLoader, "joined", True),+ (LazyLoader, "lazy", False),+ (SubqueryLoader, "subquery", False),+ (ImmediateLoader, "immediate", False),+ ]++ for loader_class, loader_type, is_joined in loaders_to_instrument:+ # Skip if monitoring joined loading is disabled+ if is_joined and not _config["monitor_joined_loading"]:+ continue++ wrapper = create_loader_wrapper(loader_class, loader_type, is_joined)++ # Instrument key methods+ methods_to_instrument = ["_load_for_path", "load_for_path"]++ for method_name in methods_to_instrument:+ if hasattr(loader_class, method_name):+ original_method = getattr(loader_class, method_name)+ key = f"{loader_class.__name__}.{method_name}"++ # Store original method for cleanup+ _instrumentation_state["original_methods"][key] = original_method++ # Apply wrapper+ setattr(loader_class, method_name, wrapper(original_method))++ # Instrument additional joined loading specific methods+ if _config["monitor_joined_loading"]:+ joined_methods = [+ (JoinedLoader, "_create_eager_join"),+ (JoinedLoader, "_generate_cache_key"),+ ]++ wrapper = create_loader_wrapper(JoinedLoader, "joined", True)++ for loader_class, method_name in joined_methods:+ if hasattr(loader_class, method_name):+ original_method = getattr(loader_class, method_name)+ key = f"{loader_class.__name__}.{method_name}"++ _instrumentation_state["original_methods"][key] = original_method+ setattr(loader_class, method_name, wrapper(original_method))+++def _instrument_loading_functions() -> None:+ """Instrument SQLAlchemy loading functions."""++ def create_loading_wrapper(func_name: str):+ """Create a wrapper for loading functions."""++ def wrapper(original_func: Callable):+ @wraps(original_func)+ def instrumented_func(*args, **kwargs):+ span = _create_sync_db_span(+ operation_type="loading_function",+ additional_attrs={+ "sqlalchemy.loading.function": func_name,+ },+ )++ try:+ result = original_func(*args, **kwargs)+ if span:+ span.set_status(Status(StatusCode.OK))+ return result+ except Exception as e:+ if span:+ span.set_status(Status(StatusCode.ERROR, str(e)))+ raise+ finally:+ if span:+ span.end()++ return instrumented_func++ return wrapper++ # Instrument loading functions+ import sqlalchemy.orm.loading as loading_module++ functions_to_instrument = [+ (loading_module, "load_on_ident", load_on_ident),+ (loading_module, "load_on_pk_identity", load_on_pk_identity),+ ]++ for module, func_name, original_func in functions_to_instrument:+ wrapper = create_loading_wrapper(func_name)++ # Store original function for cleanup+ _instrumentation_state["original_methods"][f"loading.{func_name}"] = original_func++ # Apply wrapper+ setattr(module, func_name, wrapper(original_func))+++def _instrument_session_operations() -> None:+ """Instrument SQLAlchemy session operations."""++ def before_flush(session, flush_context, instances):+ """Track session flush operations."""+ if not _config["enabled"]:+ return++ span = _create_sync_db_span(+ operation_type="session_flush",+ additional_attrs={+ "sqlalchemy.session.new_count": len(session.new),+ "sqlalchemy.session.dirty_count": len(session.dirty),+ "sqlalchemy.session.deleted_count": len(session.deleted),+ },+ )++ # Store span in session for cleanup+ session._sync_instrumentation_flush_span = span++ def after_flush(session, flush_context):+ """Track session flush completion."""+ if not _config["enabled"]:+ return++ span = getattr(session, "_sync_instrumentation_flush_span", None)+ if span:+ span.set_status(Status(StatusCode.OK))+ span.end()+ session._sync_instrumentation_flush_span = None++ def after_flush_postexec(session, flush_context):+ """Track session flush post-execution."""+ if not _config["enabled"]:+ return++ span = getattr(session, "_sync_instrumentation_flush_span", None)+ if span:+ span.set_status(Status(StatusCode.OK))+ span.end()+ session._sync_instrumentation_flush_span = None++ # Register session events+ event.listen(Session, "before_flush", before_flush)+ event.listen(Session, "after_flush", after_flush)+ event.listen(Session, "after_flush_postexec", after_flush_postexec)++ # Store listeners for cleanup+ _instrumentation_state["session_listeners"].extend(+ [+ (Session, "before_flush", before_flush),+ (Session, "after_flush", after_flush),+ (Session, "after_flush_postexec", after_flush_postexec),+ ]+ )+++def setup_sqlalchemy_sync_instrumentation(+ engines: Optional[List[Engine]] = None,+ config_overrides: Optional[Dict[str, Any]] = None,+ lazy_loading_only: bool = True,+) -> None:+ """+ Set up SQLAlchemy synchronous operation instrumentation.++ Args:+ engines: List of SQLAlchemy engines to instrument. If None, will attempt+ to discover engines automatically.+ config_overrides: Dictionary of configuration overrides.+ lazy_loading_only: If True, only instrument lazy loading operations.+ """+ if _instrumentation_state["active"]:+ return # Already active++ try:+ # Apply configuration overrides+ if config_overrides:+ _config.update(config_overrides)++ # If lazy_loading_only is True, update config to focus on lazy loading+ if lazy_loading_only:+ _config.update(+ {+ "monitor_joined_loading": False, # Don't monitor joined loading+ }+ )++ # Discover engines if not provided+ if engines is None:+ engines = []+ # Try to find engines from the database registry+ try:+ from letta.server.db import db_registry++ if hasattr(db_registry, "_async_engines"):+ engines.extend(db_registry._async_engines.values())+ if hasattr(db_registry, "_sync_engines"):+ engines.extend(db_registry._sync_engines.values())+ except ImportError:+ pass++ # Instrument loader strategies (focus on lazy loading if specified)+ _instrument_loader_strategies()++ # Instrument loading functions+ _instrument_loading_functions()++ # Instrument session operations+ _instrument_session_operations()++ # Instrument engines last to avoid potential errors with async engines+ for engine in engines:+ try:+ _instrument_engine_events(engine)+ except Exception as e:+ if _config["log_instrumentation_errors"]:+ print(f"Error instrumenting engine {engine}: {e}")+ # Continue with other engines++ _instrumentation_state["active"] = True++ except Exception as e:+ if _config["log_instrumentation_errors"]:+ print(f"Error setting up SQLAlchemy instrumentation: {e}")+ import traceback++ traceback.print_exc()+ raise+++def teardown_sqlalchemy_sync_instrumentation() -> None:+ """Tear down SQLAlchemy synchronous operation instrumentation."""+ if not _instrumentation_state["active"]:+ return # Not active++ try:+ # Remove engine listeners+ for engine, event_name, listener in _instrumentation_state["engine_listeners"]:+ event.remove(engine, event_name, listener)++ # Remove session listeners+ for target, event_name, listener in _instrumentation_state["session_listeners"]:+ event.remove(target, event_name, listener)++ # Restore original methods+ for key, original_method in _instrumentation_state["original_methods"].items():+ if "." in key:+ module_or_class_name, method_name = key.rsplit(".", 1)++ if key.startswith("loading."):+ # Restore loading function+ import sqlalchemy.orm.loading as loading_module++ setattr(loading_module, method_name, original_method)+ else:+ # Restore class method+ class_name = module_or_class_name+ # Find the class+ for cls in [SelectInLoader, JoinedLoader, LazyLoader, SubqueryLoader, ImmediateLoader]:+ if cls.__name__ == class_name:+ setattr(cls, method_name, original_method)+ break++ # Clear state+ _instrumentation_state["engine_listeners"].clear()+ _instrumentation_state["session_listeners"].clear()+ _instrumentation_state["original_methods"].clear()+ _instrumentation_state["active"] = False++ except Exception as e:+ if _config["log_instrumentation_errors"]:+ print(f"Error tearing down SQLAlchemy instrumentation: {e}")+ traceback.print_exc()+ raise+++def configure_instrumentation(**kwargs) -> None:+ """+ Configure SQLAlchemy synchronous operation instrumentation.++ Args:+ **kwargs: Configuration options to update.+ """+ _config.update(kwargs)+++def get_instrumentation_config() -> Dict[str, Any]:+ """Get current instrumentation configuration."""+ return _config.copy()+++def is_instrumentation_active() -> bool:+ """Check if instrumentation is currently active."""+ return _instrumentation_state["active"]+++# Context manager for temporary instrumentation+@contextmanager+def temporary_instrumentation(**config_overrides):+ """+ Context manager for temporary SQLAlchemy instrumentation.++ Args:+ **config_overrides: Configuration overrides for the instrumentation.+ """+ was_active = _instrumentation_state["active"]++ if not was_active:+ setup_sqlalchemy_sync_instrumentation(config_overrides=config_overrides)++ try:+ yield+ finally:+ if not was_active:+ teardown_sqlalchemy_sync_instrumentation()+++# FastAPI integration helper+def setup_fastapi_instrumentation(app):+ """+ Set up SQLAlchemy instrumentation for FastAPI application.++ Args:+ app: FastAPI application instance+ """++ @app.on_event("startup")+ async def startup_instrumentation():+ setup_sqlalchemy_sync_instrumentation()++ @app.on_event("shutdown")+ async def shutdown_instrumentation():+ teardown_sqlalchemy_sync_instrumentation()diff --git a/letta/otel/sqlalchemy_instrumentation_integration.py b/letta/otel/sqlalchemy_instrumentation_integration.pynew file mode 100644index 000000000..fe05d3a4f--- /dev/null+++ b/letta/otel/sqlalchemy_instrumentation_integration.py@@ -0,0 +1,124 @@+"""+Integration module for SQLAlchemy synchronous operation instrumentation.++This module provides easy integration with the existing Letta application,+including automatic discovery of database engines and integration with+the existing OpenTelemetry setup.+"""++import logging+from typing import Any, Dict, Optional++from letta.otel.sqlalchemy_instrumentation import (+ configure_instrumentation,+ get_instrumentation_config,+ is_instrumentation_active,+ setup_sqlalchemy_sync_instrumentation,+ teardown_sqlalchemy_sync_instrumentation,+)+from letta.server.db import db_registry++logger = logging.getLogger(__name__)+++def setup_letta_db_instrumentation(+ enable_joined_monitoring: bool = True,+ sql_truncate_length: int = 1000,+ additional_config: Optional[Dict[str, Any]] = None,+) -> None:+ """+ Set up SQLAlchemy instrumentation for Letta application.++ Args:+ enable_joined_monitoring: Whether to monitor joined loading operations+ sql_truncate_length: Maximum length of SQL statements in traces+ additional_config: Additional configuration options+ """+ if is_instrumentation_active():+ logger.info("SQLAlchemy instrumentation already active")+ return++ # Build configuration+ config = {+ "enabled": True,+ "monitor_joined_loading": enable_joined_monitoring,+ "sql_truncate_length": sql_truncate_length,+ "log_instrumentation_errors": True,+ }++ if additional_config:+ config.update(additional_config)++ # Get engines from db_registry+ engines = []+ try:+ if hasattr(db_registry, "_async_engines"):+ engines.extend(db_registry._async_engines.values())+ if hasattr(db_registry, "_sync_engines"):+ engines.extend(db_registry._sync_engines.values())+ except Exception as e:+ logger.warning(f"Could not discover engines from db_registry: {e}")++ if not engines:+ logger.warning("No SQLAlchemy engines found for instrumentation")+ return++ try:+ setup_sqlalchemy_sync_instrumentation(+ engines=engines,+ config_overrides=config,+ )+ logger.info(f"SQLAlchemy instrumentation setup complete for {len(engines)} engines")++ # Log configuration+ logger.info("Instrumentation configuration:")+ for key, value in get_instrumentation_config().items():+ logger.info(f" {key}: {value}")++ except Exception as e:+ logger.error(f"Failed to setup SQLAlchemy instrumentation: {e}")+ raise+++def teardown_letta_db_instrumentation() -> None:+ """Tear down SQLAlchemy instrumentation for Letta application."""+ if not is_instrumentation_active():+ logger.info("SQLAlchemy instrumentation not active")+ return++ try:+ teardown_sqlalchemy_sync_instrumentation()+ logger.info("SQLAlchemy instrumentation teardown complete")+ except Exception as e:+ logger.error(f"Failed to teardown SQLAlchemy instrumentation: {e}")+ raise+++def configure_letta_db_instrumentation(**kwargs) -> None:+ """+ Configure SQLAlchemy instrumentation for Letta application.++ Args:+ **kwargs: Configuration options to update+ """+ configure_instrumentation(**kwargs)+ logger.info(f"SQLAlchemy instrumentation configuration updated: {kwargs}")+++# FastAPI integration+def setup_fastapi_db_instrumentation(app, **config_kwargs):+ """+ Set up SQLAlchemy instrumentation for FastAPI application.++ Args:+ app: FastAPI application instance+ **config_kwargs: Configuration options for instrumentation+ """++ @app.on_event("startup")+ async def startup_db_instrumentation():+ setup_letta_db_instrumentation(**config_kwargs)++ @app.on_event("shutdown")+ async def shutdown_db_instrumentation():+ teardown_letta_db_instrumentation()diff --git a/letta/otel/tracing.py b/letta/otel/tracing.pyindex 05cd485a8..db22d0135 100644--- a/letta/otel/tracing.py+++ b/letta/otel/tracing.py@@ -143,7 +143,43 @@ def setup_tracing(if settings.sqlalchemy_tracing:from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor- SQLAlchemyInstrumentor().instrument()+ from letta.server.db import db_registry++ # For OpenTelemetry SQLAlchemy instrumentation, we need to use the sync_engine+ async_engine = db_registry.get_async_engine()+ if async_engine:+ # Access the sync_engine attribute safely+ try:+ SQLAlchemyInstrumentor().instrument(+ engine=async_engine.sync_engine,+ enable_commenter=True,+ commenter_options={},+ enable_attribute_commenter=True,+ )+ except Exception:+ # Fall back to instrumenting without specifying an engine+ # This will still capture some SQL operations+ SQLAlchemyInstrumentor().instrument(+ enable_commenter=True,+ commenter_options={},+ enable_attribute_commenter=True,+ )+ else:+ # If no async engine is available, instrument without an engine+ SQLAlchemyInstrumentor().instrument(+ enable_commenter=True,+ commenter_options={},+ enable_attribute_commenter=True,+ )++ # Additionally set up our custom instrumentation+ try:+ from letta.otel.sqlalchemy_instrumentation_integration import setup_letta_db_instrumentation++ setup_letta_db_instrumentation(enable_joined_monitoring=True)+ except Exception as e:+ # Log but continue if our custom instrumentation fails+ logger.warning(f"Failed to setup Letta DB instrumentation: {e}")if app:# Add middleware firstdiff --git a/letta/schemas/agent.py b/letta/schemas/agent.pyindex 8bceac98c..2ffd41391 100644--- a/letta/schemas/agent.py+++ b/letta/schemas/agent.py@@ -78,8 +78,6 @@ class AgentState(OrmMetadataBase, validate_assignment=True):# This is an object representing the in-process state of a running `Agent`# Field in this object can be theoretically edited by tools, and will be persisted by the ORM- organization_id: Optional[str] = Field(None, description="The unique identifier of the organization associated with the agent.")-description: Optional[str] = Field(None, description="The description of the agent.")metadata: Optional[Dict] = Field(None, description="The metadata of the agent.")@@ -309,7 +307,6 @@ class AgentStepResponse(BaseModel):def get_prompt_template_for_agent_type(agent_type: Optional[AgentType] = None):-# Workflow agents and ReAct agents don't use memory blocks# However, they still allow files to be injected into the contextif agent_type == AgentType.react_agent or agent_type == AgentType.workflow_agent:diff --git a/letta/schemas/agent_file.py b/letta/schemas/agent_file.pynew file mode 100644index 000000000..c9a18072f--- /dev/null+++ b/letta/schemas/agent_file.py@@ -0,0 +1,283 @@+from datetime import datetime+from typing import Dict, List, Optional++from pydantic import BaseModel, Field++from letta.schemas.agent import AgentState, CreateAgent+from letta.schemas.block import Block, CreateBlock+from letta.schemas.enums import MessageRole+from letta.schemas.file import FileAgent, FileAgentBase, FileMetadata, FileMetadataBase+from letta.schemas.group import GroupCreate+from letta.schemas.message import Message, MessageCreate+from letta.schemas.source import Source, SourceCreate+from letta.schemas.tool import Tool+from letta.schemas.user import User+from letta.services.message_manager import MessageManager+++class ImportResult:+ """Result of an agent file import operation"""++ def __init__(+ self,+ success: bool,+ message: str = "",+ imported_count: int = 0,+ errors: Optional[List[str]] = None,+ id_mappings: Optional[Dict[str, str]] = None,+ ):+ self.success = success+ self.message = message+ self.imported_count = imported_count+ self.errors = errors or []+ self.id_mappings = id_mappings or {}+++class MessageSchema(MessageCreate):+ """Message with human-readable ID for agent file"""++ __id_prefix__ = "message"+ id: str = Field(..., description="Human-readable identifier for this message in the file")++ # Override the role field to accept all message roles, not just user/system/assistant+ role: MessageRole = Field(..., description="The role of the participant.")+ model: Optional[str] = Field(None, description="The model used to make the function call")+ agent_id: Optional[str] = Field(None, description="The unique identifier of the agent")++ @classmethod+ def from_message(cls, message: Message) -> "MessageSchema":+ """Convert Message to MessageSchema"""++ # Create MessageSchema directly without going through MessageCreate+ # to avoid role validation issues+ return cls(+ id=message.id,+ role=message.role,+ content=message.content,+ name=message.name,+ otid=None, # TODO+ sender_id=None, # TODO+ batch_item_id=message.batch_item_id,+ group_id=message.group_id,+ model=message.model,+ agent_id=message.agent_id,+ )+++class FileAgentSchema(FileAgentBase):+ """File-Agent relationship with human-readable ID for agent file"""++ __id_prefix__ = "file_agent"+ id: str = Field(..., description="Human-readable identifier for this file-agent relationship in the file")++ @classmethod+ def from_file_agent(cls, file_agent: FileAgent) -> "FileAgentSchema":+ """Convert FileAgent to FileAgentSchema"""++ create_file_agent = FileAgentBase(+ agent_id=file_agent.agent_id,+ file_id=file_agent.file_id,+ source_id=file_agent.source_id,+ file_name=file_agent.file_name,+ is_open=file_agent.is_open,+ visible_content=file_agent.visible_content,+ last_accessed_at=file_agent.last_accessed_at,+ )++ # Create FileAgentSchema with the file_agent's ID (will be remapped later)+ return cls(id=file_agent.id, **create_file_agent.model_dump())+++class AgentSchema(CreateAgent):+ """Agent with human-readable ID for agent file"""++ __id_prefix__ = "agent"+ id: str = Field(..., description="Human-readable identifier for this agent in the file")+ in_context_message_ids: List[str] = Field(+ default_factory=list, description="List of message IDs that are currently in the agent's context"+ )+ messages: List[MessageSchema] = Field(default_factory=list, description="List of messages in the agent's conversation history")+ files_agents: List[FileAgentSchema] = Field(default_factory=list, description="List of file-agent relationships for this agent")++ @classmethod+ async def from_agent_state(+ cls, agent_state: AgentState, message_manager: MessageManager, files_agents: List[FileAgent], actor: User+ ) -> "AgentSchema":+ """Convert AgentState to AgentSchema"""++ create_agent = CreateAgent(+ name=agent_state.name,+ memory_blocks=[], # TODO: Convert from agent_state.memory if needed+ tools=[],+ tool_ids=[tool.id for tool in agent_state.tools] if agent_state.tools else [],+ source_ids=[], # [source.id for source in agent_state.sources] if agent_state.sources else [],+ block_ids=[block.id for block in agent_state.memory.blocks],+ tool_rules=agent_state.tool_rules,+ tags=agent_state.tags,+ system=agent_state.system,+ agent_type=agent_state.agent_type,+ llm_config=agent_state.llm_config,+ embedding_config=agent_state.embedding_config,+ initial_message_sequence=None,+ include_base_tools=False,+ include_multi_agent_tools=False,+ include_base_tool_rules=False,+ include_default_source=False,+ description=agent_state.description,+ metadata=agent_state.metadata,+ model=None,+ embedding=None,+ context_window_limit=None,+ embedding_chunk_size=None,+ max_tokens=None,+ max_reasoning_tokens=None,+ enable_reasoner=False,+ from_template=None, # TODO: Need to get passed in+ template=False, # TODO: Need to get passed in+ project=None, # TODO: Need to get passed in+ tool_exec_environment_variables=agent_state.get_agent_env_vars_as_dict(),+ memory_variables=None, # TODO: Need to get passed in+ project_id=None, # TODO: Need to get passed in+ template_id=None, # TODO: Need to get passed in+ base_template_id=None, # TODO: Need to get passed in+ identity_ids=None, # TODO: Need to get passed in+ message_buffer_autoclear=agent_state.message_buffer_autoclear,+ enable_sleeptime=False, # TODO: Need to figure out how to patch this+ response_format=agent_state.response_format,+ timezone=agent_state.timezone or "UTC",+ )++ messages = await message_manager.list_messages_for_agent_async(+ agent_id=agent_state.id, actor=actor, limit=50+ ) # TODO: Expand to get more messages++ # Convert messages to MessageSchema objects+ message_schemas = [MessageSchema.from_message(msg) for msg in messages]++ # Create AgentSchema with agent state ID (remapped later)+ return cls(+ id=agent_state.id,+ in_context_message_ids=agent_state.message_ids or [],+ messages=message_schemas, # Messages will be populated separately by the manager+ files_agents=[FileAgentSchema.from_file_agent(f) for f in files_agents],+ **create_agent.model_dump(),+ )+++class GroupSchema(GroupCreate):+ """Group with human-readable ID for agent file"""++ __id_prefix__ = "group"+ id: str = Field(..., description="Human-readable identifier for this group in the file")+++class BlockSchema(CreateBlock):+ """Block with human-readable ID for agent file"""++ __id_prefix__ = "block"+ id: str = Field(..., description="Human-readable identifier for this block in the file")++ @classmethod+ def from_block(cls, block: Block) -> "BlockSchema":+ """Convert Block to BlockSchema"""++ create_block = CreateBlock(+ value=block.value,+ limit=block.limit,+ template_name=block.template_name,+ is_template=block.is_template,+ preserve_on_migration=block.preserve_on_migration,+ label=block.label,+ read_only=block.read_only,+ description=block.description,+ metadata=block.metadata or {},+ )++ # Create BlockSchema with the block's ID (will be remapped later)+ return cls(id=block.id, **create_block.model_dump())+++class FileSchema(FileMetadataBase):+ """File with human-readable ID for agent file"""++ __id_prefix__ = "file"+ id: str = Field(..., description="Human-readable identifier for this file in the file")++ @classmethod+ def from_file_metadata(cls, file_metadata: FileMetadata) -> "FileSchema":+ """Convert FileMetadata to FileSchema"""++ create_file = FileMetadataBase(+ source_id=file_metadata.source_id,+ file_name=file_metadata.file_name,+ original_file_name=file_metadata.original_file_name,+ file_path=file_metadata.file_path,+ file_type=file_metadata.file_type,+ file_size=file_metadata.file_size,+ file_creation_date=file_metadata.file_creation_date,+ file_last_modified_date=file_metadata.file_last_modified_date,+ processing_status=file_metadata.processing_status,+ error_message=file_metadata.error_message,+ total_chunks=file_metadata.total_chunks,+ chunks_embedded=file_metadata.chunks_embedded,+ content=file_metadata.content,+ )++ # Create FileSchema with the file's ID (will be remapped later)+ return cls(id=file_metadata.id, **create_file.model_dump())+++class SourceSchema(SourceCreate):+ """Source with human-readable ID for agent file"""++ __id_prefix__ = "source"+ id: str = Field(..., description="Human-readable identifier for this source in the file")++ @classmethod+ def from_source(cls, source: Source) -> "SourceSchema":+ """Convert Block to BlockSchema"""++ create_block = SourceCreate(+ name=source.name,+ description=source.description,+ instructions=source.instructions,+ metadata=source.metadata,+ embedding_config=source.embedding_config,+ )++ # Create SourceSchema with the block's ID (will be remapped later)+ return cls(id=source.id, **create_block.model_dump())+++# TODO: This one is quite thin, just a wrapper over Tool+class ToolSchema(Tool):+ """Tool with human-readable ID for agent file"""++ __id_prefix__ = "tool"+ id: str = Field(..., description="Human-readable identifier for this tool in the file")++ @classmethod+ def from_tool(cls, tool: Tool) -> "ToolSchema":+ """Convert Tool to ToolSchema"""+ return cls(**tool.model_dump())+++# class MCPServerSchema(RegisterMCPServer):+# """MCP Server with human-readable ID for agent file"""+# id: str = Field(..., description="Human-readable identifier for this MCP server in the file")+++class AgentFileSchema(BaseModel):+ """Schema for serialized agent file that can be exported to JSON and imported into agent server."""++ agents: List[AgentSchema] = Field(..., description="List of agents in this agent file")+ groups: List[GroupSchema] = Field(..., description="List of groups in this agent file")+ blocks: List[BlockSchema] = Field(..., description="List of memory blocks in this agent file")+ files: List[FileSchema] = Field(..., description="List of files in this agent file")+ sources: List[SourceSchema] = Field(..., description="List of sources in this agent file")+ tools: List[ToolSchema] = Field(..., description="List of tools in this agent file")+ # mcp_servers: List[MCPServerSchema] = Field(..., description="List of MCP servers in this agent file")+ metadata: Dict[str, str] = Field(+ default_factory=dict, description="Metadata for this agent file, including revision_id and other export information."+ )+ created_at: Optional[datetime] = Field(default=None, description="The timestamp when the object was created.")diff --git a/letta/schemas/block.py b/letta/schemas/block.pyindex 8b00d5c12..ea9f12d41 100644--- a/letta/schemas/block.py+++ b/letta/schemas/block.py@@ -74,9 +74,6 @@ class Block(BaseBlock):id: str = BaseBlock.generate_id_field()- # associated user/agent- organization_id: Optional[str] = Field(None, description="The unique identifier of the organization associated with the block.")-# default orm fieldscreated_by_id: Optional[str] = Field(None, description="The id of the user that made this Block.")last_updated_by_id: Optional[str] = Field(None, description="The id of the user that last updated this Block.")diff --git a/letta/schemas/file.py b/letta/schemas/file.pyindex 90132c502..4a3c876f8 100644--- a/letta/schemas/file.py+++ b/letta/schemas/file.py@@ -22,12 +22,7 @@ class FileMetadataBase(LettaBase):__id_prefix__ = "file"--class FileMetadata(FileMetadataBase):- """Representation of a single FileMetadata"""-- id: str = FileMetadataBase.generate_id_field()- organization_id: Optional[str] = Field(None, description="The unique identifier of the organization associated with the document.")+ # Core file metadata fieldssource_id: str = Field(..., description="The unique identifier of the source associated with the document.")file_name: Optional[str] = Field(None, description="The name of the file.")original_file_name: Optional[str] = Field(None, description="The original name of the file as uploaded.")@@ -43,13 +38,6 @@ class FileMetadata(FileMetadataBase):error_message: Optional[str] = Field(default=None, description="Optional error message if the file failed processing.")total_chunks: Optional[int] = Field(default=None, description="Total number of chunks for the file.")chunks_embedded: Optional[int] = Field(default=None, description="Number of chunks that have been embedded.")-- # orm metadata, optional fields- created_at: Optional[datetime] = Field(default_factory=datetime.utcnow, description="The creation date of the file.")- updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow, description="The update date of the file.")- is_deleted: bool = Field(False, description="Whether this file is deleted or not.")-- # This is optional, and only occasionally pulled in since it can be very largecontent: Optional[str] = Field(default=None, description="Optional full-text content of the file; only populated on demand due to its size.")@@ -59,11 +47,38 @@ class FileMetadata(FileMetadataBase):return self.processing_status in (FileProcessingStatus.COMPLETED, FileProcessingStatus.ERROR)+class FileMetadata(FileMetadataBase):+ """Representation of a single FileMetadata"""++ id: str = FileMetadataBase.generate_id_field()+ organization_id: Optional[str] = Field(None, description="The unique identifier of the organization associated with the document.")++ # orm metadata, optional fields+ created_at: Optional[datetime] = Field(default_factory=datetime.utcnow, description="The creation date of the file.")+ updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow, description="The update date of the file.")+ is_deleted: bool = Field(False, description="Whether this file is deleted or not.")++class FileAgentBase(LettaBase):"""Base class for the FileMetadata-⇄-Agent association schemas"""__id_prefix__ = "file_agent"+ # Core file-agent association fields+ agent_id: str = Field(..., description="Unique identifier of the agent.")+ file_id: str = Field(..., description="Unique identifier of the file.")+ source_id: str = Field(..., description="Unique identifier of the source (denormalized from files.source_id).")+ file_name: str = Field(..., description="Name of the file.")+ is_open: bool = Field(True, description="True if the agent currently has the file open.")+ visible_content: Optional[str] = Field(+ None,+ description="Portion of the file the agent is focused on (may be large).",+ )+ last_accessed_at: Optional[datetime] = Field(+ default_factory=datetime.utcnow,+ description="UTC timestamp of the agent’s most recent access to this file.",+ )+class FileAgent(FileAgentBase):"""@@ -83,19 +98,6 @@ class FileAgent(FileAgentBase):None,description="Org ID this association belongs to (inherited from both agent and file).",)- agent_id: str = Field(..., description="Unique identifier of the agent.")- file_id: str = Field(..., description="Unique identifier of the file.")- source_id: str = Field(..., description="Unique identifier of the source (denormalized from files.source_id).")- file_name: str = Field(..., description="Name of the file.")- is_open: bool = Field(True, description="True if the agent currently has the file open.")- visible_content: Optional[str] = Field(- None,- description="Portion of the file the agent is focused on (may be large).",- )- last_accessed_at: Optional[datetime] = Field(- default_factory=datetime.utcnow,- description="UTC timestamp of the agent’s most recent access to this file.",- )created_at: Optional[datetime] = Field(default_factory=datetime.utcnow,diff --git a/letta/schemas/letta_message.py b/letta/schemas/letta_message.pyindex cfae6b38b..d1e9b2a70 100644--- a/letta/schemas/letta_message.py+++ b/letta/schemas/letta_message.py@@ -40,15 +40,18 @@ class LettaMessage(BaseModel):message_type (MessageType): The type of the messageotid (Optional[str]): The offline threading id associated with this messagesender_id (Optional[str]): The id of the sender of the message, can be an identity id or agent id+ step_id (Optional[str]): The step id associated with the message+ is_err (Optional[bool]): Whether the message is an errored message or not. Used for debugging purposes only."""id: strdate: datetime- name: Optional[str] = None+ name: str | None = Nonemessage_type: MessageType = Field(..., description="The type of the message.")- otid: Optional[str] = None- sender_id: Optional[str] = None- step_id: Optional[str] = None+ otid: str | None = None+ sender_id: str | None = None+ step_id: str | None = None+ is_err: bool | None = None@field_serializer("date")def serialize_datetime(self, dt: datetime, _info):@@ -60,6 +63,14 @@ class LettaMessage(BaseModel):dt = dt.replace(tzinfo=timezone.utc)return dt.isoformat(timespec="seconds")+ @field_serializer("is_err", when_used="unless-none")+ def serialize_is_err(self, value: bool | None, _info):+ """+ Only serialize is_err field when it's True (for debugging purposes).+ When is_err is None or False, this field will be excluded from the JSON output.+ """+ return value if value is True else None+class SystemMessage(LettaMessage):"""diff --git a/letta/schemas/memory.py b/letta/schemas/memory.pyindex eac33ae71..829bf7379 100644--- a/letta/schemas/memory.py+++ b/letta/schemas/memory.py@@ -174,7 +174,7 @@ class Memory(BaseModel, validate_assignment=True):def update_block_value(self, label: str, value: str):"""Update the value of a block"""if not isinstance(value, str):- raise ValueError(f"Provided value must be a string")+ raise ValueError("Provided value must be a string")for block in self.blocks:if block.label == label:diff --git a/letta/schemas/message.py b/letta/schemas/message.pyindex 2243cc96b..ec690577a 100644--- a/letta/schemas/message.py+++ b/letta/schemas/message.py@@ -128,29 +128,28 @@ class MessageUpdate(BaseModel):class Message(BaseMessage):"""- Letta's internal representation of a message. Includes methods to convert to/from LLM provider formats.-- Attributes:- id (str): The unique identifier of the message.- role (MessageRole): The role of the participant.- text (str): The text of the message.- user_id (str): The unique identifier of the user.- agent_id (str): The unique identifier of the agent.- model (str): The model used to make the function call.- name (str): The name of the participant.- created_at (datetime): The time the message was created.- tool_calls (List[OpenAIToolCall,]): The list of tool calls requested.- tool_call_id (str): The id of the tool call.- step_id (str): The id of the step that this message was created in.- otid (str): The offline threading id associated with this message.- tool_returns (List[ToolReturn]): The list of tool returns requested.- group_id (str): The multi-agent group that the message was sent in.- sender_id (str): The id of the sender of the message, can be an identity id or agent id.-+ Letta's internal representation of a message. Includes methods to convert to/from LLM provider formats.++ Attributes:+ id (str): The unique identifier of the message.+ role (MessageRole): The role of the participant.+ text (str): The text of the message.+ user_id (str): The unique identifier of the user.+ agent_id (str): The unique identifier of the agent.+ model (str): The model used to make the function call.+ name (str): The name of the participant.+ created_at (datetime): The time the message was created.+ tool_calls (List[OpenAIToolCall,]): The list of tool calls requested.+ tool_call_id (str): The id of the tool call.+ step_id (str): The id of the step that this message was created in.+ otid (str): The offline threading id associated with this message.+ tool_returns (List[ToolReturn]): The list of tool returns requested.+ group_id (str): The multi-agent group that the message was sent in.+ sender_id (str): The id of the sender of the message, can be an identity id or agent id.+ t"""id: str = BaseMessage.generate_id_field()- organization_id: Optional[str] = Field(default=None, description="The unique identifier of the organization.")agent_id: Optional[str] = Field(default=None, description="The unique identifier of the agent.")model: Optional[str] = Field(default=None, description="The model used to make the function call.")# Basic OpenAI-style fields@@ -172,6 +171,9 @@ class Message(BaseMessage):group_id: Optional[str] = Field(default=None, description="The multi-agent group that the message was sent in")sender_id: Optional[str] = Field(default=None, description="The id of the sender of the message, can be an identity id or agent id")batch_item_id: Optional[str] = Field(default=None, description="The id of the LLMBatchItem that this message is associated with")+ is_err: Optional[bool] = Field(+ default=None, description="Whether this message is part of an error step. Used only for debugging purposes."+ )# This overrides the optional base orm schema, created_at MUST exist on all messages objectscreated_at: datetime = Field(default_factory=get_utc_time, description="The timestamp when the object was created.")@@ -191,6 +193,7 @@ class Message(BaseMessage):if not is_utc_datetime(self.created_at):self.created_at = self.created_at.replace(tzinfo=timezone.utc)json_message["created_at"] = self.created_at.isoformat()+ json_message.pop("is_err", None) # make sure we don't include this debugging informationreturn json_message@staticmethod@@ -204,6 +207,7 @@ class Message(BaseMessage):assistant_message_tool_name: str = DEFAULT_MESSAGE_TOOL,assistant_message_tool_kwarg: str = DEFAULT_MESSAGE_TOOL_KWARG,reverse: bool = True,+ include_err: Optional[bool] = None,) -> List[LettaMessage]:if use_assistant_message:message_ids_to_remove = []@@ -234,6 +238,7 @@ class Message(BaseMessage):assistant_message_tool_name=assistant_message_tool_name,assistant_message_tool_kwarg=assistant_message_tool_kwarg,reverse=reverse,+ include_err=include_err,)]@@ -243,6 +248,7 @@ class Message(BaseMessage):assistant_message_tool_name: str = DEFAULT_MESSAGE_TOOL,assistant_message_tool_kwarg: str = DEFAULT_MESSAGE_TOOL_KWARG,reverse: bool = True,+ include_err: Optional[bool] = None,) -> List[LettaMessage]:"""Convert message object (in DB format) to the style used by the original Letta API"""messages = []@@ -682,14 +688,13 @@ class Message(BaseMessage):# since the only "parts" we have are for supporting various COTif self.role == "system":- assert all([v is not None for v in [self.role]]), vars(self)openai_message = {"content": text_content,"role": "developer" if use_developer_message else self.role,}elif self.role == "user":- assert all([v is not None for v in [text_content, self.role]]), vars(self)+ assert text_content is not None, vars(self)openai_message = {"content": text_content,"role": self.role,@@ -720,7 +725,7 @@ class Message(BaseMessage):tool_call_dict["id"] = tool_call_dict["id"][:max_tool_id_length]elif self.role == "tool":- assert all([v is not None for v in [self.role, self.tool_call_id]]), vars(self)+ assert self.tool_call_id is not None, vars(self)openai_message = {"content": text_content,"role": self.role,@@ -776,7 +781,7 @@ class Message(BaseMessage):if self.role == "system":# NOTE: this is not for system instructions, but instead system "events"- assert all([v is not None for v in [text_content, self.role]]), vars(self)+ assert text_content is not None, vars(self)# Two options here, we would use system.package_system_message,# or use a more Anthropic-specific packaging ie xml tagsuser_system_event = add_xml_tag(string=f"SYSTEM ALERT: {text_content}", xml_tag="event")@@ -875,7 +880,7 @@ class Message(BaseMessage):elif self.role == "tool":# NOTE: Anthropic uses role "user" for "tool" responses- assert all([v is not None for v in [self.role, self.tool_call_id]]), vars(self)+ assert self.tool_call_id is not None, vars(self)anthropic_message = {"role": "user", # NOTE: diff"content": [@@ -988,7 +993,7 @@ class Message(BaseMessage):elif self.role == "tool":# NOTE: Significantly different tool calling format, more similar to function calling format- assert all([v is not None for v in [self.role, self.tool_call_id]]), vars(self)+ assert self.tool_call_id is not None, vars(self)if self.name is None:warnings.warn(f"Couldn't find function name on tool call, defaulting to tool ID instead.")diff --git a/letta/schemas/openai/chat_completion_response.py b/letta/schemas/openai/chat_completion_response.pyindex 77f8b9911..63224cc46 100644--- a/letta/schemas/openai/chat_completion_response.py+++ b/letta/schemas/openai/chat_completion_response.py@@ -106,7 +106,6 @@ class UsageStatistics(BaseModel):completion_tokens_details: Optional[UsageStatisticsCompletionTokenDetails] = Nonedef __add__(self, other: "UsageStatistics") -> "UsageStatistics":-if self.prompt_tokens_details is None and other.prompt_tokens_details is None:total_prompt_tokens_details = Noneelif self.prompt_tokens_details is None:diff --git a/letta/schemas/providers.py b/letta/schemas/providers.pyindex 51d988bc4..97d682812 100644--- a/letta/schemas/providers.py+++ b/letta/schemas/providers.py@@ -1536,6 +1536,26 @@ class BedrockProvider(Provider):provider_category: ProviderCategory = Field(ProviderCategory.base, description="The category of the provider (base or byok)")region: str = Field(..., description="AWS region for Bedrock")+ def check_api_key(self):+ """Check if the Bedrock credentials are valid"""+ from letta.errors import LLMAuthenticationError+ from letta.llm_api.aws_bedrock import bedrock_get_model_list++ try:+ # For BYOK providers, use the custom credentials+ if self.provider_category == ProviderCategory.byok:+ # If we can list models, the credentials are valid+ bedrock_get_model_list(+ region_name=self.region,+ access_key_id=self.access_key,+ secret_access_key=self.api_key, # api_key stores the secret access key+ )+ else:+ # For base providers, use default credentials+ bedrock_get_model_list(region_name=self.region)+ except Exception as e:+ raise LLMAuthenticationError(message=f"Failed to authenticate with Bedrock: {e}")+def list_llm_models(self):from letta.llm_api.aws_bedrock import bedrock_get_model_listdiff --git a/letta/schemas/source.py b/letta/schemas/source.pyindex 79476780f..008da4889 100644--- a/letta/schemas/source.py+++ b/letta/schemas/source.py@@ -9,11 +9,17 @@ from letta.schemas.letta_base import LettaBaseclass BaseSource(LettaBase):"""- Shared attributes accourss all source schemas.+ Shared attributes across all source schemas."""__id_prefix__ = "source"+ # Core source fields+ name: str = Field(..., description="The name of the source.")+ description: Optional[str] = Field(None, description="The description of the source.")+ instructions: Optional[str] = Field(None, description="Instructions for how to use the source.")+ metadata: Optional[dict] = Field(None, description="Metadata associated with the source.")+class Source(BaseSource):"""@@ -29,9 +35,6 @@ class Source(BaseSource):"""id: str = BaseSource.generate_id_field()- name: str = Field(..., description="The name of the source.")- description: Optional[str] = Field(None, description="The description of the source.")- instructions: Optional[str] = Field(None, description="Instructions for how to use the source.")embedding_config: EmbeddingConfig = Field(..., description="The embedding configuration used by the source.")organization_id: Optional[str] = Field(None, description="The ID of the organization that created the source.")metadata: Optional[dict] = Field(None, validation_alias="metadata_", description="Metadata associated with the source.")@@ -48,29 +51,24 @@ class SourceCreate(BaseSource):Schema for creating a new Source."""- # required- name: str = Field(..., description="The name of the source.")# TODO: @matt, make this required after shub makes the FE changes-- embedding: Optional[str] = Field(None, description="The hande for the embedding config used by the source.")+ embedding: Optional[str] = Field(None, description="The handle for the embedding config used by the source.")embedding_chunk_size: Optional[int] = Field(None, description="The chunk size of the embedding.")# TODO: remove (legacy config)embedding_config: Optional[EmbeddingConfig] = Field(None, description="(Legacy) The embedding configuration used by the source.")- # optional- description: Optional[str] = Field(None, description="The description of the source.")- instructions: Optional[str] = Field(None, description="Instructions for how to use the source.")- metadata: Optional[dict] = Field(None, description="Metadata associated with the source.")-class SourceUpdate(BaseSource):"""Schema for updating an existing Source."""+ # Override base fields to make them optional for updatesname: Optional[str] = Field(None, description="The name of the source.")description: Optional[str] = Field(None, description="The description of the source.")instructions: Optional[str] = Field(None, description="Instructions for how to use the source.")metadata: Optional[dict] = Field(None, description="Metadata associated with the source.")++ # Additional update-specific fieldsembedding_config: Optional[EmbeddingConfig] = Field(None, description="The embedding configuration used by the source.")diff --git a/letta/schemas/step.py b/letta/schemas/step.pyindex 37153a569..bc5cd2041 100644--- a/letta/schemas/step.py+++ b/letta/schemas/step.py@@ -1,8 +1,10 @@+from enum import Enum, autofrom typing import Dict, List, Literal, Optionalfrom pydantic import Fieldfrom letta.schemas.letta_base import LettaBase+from letta.schemas.letta_stop_reason import StopReasonTypefrom letta.schemas.message import Message@@ -28,6 +30,7 @@ class Step(StepBase):prompt_tokens: Optional[int] = Field(None, description="The number of tokens in the prompt during this step.")total_tokens: Optional[int] = Field(None, description="The total number of tokens processed by the agent during this step.")completion_tokens_details: Optional[Dict] = Field(None, description="Metadata for the agent.")+ stop_reason: Optional[StopReasonType] = Field(None, description="The stop reason associated with the step.")tags: List[str] = Field([], description="Metadata tags.")tid: Optional[str] = Field(None, description="The unique identifier of the transaction that processed this step.")trace_id: Optional[str] = Field(None, description="The trace id of the agent step.")@@ -36,3 +39,12 @@ class Step(StepBase):None, description="The feedback for this step. Must be either 'positive' or 'negative'.")project_id: Optional[str] = Field(None, description="The project that the agent that executed this step belongs to (cloud only).")+++class StepProgression(int, Enum):+ START = auto()+ STREAM_RECEIVED = auto()+ RESPONSE_RECEIVED = auto()+ STEP_LOGGED = auto()+ LOGGED_TRACE = auto()+ FINISHED = auto()diff --git a/letta/schemas/tool.py b/letta/schemas/tool.pyindex dde4975ff..c2964e637 100644--- a/letta/schemas/tool.py+++ b/letta/schemas/tool.py@@ -50,7 +50,6 @@ class Tool(BaseTool):tool_type: ToolType = Field(ToolType.CUSTOM, description="The type of the tool.")description: Optional[str] = Field(None, description="The description of the tool.")source_type: Optional[str] = Field(None, description="The type of the source code.")- organization_id: Optional[str] = Field(None, description="The unique identifier of the organization associated with the tool.")name: Optional[str] = Field(None, description="The name of the function.")tags: List[str] = Field([], description="Metadata tags.")@@ -147,9 +146,6 @@ class ToolCreate(LettaBase):return_char_limit: int = Field(FUNCTION_RETURN_CHAR_LIMIT, description="The maximum number of characters in the response.")pip_requirements: Optional[List[PipRequirement]] = Field(None, description="Optional list of pip packages required by this tool.")- # TODO should we put the HTTP / API fetch inside from_mcp?- # async def from_mcp(cls, mcp_server: str, mcp_tool_name: str) -> "ToolCreate":-@classmethoddef from_mcp(cls, mcp_server_name: str, mcp_tool: MCPTool) -> "ToolCreate":from letta.functions.helpers import generate_mcp_tool_wrapperdiff --git a/letta/serialize_schemas/marshmallow_agent.py b/letta/serialize_schemas/marshmallow_agent.pyindex 55003db10..4e9f68aac 100644--- a/letta/serialize_schemas/marshmallow_agent.py+++ b/letta/serialize_schemas/marshmallow_agent.py@@ -86,7 +86,9 @@ class MarshmallowAgentSchema(BaseSchema):- Marks messages as in-context, preserving the order of the original `message_ids`- Removes individual message `id` fields"""- data = super().sanitize_ids(data, **kwargs)+ del data["id"]+ del data["_created_by_id"]+ del data["_last_updated_by_id"]data[self.FIELD_VERSION] = letta.__version__original_message_ids = data.pop(self.FIELD_MESSAGE_IDS, [])@@ -107,6 +109,15 @@ class MarshmallowAgentSchema(BaseSchema):return data+ @pre_load+ def regenerate_ids(self, data: Dict, **kwargs) -> Dict:+ if self.Meta.model:+ data["id"] = self.generate_id()+ data["_created_by_id"] = self.actor.id+ data["_last_updated_by_id"] = self.actor.id++ return data+@post_dumpdef hide_tool_exec_environment_variables(self, data: Dict, **kwargs):"""Hide the value of tool_exec_environment_variables"""@@ -135,4 +146,6 @@ class MarshmallowAgentSchema(BaseSchema):"identities","is_deleted","groups",+ "batch_items",+ "organization",)diff --git a/letta/serialize_schemas/marshmallow_block.py b/letta/serialize_schemas/marshmallow_block.pyindex 6325f2c88..082cd3289 100644--- a/letta/serialize_schemas/marshmallow_block.py+++ b/letta/serialize_schemas/marshmallow_block.py@@ -1,3 +1,7 @@+from typing import Dict++from marshmallow import post_dump, pre_load+from letta.orm.block import Blockfrom letta.schemas.block import Block as PydanticBlockfrom letta.serialize_schemas.marshmallow_base import BaseSchema@@ -10,6 +14,24 @@ class SerializedBlockSchema(BaseSchema):__pydantic_model__ = PydanticBlock+ @post_dump+ def sanitize_ids(self, data: Dict, **kwargs) -> Dict:+ # delete id+ del data["id"]+ del data["_created_by_id"]+ del data["_last_updated_by_id"]++ return data++ @pre_load+ def regenerate_ids(self, data: Dict, **kwargs) -> Dict:+ if self.Meta.model:+ data["id"] = self.generate_id()+ data["_created_by_id"] = self.actor.id+ data["_last_updated_by_id"] = self.actor.id++ return data+class Meta(BaseSchema.Meta):model = Block- exclude = BaseSchema.Meta.exclude + ("agents", "identities", "is_deleted")+ exclude = BaseSchema.Meta.exclude + ("agents", "identities", "is_deleted", "groups", "organization")diff --git a/letta/serialize_schemas/marshmallow_message.py b/letta/serialize_schemas/marshmallow_message.pyindex 1a8a8c22f..75678bd7a 100644--- a/letta/serialize_schemas/marshmallow_message.py+++ b/letta/serialize_schemas/marshmallow_message.py@@ -23,7 +23,6 @@ class SerializedMessageSchema(BaseSchema):# agent dump will then get rid of message idsdel data["_created_by_id"]del data["_last_updated_by_id"]- del data["organization"]return data@@ -33,10 +32,9 @@ class SerializedMessageSchema(BaseSchema):# Skip regenerating ID, as agent dump will do itdata["_created_by_id"] = self.actor.iddata["_last_updated_by_id"] = self.actor.id- data["organization"] = self.actor.organization_idreturn dataclass Meta(BaseSchema.Meta):model = Message- exclude = BaseSchema.Meta.exclude + ("step", "job_message", "otid", "is_deleted")+ exclude = BaseSchema.Meta.exclude + ("step", "job_message", "otid", "is_deleted", "organization")diff --git a/letta/serialize_schemas/marshmallow_tool.py b/letta/serialize_schemas/marshmallow_tool.pyindex 44f64a97a..a6d1c91e0 100644--- a/letta/serialize_schemas/marshmallow_tool.py+++ b/letta/serialize_schemas/marshmallow_tool.py@@ -1,3 +1,7 @@+from typing import Dict++from marshmallow import post_dump, pre_load+from letta.orm import Toolfrom letta.schemas.tool import Tool as PydanticToolfrom letta.serialize_schemas.marshmallow_base import BaseSchema@@ -10,6 +14,24 @@ class SerializedToolSchema(BaseSchema):__pydantic_model__ = PydanticTool+ @post_dump+ def sanitize_ids(self, data: Dict, **kwargs) -> Dict:+ # delete id+ del data["id"]+ del data["_created_by_id"]+ del data["_last_updated_by_id"]++ return data++ @pre_load+ def regenerate_ids(self, data: Dict, **kwargs) -> Dict:+ if self.Meta.model:+ data["id"] = self.generate_id()+ data["_created_by_id"] = self.actor.id+ data["_last_updated_by_id"] = self.actor.id++ return data+class Meta(BaseSchema.Meta):model = Tool- exclude = BaseSchema.Meta.exclude + ("is_deleted",)+ exclude = BaseSchema.Meta.exclude + ("is_deleted", "organization")diff --git a/letta/server/db.py b/letta/server/db.pyindex ff76a0007..11365522f 100644--- a/letta/server/db.py+++ b/letta/server/db.py@@ -1,20 +1,22 @@import osimport threading+import timeimport uuidfrom contextlib import asynccontextmanager, contextmanagerfrom typing import Any, AsyncGenerator, Generator+from opentelemetry import tracefrom rich.console import Consolefrom rich.panel import Panelfrom rich.text import Text-from sqlalchemy import Engine, NullPool, QueuePool, create_engine+from sqlalchemy import Engine, NullPool, QueuePool, create_engine, eventfrom sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_enginefrom sqlalchemy.orm import sessionmakerfrom letta.config import LettaConfigfrom letta.log import get_loggerfrom letta.otel.tracing import trace_method-from letta.settings import settings+from letta.settings import DatabaseChoice, settingslogger = get_logger(__name__)@@ -36,6 +38,46 @@ def print_sqlite_schema_error():console.print(Panel(error_text, border_style="red"))[email protected]_for(Engine, "connect")+def enable_sqlite_foreign_keys(dbapi_connection, connection_record):+ """Enable foreign key constraints for SQLite connections."""+ if "sqlite" in str(dbapi_connection):+ cursor = dbapi_connection.cursor()+ cursor.execute("PRAGMA foreign_keys=ON")+ cursor.close()+++def on_connect(dbapi_connection, connection_record):+ cursor = dbapi_connection.cursor()+ cursor.execute("SELECT pg_backend_pid()")+ pid = cursor.fetchone()[0]+ connection_record.info["pid"] = pid+ connection_record.info["connect_spawn_time_ms"] = time.perf_counter() * 1000+ cursor.close()+++def on_close(dbapi_connection, connection_record):+ connection_record.info.get("pid")+ (time.perf_counter() * 1000) - connection_record.info.get("connect_spawn_time_ms")+ # print(f"Connection closed: {pid}, duration: {duration:.6f}s")+++def on_checkout(dbapi_connection, connection_record, connection_proxy):+ connection_record.info.get("pid")+ connection_record.info["connect_checkout_time_ms"] = time.perf_counter() * 1000+++def on_checkin(dbapi_connection, connection_record):+ pid = connection_record.info.get("pid")+ duration = (time.perf_counter() * 1000) - connection_record.info.get("connect_checkout_time_ms")++ tracer = trace.get_tracer("letta.db.connection")+ with tracer.start_as_current_span("connect_release") as span:+ span.set_attribute("db.connection.pid", pid)+ span.set_attribute("db.connection.duration_ms", duration)+ span.set_attribute("db.connection.operation", "checkin")++@contextmanagerdef db_error_handler():"""Context manager for handling database errors"""@@ -43,6 +85,14 @@ def db_error_handler():yieldexcept Exception as e:# Handle other SQLAlchemy errors+ error_str = str(e)++ # Don't exit for expected constraint violations that should be handled by the application+ if "UNIQUE constraint failed" in error_str or "FOREIGN KEY constraint failed" in error_str:+ # These are application-level errors that should be handled by the ORM+ raise++ # For other database errors, print error and exitprint(e)print_sqlite_schema_error()# raise ValueError(f"SQLite DB error: {str(e)}")@@ -73,7 +123,7 @@ class DatabaseRegistry:return# Postgres engine- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:self.logger.info("Creating postgres engine")self.config.recall_storage_type = "postgres"self.config.recall_storage_uri = settings.letta_pg_uri_no_default@@ -99,6 +149,15 @@ class DatabaseRegistry:Base.metadata.create_all(bind=engine)self._engines["default"] = engine+ # Set up connection monitoring+ if settings.sqlalchemy_tracing and settings.database_engine is DatabaseChoice.POSTGRES:+ event.listen(engine, "connect", on_connect)+ event.listen(engine, "close", on_close)+ event.listen(engine, "checkout", on_checkout)+ event.listen(engine, "checkin", on_checkin)++ self._setup_pool_monitoring(engine, "default")+# Create session factoryself._session_factories["default"] = sessionmaker(autocommit=False, autoflush=False, bind=self._engines["default"])self._initialized["sync"] = True@@ -109,7 +168,7 @@ class DatabaseRegistry:if self._initialized.get("async") and not force:return- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:self.logger.info("Creating async postgres engine")# Create async engine - convert URI to async format@@ -128,10 +187,27 @@ class DatabaseRegistry:self.logger.info("Creating sqlite engine " + engine_path)async_engine = create_async_engine(engine_path, **self._build_sqlalchemy_engine_args(is_async=True))+ # Enable foreign keys for SQLite async connections+ @event.listens_for(async_engine.sync_engine, "connect")+ def enable_sqlite_foreign_keys_async(dbapi_connection, connection_record):+ cursor = dbapi_connection.cursor()+ cursor.execute("PRAGMA foreign_keys=ON")+ cursor.close()+# Create async session factoryself._async_engines["default"] = async_engine++ # Set up connection monitoring for async engine+ if settings.sqlalchemy_tracing and settings.database_engine is DatabaseChoice.POSTGRES:+ event.listen(async_engine.sync_engine, "connect", on_connect)+ event.listen(async_engine.sync_engine, "close", on_close)+ event.listen(async_engine.sync_engine, "checkout", on_checkout)+ event.listen(async_engine.sync_engine, "checkin", on_checkin)++ self._setup_pool_monitoring(async_engine, "default_async")+self._async_session_factories["default"] = async_sessionmaker(- expire_on_commit=True,+ expire_on_commit=False,close_resets_only=False,autocommit=False,autoflush=False,@@ -149,7 +225,10 @@ class DatabaseRegistry:pool_cls = NullPoolelse:logger.info("Enabling pooling on SqlAlchemy")- pool_cls = QueuePool if not is_async else None+ # AsyncAdaptedQueuePool will be the default if none is provided for async but setting this explicitly.+ from sqlalchemy import AsyncAdaptedQueuePool++ pool_cls = QueuePool if not is_async else AsyncAdaptedQueuePoolbase_args = {"echo": settings.pg_echo,@@ -207,11 +286,31 @@ class DatabaseRegistry:engine.connect = wrapped_connect+ def _setup_pool_monitoring(self, engine: Engine | AsyncEngine, engine_name: str) -> None:+ """Set up database pool monitoring for the given engine."""+ if not settings.enable_db_pool_monitoring:+ return++ try:+ from letta.otel.db_pool_monitoring import setup_pool_monitoring++ setup_pool_monitoring(engine, engine_name)+ self.logger.info(f"Database pool monitoring enabled for {engine_name}")+ except ImportError:+ self.logger.warning("Database pool monitoring not available - missing dependencies")+ except Exception as e:+ self.logger.warning(f"Failed to setup pool monitoring for {engine_name}: {e}")+def get_engine(self, name: str = "default") -> Engine:"""Get a database engine by name."""self.initialize_sync()return self._engines.get(name)+ def get_async_engine(self, name: str = "default") -> Engine:+ """Get a database engine by name."""+ self.initialize_async()+ return self._async_engines.get(name)+def get_session_factory(self, name: str = "default") -> sessionmaker:"""Get a session factory by name."""self.initialize_sync()@@ -286,6 +385,11 @@ class DatabaseRegistry:db_registry = DatabaseRegistry()+def get_db_registry() -> DatabaseRegistry:+ """Get the global database registry instance."""+ return db_registry++def get_db():"""Get a database session."""with db_registry.session() as session:diff --git a/letta/server/rest_api/app.py b/letta/server/rest_api/app.pyindex c630e2f59..3c1cbdfb1 100644--- a/letta/server/rest_api/app.py+++ b/letta/server/rest_api/app.py@@ -2,8 +2,10 @@ import importlib.utilimport jsonimport loggingimport os+import platformimport sysfrom contextlib import asynccontextmanager+from functools import partialfrom pathlib import Pathfrom typing import Optional@@ -34,32 +36,25 @@ from letta.server.db import db_registryfrom letta.server.rest_api.auth.index import setup_auth_router # TODO: probably remove right?from letta.server.rest_api.interface import StreamingServerInterfacefrom letta.server.rest_api.routers.openai.chat_completions.chat_completions import router as openai_chat_completions_router--# from letta.orm.utilities import get_db_session # TODO(ethan) reenable once we merge ORMfrom letta.server.rest_api.routers.v1 import ROUTERS as v1_routesfrom letta.server.rest_api.routers.v1.organizations import router as organizations_routerfrom letta.server.rest_api.routers.v1.users import router as users_router # TODO: decide on adminfrom letta.server.rest_api.static_files import mount_static_files+from letta.server.rest_api.utils import SENTRY_ENABLEDfrom letta.server.server import SyncServerfrom letta.settings import settings-# TODO(ethan)+if SENTRY_ENABLED:+ import sentry_sdk++IS_WINDOWS = platform.system() == "Windows"+# NOTE(charles): @ethan I had to add this to get the global as the bottom to work-interface: StreamingServerInterface = StreamingServerInterface+interface: type = StreamingServerInterfaceserver = SyncServer(default_interface_factory=lambda: interface())logger = get_logger(__name__)-import logging-import platform--from fastapi import FastAPI--is_windows = platform.system() == "Windows"--log = logging.getLogger("uvicorn")--def generate_openapi_schema(app: FastAPI):# Update the OpenAPI schemaif not app.openapi_schema:@@ -157,6 +152,17 @@ async def lifespan(app_: FastAPI):logger.info(f"[Worker {worker_id}] Scheduler shutdown completed")except Exception as e:logger.error(f"[Worker {worker_id}] Scheduler shutdown failed: {e}", exc_info=True)++ # Cleanup SQLAlchemy instrumentation+ if not settings.disable_tracing and settings.sqlalchemy_tracing:+ try:+ from letta.otel.sqlalchemy_instrumentation_integration import teardown_letta_db_instrumentation++ teardown_letta_db_instrumentation()+ logger.info(f"[Worker {worker_id}] SQLAlchemy instrumentation shutdown completed")+ except Exception as e:+ logger.warning(f"[Worker {worker_id}] SQLAlchemy instrumentation shutdown failed: {e}")+logger.info(f"[Worker {worker_id}] Lifespan shutdown completed")@@ -166,9 +172,7 @@ def create_application() -> "FastAPI":# server = SyncServer(default_interface_factory=lambda: interface())print(f"\n[[ Letta server // v{letta_version} ]]")- if (os.getenv("SENTRY_DSN") is not None) and (os.getenv("SENTRY_DSN") != ""):- import sentry_sdk-+ if SENTRY_ENABLED:sentry_sdk.init(dsn=os.getenv("SENTRY_DSN"),traces_sample_rate=1.0,@@ -176,6 +180,7 @@ def create_application() -> "FastAPI":"continuous_profiling_auto_start": True,},)+ logger.info("Sentry enabled.")debug_mode = "--debug" in sys.argvapp = FastAPI(@@ -188,31 +193,13 @@ def create_application() -> "FastAPI":lifespan=lifespan,)- @app.exception_handler(IncompatibleAgentType)- async def handle_incompatible_agent_type(request: Request, exc: IncompatibleAgentType):- return JSONResponse(- status_code=400,- content={- "detail": str(exc),- "expected_type": exc.expected_type,- "actual_type": exc.actual_type,- },- )+ # === Exception Handlers ===+ # TODO (cliandy): move to separate file@app.exception_handler(Exception)async def generic_error_handler(request: Request, exc: Exception):- # Log the actual error for debugging- log.error(f"Unhandled error: {str(exc)}", exc_info=True)- print(f"Unhandled error: {str(exc)}")-- import traceback-- # Print the stack trace- print(f"Stack trace: {traceback.format_exc()}")-- if (os.getenv("SENTRY_DSN") is not None) and (os.getenv("SENTRY_DSN") != ""):- import sentry_sdk-+ logger.error(f"Unhandled error: {str(exc)}", exc_info=True)+ if SENTRY_ENABLED:sentry_sdk.capture_exception(exc)return JSONResponse(@@ -224,62 +211,70 @@ def create_application() -> "FastAPI":},)- @app.exception_handler(NoResultFound)- async def no_result_found_handler(request: Request, exc: NoResultFound):- logger.error(f"NoResultFound: {exc}")+ async def error_handler_with_code(request: Request, exc: Exception, code: int, detail: str | None = None):+ logger.error(f"{type(exc).__name__}", exc_info=exc)+ if SENTRY_ENABLED:+ sentry_sdk.capture_exception(exc)+ if not detail:+ detail = str(exc)return JSONResponse(- status_code=404,- content={"detail": str(exc)},+ status_code=code,+ content={"detail": detail},)- @app.exception_handler(ForeignKeyConstraintViolationError)- async def foreign_key_constraint_handler(request: Request, exc: ForeignKeyConstraintViolationError):- logger.error(f"ForeignKeyConstraintViolationError: {exc}")+ _error_handler_400 = partial(error_handler_with_code, code=400)+ _error_handler_404 = partial(error_handler_with_code, code=404)+ _error_handler_404_agent = partial(_error_handler_404, detail="Agent not found")+ _error_handler_404_user = partial(_error_handler_404, detail="User not found")+ _error_handler_409 = partial(error_handler_with_code, code=409)- return JSONResponse(- status_code=409,- content={"detail": str(exc)},- )+ app.add_exception_handler(ValueError, _error_handler_400)+ app.add_exception_handler(NoResultFound, _error_handler_404)+ app.add_exception_handler(LettaAgentNotFoundError, _error_handler_404_agent)+ app.add_exception_handler(LettaUserNotFoundError, _error_handler_404_user)+ app.add_exception_handler(ForeignKeyConstraintViolationError, _error_handler_409)+ app.add_exception_handler(UniqueConstraintViolationError, _error_handler_409)- @app.exception_handler(UniqueConstraintViolationError)- async def unique_key_constraint_handler(request: Request, exc: UniqueConstraintViolationError):- logger.error(f"UniqueConstraintViolationError: {exc}")+ @app.exception_handler(IncompatibleAgentType)+ async def handle_incompatible_agent_type(request: Request, exc: IncompatibleAgentType):+ logger.error("Incompatible agent types. Expected: %s, Actual: %s", exc.expected_type, exc.actual_type)+ if SENTRY_ENABLED:+ sentry_sdk.capture_exception(exc)return JSONResponse(- status_code=409,- content={"detail": str(exc)},+ status_code=400,+ content={+ "detail": str(exc),+ "expected_type": exc.expected_type,+ "actual_type": exc.actual_type,+ },)@app.exception_handler(DatabaseTimeoutError)async def database_timeout_error_handler(request: Request, exc: DatabaseTimeoutError):logger.error(f"Timeout occurred: {exc}. Original exception: {exc.original_exception}")+ if SENTRY_ENABLED:+ sentry_sdk.capture_exception(exc)+return JSONResponse(status_code=503,content={"detail": "The database is temporarily unavailable. Please try again later."},)- @app.exception_handler(ValueError)- async def value_error_handler(request: Request, exc: ValueError):- return JSONResponse(status_code=400, content={"detail": str(exc)})-- @app.exception_handler(LettaAgentNotFoundError)- async def agent_not_found_handler(request: Request, exc: LettaAgentNotFoundError):- return JSONResponse(status_code=404, content={"detail": "Agent not found"})-- @app.exception_handler(LettaUserNotFoundError)- async def user_not_found_handler(request: Request, exc: LettaUserNotFoundError):- return JSONResponse(status_code=404, content={"detail": "User not found"})-@app.exception_handler(BedrockPermissionError)async def bedrock_permission_error_handler(request, exc: BedrockPermissionError):+ logger.error(f"Bedrock permission denied.")+ if SENTRY_ENABLED:+ sentry_sdk.capture_exception(exc)+return JSONResponse(status_code=403,content={"error": {"type": "bedrock_permission_denied","message": "Unable to access the required AI model. Please check your Bedrock permissions or contact support.",- "details": {"model_arn": exc.model_arn, "reason": str(exc)},+ "detail": {str(exc)},}},)@@ -290,6 +285,9 @@ def create_application() -> "FastAPI":print(f"▶ Using secure mode with password: {random_password}")app.add_middleware(CheckPasswordMiddleware)+ # Add reverse proxy middleware to handle X-Forwarded-* headers+ # app.add_middleware(ReverseProxyMiddleware, base_path=settings.server_base_path)+app.add_middleware(CORSMiddleware,allow_origins=settings.cors_origins,@@ -314,6 +312,20 @@ def create_application() -> "FastAPI":)setup_metrics(endpoint=otlp_endpoint, app=app, service_name=service_name)+ # Set up SQLAlchemy synchronous operation instrumentation+ if settings.sqlalchemy_tracing:+ from letta.otel.sqlalchemy_instrumentation_integration import setup_letta_db_instrumentation++ try:+ setup_letta_db_instrumentation(+ enable_joined_monitoring=True, # Monitor joined loading operations+ sql_truncate_length=1500, # Longer SQL statements for debugging+ )+ print("▶ SQLAlchemy synchronous operation instrumentation enabled")+ except Exception as e:+ logger.warning(f"Failed to setup SQLAlchemy instrumentation: {e}")+ # Don't fail startup if instrumentation fails+for route in v1_routes:app.include_router(route, prefix=API_PREFIX)# this gives undocumented routes for "latest" and bare api calls.@@ -371,8 +383,8 @@ def start_server(# Experimental UV Loop Supporttry:- if importlib.util.find_spec("uvloop") is not None and settings.use_uvloop:- print("Running server on uvloop...")+ if settings.use_uvloop:+ print("Running server asyncio loop on uvloop...")import asyncioimport uvloop@@ -383,7 +395,7 @@ def start_server(if (os.getenv("LOCAL_HTTPS") == "true") or "--localhttps" in sys.argv:print(f"▶ Server running at: https://{host or 'localhost'}:{port or REST_DEFAULT_PORT}")- print(f"▶ View using ADE at: https://app.letta.com/development-servers/local/dashboard\n")+ print("▶ View using ADE at: https://app.letta.com/development-servers/local/dashboard\n")if importlib.util.find_spec("granian") is not None and settings.use_granian:from granian import Granian@@ -417,7 +429,7 @@ def start_server()else:- if is_windows:+ if IS_WINDOWS:# Windows doesn't those the fancy unicode charactersprint(f"Server running at: http://{host or 'localhost'}:{port or REST_DEFAULT_PORT}")print(f"View using ADE at: https://app.letta.com/development-servers/local/dashboard\n")diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex 78355f668..55f5099ec 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -636,6 +636,9 @@ async def list_messages(use_assistant_message: bool = Query(True, description="Whether to use assistant messages"),assistant_message_tool_name: str = Query(DEFAULT_MESSAGE_TOOL, description="The name of the designated message tool."),assistant_message_tool_kwarg: str = Query(DEFAULT_MESSAGE_TOOL_KWARG, description="The name of the message argument."),+ include_err: bool | None = Query(+ None, description="Whether to include error messages and error statuses. For debugging purposes only."+ ),actor_id: str | None = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present):"""@@ -654,6 +657,7 @@ async def list_messages(use_assistant_message=use_assistant_message,assistant_message_tool_name=assistant_message_tool_name,assistant_message_tool_kwarg=assistant_message_tool_kwarg,+ include_err=include_err,actor=actor,)@@ -701,28 +705,32 @@ async def send_message(model_compatible = agent.llm_config.model_endpoint_type in ["anthropic", "openai", "together", "google_ai", "google_vertex", "bedrock"]# Create a new run for execution tracking- job_status = JobStatus.created- run = await server.job_manager.create_job_async(- pydantic_job=Run(- user_id=actor.id,- status=job_status,- metadata={- "job_type": "send_message",- "agent_id": agent_id,- },- request_config=LettaRequestConfig(- use_assistant_message=request.use_assistant_message,- assistant_message_tool_name=request.assistant_message_tool_name,- assistant_message_tool_kwarg=request.assistant_message_tool_kwarg,- include_return_message_types=request.include_return_message_types,+ if settings.track_agent_run:+ job_status = JobStatus.created+ run = await server.job_manager.create_job_async(+ pydantic_job=Run(+ user_id=actor.id,+ status=job_status,+ metadata={+ "job_type": "send_message",+ "agent_id": agent_id,+ },+ request_config=LettaRequestConfig(+ use_assistant_message=request.use_assistant_message,+ assistant_message_tool_name=request.assistant_message_tool_name,+ assistant_message_tool_kwarg=request.assistant_message_tool_kwarg,+ include_return_message_types=request.include_return_message_types,+ ),),- ),- actor=actor,- )+ actor=actor,+ )+ else:+ run = None+job_update_metadata = None# TODO (cliandy): clean this upredis_client = await get_redis_client()- await redis_client.set(f"{REDIS_RUN_ID_PREFIX}:{agent_id}", run.id)+ await redis_client.set(f"{REDIS_RUN_ID_PREFIX}:{agent_id}", run.id if run else None)try:if agent_eligible and model_compatible:@@ -737,7 +745,7 @@ async def send_message(job_manager=server.job_manager,actor=actor,group=agent.multi_agent_group,- current_run_id=run.id,+ current_run_id=run.id if run else None,)else:agent_loop = LettaAgent(@@ -750,7 +758,7 @@ async def send_message(actor=actor,step_manager=server.step_manager,telemetry_manager=server.telemetry_manager if settings.llm_api_logging else NoopTelemetryManager(),- current_run_id=run.id,+ current_run_id=run.id if run else None,# summarizer settings to be added heresummarizer_mode=(SummarizationMode.STATIC_MESSAGE_BUFFER@@ -786,12 +794,13 @@ async def send_message(job_status = JobStatus.failedraisefinally:- await server.job_manager.safe_update_job_status_async(- job_id=run.id,- new_status=job_status,- actor=actor,- metadata=job_update_metadata,- )+ if settings.track_agent_run:+ await server.job_manager.safe_update_job_status_async(+ job_id=run.id,+ new_status=job_status,+ actor=actor,+ metadata=job_update_metadata,+ )# noinspection PyInconsistentReturns@@ -832,29 +841,32 @@ async def send_message_streaming(not_letta_endpoint = agent.llm_config.model_endpoint != LETTA_MODEL_ENDPOINT# Create a new job for execution tracking- job_status = JobStatus.created- run = await server.job_manager.create_job_async(- pydantic_job=Run(- user_id=actor.id,- status=job_status,- metadata={- "job_type": "send_message_streaming",- "agent_id": agent_id,- },- request_config=LettaRequestConfig(- use_assistant_message=request.use_assistant_message,- assistant_message_tool_name=request.assistant_message_tool_name,- assistant_message_tool_kwarg=request.assistant_message_tool_kwarg,- include_return_message_types=request.include_return_message_types,+ if settings.track_agent_run:+ job_status = JobStatus.created+ run = await server.job_manager.create_job_async(+ pydantic_job=Run(+ user_id=actor.id,+ status=job_status,+ metadata={+ "job_type": "send_message_streaming",+ "agent_id": agent_id,+ },+ request_config=LettaRequestConfig(+ use_assistant_message=request.use_assistant_message,+ assistant_message_tool_name=request.assistant_message_tool_name,+ assistant_message_tool_kwarg=request.assistant_message_tool_kwarg,+ include_return_message_types=request.include_return_message_types,+ ),),- ),- actor=actor,- )+ actor=actor,+ )+ else:+ run = Nonejob_update_metadata = None# TODO (cliandy): clean this upredis_client = await get_redis_client()- await redis_client.set(f"{REDIS_RUN_ID_PREFIX}:{agent_id}", run.id)+ await redis_client.set(f"{REDIS_RUN_ID_PREFIX}:{agent_id}", run.id if run else None)try:if agent_eligible and model_compatible:@@ -871,7 +883,7 @@ async def send_message_streaming(step_manager=server.step_manager,telemetry_manager=server.telemetry_manager if settings.llm_api_logging else NoopTelemetryManager(),group=agent.multi_agent_group,- current_run_id=run.id,+ current_run_id=run.id if run else None,)else:agent_loop = LettaAgent(@@ -884,7 +896,7 @@ async def send_message_streaming(actor=actor,step_manager=server.step_manager,telemetry_manager=server.telemetry_manager if settings.llm_api_logging else NoopTelemetryManager(),- current_run_id=run.id,+ current_run_id=run.id if run else None,# summarizer settings to be added heresummarizer_mode=(SummarizationMode.STATIC_MESSAGE_BUFFER@@ -937,12 +949,13 @@ async def send_message_streaming(job_status = JobStatus.failedraisefinally:- await server.job_manager.safe_update_job_status_async(- job_id=run.id,- new_status=job_status,- actor=actor,- metadata=job_update_metadata,- )+ if settings.track_agent_run:+ await server.job_manager.safe_update_job_status_async(+ job_id=run.id,+ new_status=job_status,+ actor=actor,+ metadata=job_update_metadata,+ )@router.post("/{agent_id}/messages/cancel", operation_id="cancel_agent_run")@@ -959,6 +972,8 @@ async def cancel_agent_run("""actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)+ if not settings.track_agent_run:+ raise HTTPException(status_code=400, detail="Agent run tracking is disabled")if not run_ids:redis_client = await get_redis_client()run_id = await redis_client.get(f"{REDIS_RUN_ID_PREFIX}:{agent_id}")@@ -1156,7 +1171,7 @@ async def list_agent_groups():"""Lists the groups for an agent"""actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)- print("in list agents with manager_type", manager_type)+ logger.info("in list agents with manager_type", manager_type)return server.agent_manager.list_groups(agent_id=agent_id, manager_type=manager_type, actor=actor)diff --git a/letta/server/rest_api/routers/v1/blocks.py b/letta/server/rest_api/routers/v1/blocks.pyindex 9142e915b..2ccdc6f54 100644--- a/letta/server/rest_api/routers/v1/blocks.py+++ b/letta/server/rest_api/routers/v1/blocks.py@@ -72,14 +72,14 @@ async def modify_block(return await server.block_manager.update_block_async(block_id=block_id, block_update=block_update, actor=actor)[email protected]("/{block_id}", response_model=Block, operation_id="delete_block")[email protected]("/{block_id}", operation_id="delete_block")async def delete_block(block_id: str,server: SyncServer = Depends(get_letta_server),actor_id: Optional[str] = Header(None, alias="user_id"),):actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)- return await server.block_manager.delete_block_async(block_id=block_id, actor=actor)+ await server.block_manager.delete_block_async(block_id=block_id, actor=actor)@router.get("/{block_id}", response_model=Block, operation_id="retrieve_block")diff --git a/letta/server/rest_api/routers/v1/jobs.py b/letta/server/rest_api/routers/v1/jobs.pyindex 90c108d93..2a3ec4648 100644--- a/letta/server/rest_api/routers/v1/jobs.py+++ b/letta/server/rest_api/routers/v1/jobs.py@@ -7,6 +7,7 @@ from letta.schemas.enums import JobStatusfrom letta.schemas.job import Jobfrom letta.server.rest_api.utils import get_letta_serverfrom letta.server.server import SyncServer+from letta.settings import settingsrouter = APIRouter(prefix="/jobs", tags=["jobs"])@@ -93,6 +94,8 @@ async def cancel_job(agent execution to terminate as soon as possible."""actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)+ if not settings.track_agent_run:+ raise HTTPException(status_code=400, detail="Agent run tracking is disabled")try:# First check if the job exists and is in a cancellable statediff --git a/letta/server/rest_api/routers/v1/organizations.py b/letta/server/rest_api/routers/v1/organizations.pyindex 04b69e947..7f52a79df 100644--- a/letta/server/rest_api/routers/v1/organizations.py+++ b/letta/server/rest_api/routers/v1/organizations.py@@ -52,7 +52,7 @@ async def delete_org(try:org = await server.organization_manager.get_organization_by_id_async(org_id=org_id)if org is None:- raise HTTPException(status_code=404, detail=f"Organization does not exist")+ raise HTTPException(status_code=404, detail="Organization does not exist")await server.organization_manager.delete_organization_by_id_async(org_id=org_id)except HTTPException:raise@@ -70,7 +70,7 @@ async def update_org(try:org = await server.organization_manager.get_organization_by_id_async(org_id=org_id)if org is None:- raise HTTPException(status_code=404, detail=f"Organization does not exist")+ raise HTTPException(status_code=404, detail="Organization does not exist")org = await server.organization_manager.update_organization_async(org_id=org_id, name=request.name)except HTTPException:raisediff --git a/letta/server/rest_api/routers/v1/sources.py b/letta/server/rest_api/routers/v1/sources.pyindex 3997d5788..fb41bf802 100644--- a/letta/server/rest_api/routers/v1/sources.py+++ b/letta/server/rest_api/routers/v1/sources.py@@ -99,6 +99,7 @@ async def get_source_id_by_name(async def get_sources_metadata(server: "SyncServer" = Depends(get_letta_server),actor_id: Optional[str] = Header(None, alias="user_id"),+ include_detailed_per_source_metadata: bool = False,):"""Get aggregated metadata for all sources in an organization.@@ -107,10 +108,12 @@ async def get_sources_metadata(- Total number of sources- Total number of files across all sources- Total size of all files- - Per-source breakdown with file details (file_name, file_size per file)+ - Per-source breakdown with file details (file_name, file_size per file) if include_detailed_per_source_metadata is True"""actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)- return await server.file_manager.get_organization_sources_metadata(actor=actor)+ return await server.file_manager.get_organization_sources_metadata(+ actor=actor, include_detailed_per_source_metadata=include_detailed_per_source_metadata+ )@router.get("/", response_model=List[Source], operation_id="list_sources")@@ -321,6 +324,19 @@ async def upload_file_to_source(return file_metadata[email protected]("/{source_id}/agents", response_model=List[str], operation_id="get_agents_for_source")+async def get_agents_for_source(+ source_id: str,+ server: SyncServer = Depends(get_letta_server),+ actor_id: Optional[str] = Header(None, alias="user_id"),+):+ """+ Get all agent IDs that have the specified source attached.+ """+ actor = await server.user_manager.get_actor_or_default_async(actor_id=actor_id)+ return await server.source_manager.get_agents_for_source_id(source_id=source_id, actor=actor)++@router.get("/{source_id}/passages", response_model=List[Passage], operation_id="list_source_passages")async def list_source_passages(source_id: str,diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.pyindex 59b93a4eb..444b4900b 100644--- a/letta/server/rest_api/routers/v1/tools.py+++ b/letta/server/rest_api/routers/v1/tools.py@@ -20,11 +20,12 @@ from letta.helpers.composio_helpers import get_composio_api_keyfrom letta.log import get_loggerfrom letta.orm.errors import UniqueConstraintViolationErrorfrom letta.schemas.letta_message import ToolReturnMessage-from letta.schemas.mcp import UpdateSSEMCPServer, UpdateStreamableHTTPMCPServer+from letta.schemas.mcp import UpdateSSEMCPServer, UpdateStdioMCPServer, UpdateStreamableHTTPMCPServerfrom letta.schemas.tool import Tool, ToolCreate, ToolRunFromSource, ToolUpdatefrom letta.server.rest_api.utils import get_letta_serverfrom letta.server.server import SyncServerfrom letta.services.mcp.sse_client import AsyncSSEMCPClient+from letta.services.mcp.stdio_client import AsyncStdioMCPClientfrom letta.services.mcp.streamable_http_client import AsyncStreamableHTTPMCPClientfrom letta.settings import tool_settings@@ -136,7 +137,7 @@ async def create_tool(except UniqueConstraintViolationError as e:# Log or print the full exception here for debuggingprint(f"Error occurred: {e}")- clean_error_message = f"Tool with this name already exists."+ clean_error_message = "Tool with this name already exists."raise HTTPException(status_code=409, detail=clean_error_message)except LettaToolCreateError as e:# HTTP 400 == Bad Request@@ -234,6 +235,7 @@ async def run_tool_from_source(tool_name=request.name,tool_args_json_schema=request.args_json_schema,tool_json_schema=request.json_schema,+ pip_requirements=request.pip_requirements,actor=actor,)except LettaToolCreateError as e:@@ -262,7 +264,7 @@ def list_composio_apps(server: SyncServer = Depends(get_letta_server), user_id:if not composio_api_key:raise HTTPException(status_code=400, # Bad Request- detail=f"No API keys found for Composio. Please add your Composio API Key as an environment variable for your sandbox configuration, or set it as environment variable COMPOSIO_API_KEY.",+ detail="No API keys found for Composio. Please add your Composio API Key as an environment variable for your sandbox configuration, or set it as environment variable COMPOSIO_API_KEY.",)return server.get_composio_apps(api_key=composio_api_key)@@ -281,7 +283,7 @@ def list_composio_actions_by_app(if not composio_api_key:raise HTTPException(status_code=400, # Bad Request- detail=f"No API keys found for Composio. Please add your Composio API Key as an environment variable for your sandbox configuration, or set it as environment variable COMPOSIO_API_KEY.",+ detail="No API keys found for Composio. Please add your Composio API Key as an environment variable for your sandbox configuration, or set it as environment variable COMPOSIO_API_KEY.",)return server.get_composio_actions_from_app_name(composio_app_name=composio_app_name, api_key=composio_api_key)@@ -444,7 +446,6 @@ async def add_mcp_tool(actor = server.user_manager.get_user_or_default(user_id=actor_id)if tool_settings.mcp_read_from_config:-try:available_tools = await server.get_tools_from_mcp_server(mcp_server_name=mcp_server_name)except ValueError as e:@@ -565,7 +566,7 @@ async def add_mcp_server_to_config()async def update_mcp_server(mcp_server_name: str,- request: Union[UpdateSSEMCPServer, UpdateStreamableHTTPMCPServer] = Body(...),+ request: Union[UpdateStdioMCPServer, UpdateSSEMCPServer, UpdateStreamableHTTPMCPServer] = Body(...),server: SyncServer = Depends(get_letta_server),actor_id: Optional[str] = Header(None, alias="user_id"),):@@ -627,12 +628,6 @@ async def test_mcp_server("""client = Nonetry:- if isinstance(request, StdioServerConfig):- raise HTTPException(- status_code=400,- detail="stdio is not supported currently for testing connection",- )-# create a temporary MCP client based on the server typeif request.type == MCPServerType.SSE:if not isinstance(request, SSEServerConfig):@@ -642,6 +637,10 @@ async def test_mcp_server(if not isinstance(request, StreamableHTTPServerConfig):request = StreamableHTTPServerConfig(**request.model_dump())client = AsyncStreamableHTTPMCPClient(request)+ elif request.type == MCPServerType.STDIO:+ if not isinstance(request, StdioServerConfig):+ request = StdioServerConfig(**request.model_dump())+ client = AsyncStdioMCPClient(request)else:raise ValueError(f"Invalid MCP server type: {request.type}")diff --git a/letta/server/rest_api/routers/v1/users.py b/letta/server/rest_api/routers/v1/users.pyindex 4b4bfd918..d12315cdb 100644--- a/letta/server/rest_api/routers/v1/users.py+++ b/letta/server/rest_api/routers/v1/users.py@@ -65,7 +65,7 @@ async def delete_user(try:user = await server.user_manager.get_actor_by_id_async(actor_id=user_id)if user is None:- raise HTTPException(status_code=404, detail=f"User does not exist")+ raise HTTPException(status_code=404, detail="User does not exist")await server.user_manager.delete_actor_by_id_async(user_id=user_id)except HTTPException:raisediff --git a/letta/server/rest_api/streaming_response.py b/letta/server/rest_api/streaming_response.pyindex ac22c4697..4daf65a7f 100644--- a/letta/server/rest_api/streaming_response.py+++ b/letta/server/rest_api/streaming_response.py@@ -12,6 +12,7 @@ from starlette.types import Sendfrom letta.log import get_loggerfrom letta.schemas.enums import JobStatusfrom letta.schemas.user import User+from letta.server.rest_api.utils import capture_sentry_exceptionfrom letta.services.job_manager import JobManagerlogger = get_logger(__name__)@@ -92,6 +93,7 @@ class StreamingResponseWithStatusCode(StreamingResponse):more_body = Truetry:first_chunk = await self.body_iterator.__anext__()+ logger.debug("stream_response first chunk:", first_chunk)if isinstance(first_chunk, tuple):first_chunk_content, self.status_code = first_chunkelse:@@ -130,7 +132,7 @@ class StreamingResponseWithStatusCode(StreamingResponse):"more_body": more_body,})- return+ raise Exception(f"An exception occurred mid-stream with status code {status_code}", detail={"content": content})else:content = chunk@@ -146,8 +148,8 @@ class StreamingResponseWithStatusCode(StreamingResponse):)# This should be handled properly upstream?- except asyncio.CancelledError:- logger.info("Stream was cancelled by client or job cancellation")+ except asyncio.CancelledError as exc:+ logger.warning("Stream was cancelled by client or job cancellation")# Handle cancellation gracefullymore_body = Falsecancellation_resp = {"error": {"message": "Stream cancelled"}}@@ -160,6 +162,7 @@ class StreamingResponseWithStatusCode(StreamingResponse):"headers": self.raw_headers,})+ raiseawait send({"type": "http.response.body",@@ -167,13 +170,15 @@ class StreamingResponseWithStatusCode(StreamingResponse):"more_body": more_body,})+ capture_sentry_exception(exc)return- except Exception:- logger.exception("unhandled_streaming_error")+ except Exception as exc:+ logger.exception("Unhandled Streaming Error")more_body = Falseerror_resp = {"error": {"message": "Internal Server Error"}}error_event = f"event: error\ndata: {json.dumps(error_resp)}\n\n".encode(self.charset)+ logger.debug("response_started:", self.response_started)if not self.response_started:await send({@@ -182,6 +187,7 @@ class StreamingResponseWithStatusCode(StreamingResponse):"headers": self.raw_headers,})+ raiseawait send({"type": "http.response.body",@@ -189,5 +195,7 @@ class StreamingResponseWithStatusCode(StreamingResponse):"more_body": more_body,})+ capture_sentry_exception(exc)+ returnif more_body:await send({"type": "http.response.body", "body": b"", "more_body": False})diff --git a/letta/server/rest_api/utils.py b/letta/server/rest_api/utils.pyindex 394193e36..17077fe35 100644--- a/letta/server/rest_api/utils.py+++ b/letta/server/rest_api/utils.py@@ -2,7 +2,6 @@ import asyncioimport jsonimport osimport uuid-import warningsfrom enum import Enumfrom typing import TYPE_CHECKING, AsyncGenerator, Dict, Iterable, List, Optional, Union, cast@@ -34,12 +33,15 @@ from letta.schemas.message import Message, MessageCreate, ToolReturnfrom letta.schemas.tool_execution_result import ToolExecutionResultfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.schemas.user import User-from letta.server.rest_api.interface import StreamingServerInterfacefrom letta.system import get_heartbeat, package_function_responseif TYPE_CHECKING:from letta.server.server import SyncServer+SENTRY_ENABLED = bool(os.getenv("SENTRY_DSN"))++if SENTRY_ENABLED:+ import sentry_sdkSSE_PREFIX = "data: "SSE_SUFFIX = "\n\n"@@ -130,7 +132,7 @@ async def sse_async_generator(except Exception as e:log_error_to_sentry(e)logger.error(f"Caught unexpected Exception: {e}")- yield sse_formatter({"error": f"Stream failed (internal error occurred)"})+ yield sse_formatter({"error": "Stream failed (internal error occurred)"})except Exception as e:log_error_to_sentry(e)@@ -157,21 +159,9 @@ def get_user_id(user_id: Optional[str] = Header(None, alias="user_id")) -> Optioreturn user_id-def get_current_interface() -> StreamingServerInterface:- return StreamingServerInterface---def log_error_to_sentry(e):- import traceback-- traceback.print_exc()- warnings.warn(f"SSE stream generator failed: {e}")-- # Log the error, since the exception handler upstack (in FastAPI) won't catch it, because this may be a 200 response- # Print the stack trace- if (os.getenv("SENTRY_DSN") is not None) and (os.getenv("SENTRY_DSN") != ""):- import sentry_sdk-+def capture_sentry_exception(e: BaseException):+ """This will capture the exception in sentry, since the exception handler upstack (in FastAPI) won't catch it, because this may be a 200 response"""+ if SENTRY_ENABLED:sentry_sdk.capture_exception(e)@@ -184,8 +174,6 @@ def create_input_messages(input_messages: List[MessageCreate], agent_id: str, ti"""messages = convert_message_creates_to_messages(input_messages, agent_id, timezone, wrap_user_message=False, wrap_system_message=False)- for message in messages:- message.organization_id = actor.organization_idreturn messages@@ -224,7 +212,6 @@ def create_letta_messages_from_llm_response(assistant_message = Message(role=MessageRole.assistant,content=reasoning_content if reasoning_content else [],- organization_id=actor.organization_id,agent_id=agent_id,model=model,tool_calls=[tool_call],@@ -241,7 +228,6 @@ def create_letta_messages_from_llm_response(tool_message = Message(role=MessageRole.tool,content=[TextContent(text=package_function_response(function_call_success, function_response, timezone))],- organization_id=actor.organization_id,agent_id=agent_id,model=model,tool_calls=[],@@ -294,7 +280,6 @@ def create_heartbeat_system_message(heartbeat_system_message = Message(role=MessageRole.user,content=[TextContent(text=get_heartbeat(timezone, text_content))],- organization_id=actor.organization_id,agent_id=agent_id,model=model,tool_calls=[],@@ -370,7 +355,6 @@ def convert_in_context_letta_messages_to_openai(in_context_messages: List[Messagid=msg.id,role=msg.role,content=[TextContent(text=extracted_text)],- organization_id=msg.organization_id,agent_id=msg.agent_id,model=msg.model,name=msg.name,@@ -399,7 +383,6 @@ def convert_in_context_letta_messages_to_openai(in_context_messages: List[Messagid=msg.id,role=msg.role,content=[TextContent(text=actual_user_text)],- organization_id=msg.organization_id,agent_id=msg.agent_id,model=msg.model,name=msg.name,diff --git a/letta/server/server.py b/letta/server/server.pyindex af996ffc2..fcea1e8a7 100644--- a/letta/server/server.py+++ b/letta/server/server.py@@ -53,6 +53,7 @@ from letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import ArchivalMemorySummary, Memory, RecallMemorySummaryfrom letta.schemas.message import Message, MessageCreate, MessageUpdatefrom letta.schemas.passage import Passage, PassageUpdate+from letta.schemas.pip_requirement import PipRequirementfrom letta.schemas.providers import (AnthropicProvider,AzureProvider,@@ -104,7 +105,8 @@ from letta.services.telemetry_manager import TelemetryManagerfrom letta.services.tool_executor.tool_execution_manager import ToolExecutionManagerfrom letta.services.tool_manager import ToolManagerfrom letta.services.user_manager import UserManager-from letta.settings import model_settings, settings, tool_settings+from letta.settings import DatabaseChoice, model_settings, settings, tool_settings+from letta.streaming_interface import AgentChunkStreamingInterfacefrom letta.utils import get_friendly_error_msg, get_persona_text, make_keyconfig = LettaConfig.load()@@ -176,7 +178,7 @@ class SyncServer(Server):self,chaining: bool = True,max_chaining_steps: Optional[int] = 100,- default_interface_factory: Callable[[], AgentInterface] = lambda: CLIInterface(),+ default_interface_factory: Callable[[], AgentChunkStreamingInterface] = lambda: CLIInterface(),init_with_default_org_and_user: bool = True,# default_interface: AgentInterface = CLIInterface(),# default_persistence_manager_cls: PersistenceManager = LocalStateManager,@@ -195,7 +197,7 @@ class SyncServer(Server):# Initialize the metadata storeconfig = LettaConfig.load()- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:config.recall_storage_type = "postgres"config.recall_storage_uri = settings.letta_pg_uri_no_defaultconfig.archival_storage_type = "postgres"@@ -1244,6 +1246,7 @@ class SyncServer(Server):use_assistant_message: bool = True,assistant_message_tool_name: str = constants.DEFAULT_MESSAGE_TOOL,assistant_message_tool_kwarg: str = constants.DEFAULT_MESSAGE_TOOL_KWARG,+ include_err: Optional[bool] = None,) -> Union[List[Message], List[LettaMessage]]:records = await self.message_manager.list_messages_for_agent_async(agent_id=agent_id,@@ -1253,6 +1256,7 @@ class SyncServer(Server):limit=limit,ascending=not reverse,group_id=group_id,+ include_err=include_err,)if not return_message_object:@@ -1262,6 +1266,7 @@ class SyncServer(Server):assistant_message_tool_name=assistant_message_tool_name,assistant_message_tool_kwarg=assistant_message_tool_kwarg,reverse=reverse,+ include_err=include_err,)if reverse:@@ -2001,6 +2006,7 @@ class SyncServer(Server):tool_name: Optional[str] = None,tool_args_json_schema: Optional[Dict[str, Any]] = None,tool_json_schema: Optional[Dict[str, Any]] = None,+ pip_requirements: Optional[List[PipRequirement]] = None,) -> ToolReturnMessage:"""Run a tool from source code"""if tool_source_type is not None and tool_source_type != "python":@@ -2008,13 +2014,14 @@ class SyncServer(Server):# If tools_json_schema is explicitly passed in, override it on the created Tool objectif tool_json_schema:- tool = Tool(name=tool_name, source_code=tool_source, json_schema=tool_json_schema)+ tool = Tool(name=tool_name, source_code=tool_source, json_schema=tool_json_schema, pip_requirements=pip_requirements)else:# NOTE: we're creating a floating Tool object and NOT persisting to DBtool = Tool(name=tool_name,source_code=tool_source,args_json_schema=tool_args_json_schema,+ pip_requirements=pip_requirements,)assert tool.name is not None, "Failed to create tool object"diff --git a/letta/server/ws_api/server.py b/letta/server/ws_api/server.pyindex e2408ddaa..75b18aaba 100644--- a/letta/server/ws_api/server.py+++ b/letta/server/ws_api/server.py@@ -21,7 +21,7 @@ class WebSocketServer:def shutdown_server(self):try:self.interface.close()- print(f"Closed the WS interface")+ print("Closed the WS interface")except Exception as e:print(f"Closing the WS interface failed with: {e}")@@ -100,7 +100,7 @@ class WebSocketServer:await websocket.send(protocol.server_error(f"unrecognized client package data type: {data}"))except websockets.exceptions.ConnectionClosed:- print(f"[server] connection with client was closed")+ print("[server] connection with client was closed")finally:self.interface.unregister_client(websocket)diff --git a/letta/services/agent_file_manager.py b/letta/services/agent_file_manager.pynew file mode 100644index 000000000..da2789122--- /dev/null+++ b/letta/services/agent_file_manager.py@@ -0,0 +1,616 @@+from datetime import datetime, timezone+from typing import Dict, List++from letta.errors import AgentFileExportError, AgentFileImportError+from letta.log import get_logger+from letta.schemas.agent import AgentState, CreateAgent+from letta.schemas.agent_file import (+ AgentFileSchema,+ AgentSchema,+ BlockSchema,+ FileAgentSchema,+ FileSchema,+ GroupSchema,+ ImportResult,+ MessageSchema,+ SourceSchema,+ ToolSchema,+)+from letta.schemas.block import Block+from letta.schemas.file import FileMetadata+from letta.schemas.message import Message+from letta.schemas.source import Source+from letta.schemas.tool import Tool+from letta.schemas.user import User+from letta.services.agent_manager import AgentManager+from letta.services.block_manager import BlockManager+from letta.services.file_manager import FileManager+from letta.services.file_processor.embedder.base_embedder import BaseEmbedder+from letta.services.file_processor.file_processor import FileProcessor+from letta.services.file_processor.parser.mistral_parser import MistralFileParser+from letta.services.files_agents_manager import FileAgentManager+from letta.services.group_manager import GroupManager+from letta.services.mcp_manager import MCPManager+from letta.services.message_manager import MessageManager+from letta.services.source_manager import SourceManager+from letta.services.tool_manager import ToolManager+from letta.utils import get_latest_alembic_revision++logger = get_logger(__name__)+++class AgentFileManager:+ """+ Manages export and import of agent files between database and AgentFileSchema format.++ Handles:+ - ID mapping between database IDs and human-readable file IDs+ - Coordination across multiple entity managers+ - Transaction safety during imports+ - Referential integrity validation+ """++ def __init__(+ self,+ agent_manager: AgentManager,+ tool_manager: ToolManager,+ source_manager: SourceManager,+ block_manager: BlockManager,+ group_manager: GroupManager,+ mcp_manager: MCPManager,+ file_manager: FileManager,+ file_agent_manager: FileAgentManager,+ message_manager: MessageManager,+ embedder: BaseEmbedder,+ file_parser: MistralFileParser,+ using_pinecone: bool = False,+ ):+ self.agent_manager = agent_manager+ self.tool_manager = tool_manager+ self.source_manager = source_manager+ self.block_manager = block_manager+ self.group_manager = group_manager+ self.mcp_manager = mcp_manager+ self.file_manager = file_manager+ self.file_agent_manager = file_agent_manager+ self.message_manager = message_manager+ self.embedder = embedder+ self.file_parser = file_parser+ self.using_pinecone = using_pinecone++ # ID mapping state for export+ self._db_to_file_ids: Dict[str, str] = {}++ # Counters for generating Stripe-style IDs+ self._id_counters: Dict[str, int] = {+ AgentSchema.__id_prefix__: 0,+ GroupSchema.__id_prefix__: 0,+ BlockSchema.__id_prefix__: 0,+ FileSchema.__id_prefix__: 0,+ SourceSchema.__id_prefix__: 0,+ ToolSchema.__id_prefix__: 0,+ MessageSchema.__id_prefix__: 0,+ FileAgentSchema.__id_prefix__: 0,+ # MCPServerSchema.__id_prefix__: 0,+ }++ def _reset_state(self):+ """Reset internal state for a new operation"""+ self._db_to_file_ids.clear()+ for key in self._id_counters:+ self._id_counters[key] = 0++ def _generate_file_id(self, entity_type: str) -> str:+ """Generate a Stripe-style ID for the given entity type"""+ counter = self._id_counters[entity_type]+ file_id = f"{entity_type}-{counter}"+ self._id_counters[entity_type] += 1+ return file_id++ def _map_db_to_file_id(self, db_id: str, entity_type: str, allow_new: bool = True) -> str:+ """Map a database UUID to a file ID, creating if needed (export only)"""+ if db_id in self._db_to_file_ids:+ return self._db_to_file_ids[db_id]++ if not allow_new:+ raise AgentFileExportError(+ f"Unexpected new {entity_type} ID '{db_id}' encountered during conversion. "+ f"All IDs should have been mapped during agent processing."+ )++ file_id = self._generate_file_id(entity_type)+ self._db_to_file_ids[db_id] = file_id+ return file_id++ def _extract_unique_tools(self, agent_states: List[AgentState]) -> List:+ """Extract unique tools across all agent states by ID"""+ all_tools = []+ for agent_state in agent_states:+ if agent_state.tools:+ all_tools.extend(agent_state.tools)++ unique_tools = {}+ for tool in all_tools:+ unique_tools[tool.id] = tool++ return sorted(unique_tools.values(), key=lambda x: x.name)++ def _extract_unique_blocks(self, agent_states: List[AgentState]) -> List:+ """Extract unique blocks across all agent states by ID"""+ all_blocks = []+ for agent_state in agent_states:+ if agent_state.memory and agent_state.memory.blocks:+ all_blocks.extend(agent_state.memory.blocks)++ unique_blocks = {}+ for block in all_blocks:+ unique_blocks[block.id] = block++ return sorted(unique_blocks.values(), key=lambda x: x.label)++ async def _extract_unique_sources_and_files_from_agents(+ self, agent_states: List[AgentState], actor: User+ ) -> tuple[List[Source], List[FileMetadata]]:+ """Extract unique sources and files from agent states using bulk operations"""++ all_source_ids = set()+ all_file_ids = set()++ for agent_state in agent_states:+ files_agents = await self.file_agent_manager.list_files_for_agent(+ agent_id=agent_state.id, actor=actor, is_open_only=False, return_as_blocks=False+ )+ for file_agent in files_agents:+ all_source_ids.add(file_agent.source_id)+ all_file_ids.add(file_agent.file_id)+ sources = await self.source_manager.get_sources_by_ids_async(list(all_source_ids), actor)+ files = await self.file_manager.get_files_by_ids_async(list(all_file_ids), actor, include_content=True)++ return sources, files++ async def _convert_agent_state_to_schema(self, agent_state: AgentState, actor: User) -> AgentSchema:+ """Convert AgentState to AgentSchema with ID remapping"""++ agent_file_id = self._map_db_to_file_id(agent_state.id, AgentSchema.__id_prefix__)+ files_agents = await self.file_agent_manager.list_files_for_agent(+ agent_id=agent_state.id, actor=actor, is_open_only=False, return_as_blocks=False+ )+ agent_schema = await AgentSchema.from_agent_state(+ agent_state, message_manager=self.message_manager, files_agents=files_agents, actor=actor+ )+ agent_schema.id = agent_file_id++ if agent_schema.messages:+ for message in agent_schema.messages:+ message_file_id = self._map_db_to_file_id(message.id, MessageSchema.__id_prefix__)+ message.id = message_file_id+ message.agent_id = agent_file_id++ if agent_schema.in_context_message_ids:+ agent_schema.in_context_message_ids = [+ self._map_db_to_file_id(message_id, MessageSchema.__id_prefix__, allow_new=False)+ for message_id in agent_schema.in_context_message_ids+ ]++ if agent_schema.tool_ids:+ agent_schema.tool_ids = [self._map_db_to_file_id(tool_id, ToolSchema.__id_prefix__) for tool_id in agent_schema.tool_ids]++ if agent_schema.source_ids:+ agent_schema.source_ids = [+ self._map_db_to_file_id(source_id, SourceSchema.__id_prefix__) for source_id in agent_schema.source_ids+ ]++ if agent_schema.block_ids:+ agent_schema.block_ids = [self._map_db_to_file_id(block_id, BlockSchema.__id_prefix__) for block_id in agent_schema.block_ids]++ if agent_schema.files_agents:+ for file_agent in agent_schema.files_agents:+ file_agent.file_id = self._map_db_to_file_id(file_agent.file_id, FileSchema.__id_prefix__)+ file_agent.source_id = self._map_db_to_file_id(file_agent.source_id, SourceSchema.__id_prefix__)+ file_agent.agent_id = agent_file_id++ return agent_schema++ def _convert_tool_to_schema(self, tool) -> ToolSchema:+ """Convert Tool to ToolSchema with ID remapping"""+ tool_file_id = self._map_db_to_file_id(tool.id, ToolSchema.__id_prefix__, allow_new=False)+ tool_schema = ToolSchema.from_tool(tool)+ tool_schema.id = tool_file_id+ return tool_schema++ def _convert_block_to_schema(self, block) -> BlockSchema:+ """Convert Block to BlockSchema with ID remapping"""+ block_file_id = self._map_db_to_file_id(block.id, BlockSchema.__id_prefix__, allow_new=False)+ block_schema = BlockSchema.from_block(block)+ block_schema.id = block_file_id+ return block_schema++ def _convert_source_to_schema(self, source) -> SourceSchema:+ """Convert Source to SourceSchema with ID remapping"""+ source_file_id = self._map_db_to_file_id(source.id, SourceSchema.__id_prefix__, allow_new=False)+ source_schema = SourceSchema.from_source(source)+ source_schema.id = source_file_id+ return source_schema++ def _convert_file_to_schema(self, file_metadata) -> FileSchema:+ """Convert FileMetadata to FileSchema with ID remapping"""+ file_file_id = self._map_db_to_file_id(file_metadata.id, FileSchema.__id_prefix__, allow_new=False)+ file_schema = FileSchema.from_file_metadata(file_metadata)+ file_schema.id = file_file_id+ file_schema.source_id = self._map_db_to_file_id(file_metadata.source_id, SourceSchema.__id_prefix__, allow_new=False)+ return file_schema++ async def export(self, agent_ids: List[str], actor: User) -> AgentFileSchema:+ """+ Export agents and their related entities to AgentFileSchema format.++ Args:+ agent_ids: List of agent UUIDs to export++ Returns:+ AgentFileSchema with all related entities++ Raises:+ AgentFileExportError: If export fails+ """+ try:+ self._reset_state()++ agent_states = await self.agent_manager.get_agents_by_ids_async(agent_ids=agent_ids, actor=actor)++ # Validate that all requested agents were found+ if len(agent_states) != len(agent_ids):+ found_ids = {agent.id for agent in agent_states}+ missing_ids = [agent_id for agent_id in agent_ids if agent_id not in found_ids]+ raise AgentFileExportError(f"The following agent IDs were not found: {missing_ids}")++ # Extract unique entities across all agents+ tool_set = self._extract_unique_tools(agent_states)+ block_set = self._extract_unique_blocks(agent_states)++ # Extract sources and files from agent states BEFORE conversion+ source_set, file_set = await self._extract_unique_sources_and_files_from_agents(agent_states, actor)++ # Convert to schemas with ID remapping+ agent_schemas = [await self._convert_agent_state_to_schema(agent_state, actor=actor) for agent_state in agent_states]+ tool_schemas = [self._convert_tool_to_schema(tool) for tool in tool_set]+ block_schemas = [self._convert_block_to_schema(block) for block in block_set]+ source_schemas = [self._convert_source_to_schema(source) for source in source_set]+ file_schemas = [self._convert_file_to_schema(file_metadata) for file_metadata in file_set]++ logger.info(f"Exporting {len(agent_ids)} agents to agent file format")++ # Return AgentFileSchema with converted entities+ return AgentFileSchema(+ agents=agent_schemas,+ groups=[], # TODO: Extract and convert groups+ blocks=block_schemas,+ files=file_schemas,+ sources=source_schemas,+ tools=tool_schemas,+ # mcp_servers=[], # TODO: Extract and convert MCP servers+ metadata={"revision_id": await get_latest_alembic_revision()},+ created_at=datetime.now(timezone.utc),+ )++ except Exception as e:+ logger.error(f"Failed to export agent file: {e}")+ raise AgentFileExportError(f"Export failed: {e}") from e++ async def import_file(self, schema: AgentFileSchema, actor: User, dry_run: bool = False) -> ImportResult:+ """+ Import AgentFileSchema into the database.++ Args:+ schema: The agent file schema to import+ dry_run: If True, validate but don't commit changes++ Returns:+ ImportResult with success status and details++ Raises:+ AgentFileImportError: If import fails+ """+ try:+ self._reset_state()++ if dry_run:+ logger.info("Starting dry run import validation")+ else:+ logger.info("Starting agent file import")++ # Validate schema first+ self._validate_schema(schema)++ if dry_run:+ return ImportResult(+ success=True,+ message="Dry run validation passed",+ imported_count=0,+ )++ # Import in dependency order+ imported_count = 0+ file_to_db_ids = {} # Maps file IDs to new database IDs++ # 1. Create tools first (no dependencies)+ for tool_schema in schema.tools:+ # Convert ToolSchema back to ToolCreate+ created_tool = await self.tool_manager.create_or_update_tool_async(+ pydantic_tool=Tool(**tool_schema.model_dump(exclude={"id"})), actor=actor+ )+ file_to_db_ids[tool_schema.id] = created_tool.id+ imported_count += 1++ # 2. Create blocks (no dependencies)+ for block_schema in schema.blocks:+ # Convert BlockSchema back to CreateBlock+ block = Block(**block_schema.model_dump(exclude={"id"}))+ created_block = await self.block_manager.create_or_update_block_async(block, actor)+ file_to_db_ids[block_schema.id] = created_block.id+ imported_count += 1++ # 3. Create sources (no dependencies)+ for source_schema in schema.sources:+ # Convert SourceSchema back to Source+ source_data = source_schema.model_dump(exclude={"id", "embedding", "embedding_chunk_size"})+ source = Source(**source_data)+ created_source = await self.source_manager.create_source(source, actor)+ file_to_db_ids[source_schema.id] = created_source.id+ imported_count += 1++ # 4. Create files (depends on sources)+ for file_schema in schema.files:+ # Convert FileSchema back to FileMetadata+ file_data = file_schema.model_dump(exclude={"id", "content"})+ # Remap source_id from file ID to database ID+ file_data["source_id"] = file_to_db_ids[file_schema.source_id]+ file_metadata = FileMetadata(**file_data)+ created_file = await self.file_manager.create_file(file_metadata, actor, text=file_schema.content)+ file_to_db_ids[file_schema.id] = created_file.id+ imported_count += 1++ # 5. Process files for chunking/embedding (depends on files and sources)+ file_processor = FileProcessor(+ file_parser=self.file_parser,+ embedder=self.embedder,+ actor=actor,+ using_pinecone=self.using_pinecone,+ )++ for file_schema in schema.files:+ if file_schema.content: # Only process files with content+ file_db_id = file_to_db_ids[file_schema.id]+ source_db_id = file_to_db_ids[file_schema.source_id]++ # Get the created file metadata+ file_metadata = await self.file_manager.get_file_by_id(file_db_id, actor)++ # Save the db call of fetching content again+ file_metadata.content = file_schema.content++ # Process the file for chunking/embedding+ passages = await file_processor.process_imported_file(file_metadata=file_metadata, source_id=source_db_id)+ imported_count += len(passages)++ # 6. Create agents with empty message history+ for agent_schema in schema.agents:+ # Convert AgentSchema back to CreateAgent, remapping tool/block IDs+ agent_data = agent_schema.model_dump(exclude={"id", "in_context_message_ids", "messages"})++ # Remap tool_ids from file IDs to database IDs+ if agent_data.get("tool_ids"):+ agent_data["tool_ids"] = [file_to_db_ids[file_id] for file_id in agent_data["tool_ids"]]++ # Remap block_ids from file IDs to database IDs+ if agent_data.get("block_ids"):+ agent_data["block_ids"] = [file_to_db_ids[file_id] for file_id in agent_data["block_ids"]]++ agent_create = CreateAgent(**agent_data)+ created_agent = await self.agent_manager.create_agent_async(agent_create, actor, _init_with_no_messages=True)+ file_to_db_ids[agent_schema.id] = created_agent.id+ imported_count += 1++ # 7. Create messages and update agent message_ids+ for agent_schema in schema.agents:+ agent_db_id = file_to_db_ids[agent_schema.id]+ message_file_to_db_ids = {}++ # Create messages for this agent+ messages = []+ for message_schema in agent_schema.messages:+ # Convert MessageSchema back to Message, setting agent_id to new DB ID+ message_data = message_schema.model_dump(exclude={"id"})+ message_data["agent_id"] = agent_db_id # Remap agent_id to new database ID+ message_obj = Message(**message_data)+ messages.append(message_obj)+ # Map file ID to the generated database ID immediately+ message_file_to_db_ids[message_schema.id] = message_obj.id++ created_messages = await self.message_manager.create_many_messages_async(pydantic_msgs=messages, actor=actor)+ imported_count += len(created_messages)++ # Remap in_context_message_ids from file IDs to database IDs+ in_context_db_ids = [message_file_to_db_ids[message_schema_id] for message_schema_id in agent_schema.in_context_message_ids]++ # Update agent with the correct message_ids+ await self.agent_manager.update_message_ids_async(agent_id=agent_db_id, message_ids=in_context_db_ids, actor=actor)++ # 8. Create file-agent relationships (depends on agents and files)+ for agent_schema in schema.agents:+ if agent_schema.files_agents:+ agent_db_id = file_to_db_ids[agent_schema.id]++ # Prepare files for bulk attachment+ files_for_agent = []+ visible_content_map = {}++ for file_agent_schema in agent_schema.files_agents:+ file_db_id = file_to_db_ids[file_agent_schema.file_id]+ file_metadata = await self.file_manager.get_file_by_id(file_db_id, actor)+ files_for_agent.append(file_metadata)++ if file_agent_schema.visible_content:+ visible_content_map[file_db_id] = file_agent_schema.visible_content++ # Bulk attach files to agent+ await self.file_agent_manager.attach_files_bulk(+ agent_id=agent_db_id, files_metadata=files_for_agent, visible_content_map=visible_content_map, actor=actor+ )+ imported_count += len(files_for_agent)++ return ImportResult(+ success=True,+ message=f"Import completed successfully. Imported {imported_count} entities.",+ imported_count=imported_count,+ id_mappings=file_to_db_ids,+ )++ except Exception as e:+ logger.exception(f"Failed to import agent file: {e}")+ raise AgentFileImportError(f"Import failed: {e}") from e++ def _validate_id_format(self, schema: AgentFileSchema) -> List[str]:+ """Validate that all IDs follow the expected format"""+ errors = []++ # Define entity types and their expected prefixes+ entity_checks = [+ (schema.agents, AgentSchema.__id_prefix__),+ (schema.groups, GroupSchema.__id_prefix__),+ (schema.blocks, BlockSchema.__id_prefix__),+ (schema.files, FileSchema.__id_prefix__),+ (schema.sources, SourceSchema.__id_prefix__),+ (schema.tools, ToolSchema.__id_prefix__),+ ]++ for entities, expected_prefix in entity_checks:+ for entity in entities:+ if not entity.id.startswith(f"{expected_prefix}-"):+ errors.append(f"Invalid ID format: {entity.id} should start with '{expected_prefix}-'")+ else:+ # Check that the suffix is a valid integer+ try:+ suffix = entity.id[len(expected_prefix) + 1 :]+ int(suffix)+ except ValueError:+ errors.append(f"Invalid ID format: {entity.id} should have integer suffix")++ # Also check message IDs within agents+ for agent in schema.agents:+ for message in agent.messages:+ if not message.id.startswith(f"{MessageSchema.__id_prefix__}-"):+ errors.append(f"Invalid message ID format: {message.id} should start with '{MessageSchema.__id_prefix__}-'")+ else:+ # Check that the suffix is a valid integer+ try:+ suffix = message.id[len(MessageSchema.__id_prefix__) + 1 :]+ int(suffix)+ except ValueError:+ errors.append(f"Invalid message ID format: {message.id} should have integer suffix")++ return errors++ def _validate_duplicate_ids(self, schema: AgentFileSchema) -> List[str]:+ """Validate that there are no duplicate IDs within or across entity types"""+ errors = []+ all_ids = set()++ # Check each entity type for internal duplicates and collect all IDs+ entity_collections = [+ ("agents", schema.agents),+ ("groups", schema.groups),+ ("blocks", schema.blocks),+ ("files", schema.files),+ ("sources", schema.sources),+ ("tools", schema.tools),+ ]++ for entity_type, entities in entity_collections:+ entity_ids = [entity.id for entity in entities]++ # Check for duplicates within this entity type+ if len(entity_ids) != len(set(entity_ids)):+ duplicates = [id for id in entity_ids if entity_ids.count(id) > 1]+ errors.append(f"Duplicate {entity_type} IDs found: {set(duplicates)}")++ # Check for duplicates across all entity types+ for entity_id in entity_ids:+ if entity_id in all_ids:+ errors.append(f"Duplicate ID across entity types: {entity_id}")+ all_ids.add(entity_id)++ # Also check message IDs within agents+ for agent in schema.agents:+ message_ids = [msg.id for msg in agent.messages]++ # Check for duplicates within agent messages+ if len(message_ids) != len(set(message_ids)):+ duplicates = [id for id in message_ids if message_ids.count(id) > 1]+ errors.append(f"Duplicate message IDs in agent {agent.id}: {set(duplicates)}")++ # Check for duplicates across all entity types+ for message_id in message_ids:+ if message_id in all_ids:+ errors.append(f"Duplicate ID across entity types: {message_id}")+ all_ids.add(message_id)++ return errors++ def _validate_file_source_references(self, schema: AgentFileSchema) -> List[str]:+ """Validate that all file source_id references exist"""+ errors = []+ source_ids = {source.id for source in schema.sources}++ for file in schema.files:+ if file.source_id not in source_ids:+ errors.append(f"File {file.id} references non-existent source {file.source_id}")++ return errors++ def _validate_file_agent_references(self, schema: AgentFileSchema) -> List[str]:+ """Validate that all file-agent relationships reference existing entities"""+ errors = []+ file_ids = {file.id for file in schema.files}+ source_ids = {source.id for source in schema.sources}+ {agent.id for agent in schema.agents}++ for agent in schema.agents:+ for file_agent in agent.files_agents:+ if file_agent.file_id not in file_ids:+ errors.append(f"File-agent relationship references non-existent file {file_agent.file_id}")+ if file_agent.source_id not in source_ids:+ errors.append(f"File-agent relationship references non-existent source {file_agent.source_id}")+ if file_agent.agent_id != agent.id:+ errors.append(f"File-agent relationship has mismatched agent_id {file_agent.agent_id} vs {agent.id}")++ return errors++ def _validate_schema(self, schema: AgentFileSchema):+ """+ Validate the agent file schema for consistency and referential integrity.++ Args:+ schema: The schema to validate++ Raises:+ AgentFileImportError: If validation fails+ """+ errors = []++ # 1. ID Format Validation+ errors.extend(self._validate_id_format(schema))++ # 2. Duplicate ID Detection+ errors.extend(self._validate_duplicate_ids(schema))++ # 3. File Source Reference Validation+ errors.extend(self._validate_file_source_references(schema))++ # 4. File-Agent Reference Validation+ errors.extend(self._validate_file_agent_references(schema))++ if errors:+ raise AgentFileImportError(f"Schema validation failed: {'; '.join(errors)}")++ logger.info("Schema validation passed")diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.pyindex d9253a9ad..c41d81a34 100644--- a/letta/services/agent_manager.py+++ b/letta/services/agent_manager.py@@ -28,7 +28,7 @@ from letta.orm import AgentPassage, AgentsTagsfrom letta.orm import Block as BlockModelfrom letta.orm import BlocksAgentsfrom letta.orm import Group as GroupModel-from letta.orm import IdentitiesAgents+from letta.orm import GroupsAgents, IdentitiesAgentsfrom letta.orm import Source as SourceModelfrom letta.orm import SourcePassage, SourcesAgentsfrom letta.orm import Tool as ToolModel@@ -71,6 +71,7 @@ from letta.services.helpers.agent_manager_helper import (_apply_identity_filters,_apply_pagination,_apply_pagination_async,+ _apply_relationship_filters,_apply_tag_filter,_process_relationship,_process_relationship_async,@@ -84,12 +85,14 @@ from letta.services.helpers.agent_manager_helper import (derive_system_message,initialize_message_sequence,package_initial_message_sequence,+ validate_agent_exists_async,)from letta.services.identity_manager import IdentityManagerfrom letta.services.message_manager import MessageManagerfrom letta.services.passage_manager import PassageManagerfrom letta.services.source_manager import SourceManagerfrom letta.services.tool_manager import ToolManager+from letta.settings import DatabaseChoice, settingsfrom letta.utils import enforce_types, united_difflogger = get_logger(__name__)@@ -448,7 +451,11 @@ class AgentManager:@trace_methodasync def create_agent_async(- self, agent_create: CreateAgent, actor: PydanticUser, _test_only_force_id: Optional[str] = None+ self,+ agent_create: CreateAgent,+ actor: PydanticUser,+ _test_only_force_id: Optional[str] = None,+ _init_with_no_messages: bool = False,) -> PydanticAgentState:# validate required configsif not agent_create.llm_config or not agent_create.embedding_config:@@ -616,20 +623,36 @@ class AgentManager:]await session.execute(insert(AgentEnvironmentVariable).values(env_rows))- # initial message sequence- agent_state = await new_agent.to_pydantic_async(include_relationships={"memory"})- init_messages = self._generate_initial_message_sequence(- actor,- agent_state=agent_state,- supplied_initial_message_sequence=agent_create.initial_message_sequence,- )- new_agent.message_ids = [msg.id for msg in init_messages]-- await session.refresh(new_agent)-- result = await new_agent.to_pydantic_async()+ include_relationships = []+ if tool_ids:+ include_relationships.append("tools")+ if source_ids:+ include_relationships.append("sources")+ if block_ids:+ include_relationships.append("memory")+ if identity_ids:+ include_relationships.append("identity_ids")+ if tag_values:+ include_relationships.append("tags")++ result = await new_agent.to_pydantic_async(include_relationships=include_relationships)++ # initial message sequence (skip if _init_with_no_messages is True)+ if not _init_with_no_messages:+ init_messages = self._generate_initial_message_sequence(+ actor,+ agent_state=result,+ supplied_initial_message_sequence=agent_create.initial_message_sequence,+ )+ result.message_ids = [msg.id for msg in init_messages]+ new_agent.message_ids = [msg.id for msg in init_messages]+ await new_agent.update_async(session, no_refresh=True)+ else:+ init_messages = []- await self.message_manager.create_many_messages_async(pydantic_msgs=init_messages, actor=actor)+ # Only create messages if we initialized with messages+ if not _init_with_no_messages:+ await self.message_manager.create_many_messages_async(pydantic_msgs=init_messages, actor=actor)return result@enforce_types@@ -920,6 +943,30 @@ class AgentManager:return await agent.to_pydantic_async()+ @enforce_types+ @trace_method+ async def update_message_ids_async(+ self,+ agent_id: str,+ message_ids: List[str],+ actor: PydanticUser,+ ) -> None:+ async with db_registry.async_session() as session:+ query = select(AgentModel)+ query = AgentModel.apply_access_predicate(query, actor, ["read"], AccessType.ORGANIZATION)+ query = query.where(AgentModel.id == agent_id)+ query = _apply_relationship_filters(query, include_relationships=[])++ result = await session.execute(query)+ agent = result.scalar_one_or_none()++ agent.updated_at = datetime.now(timezone.utc)+ agent.last_updated_by_id = actor.id+ agent.message_ids = message_ids++ await agent.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)+ await session.commit()+# TODO: Make this general and think about how to roll this into sqlalchemybase@trace_methoddef list_agents(@@ -1019,7 +1066,8 @@ class AgentManager:identity_id (Optional[str]): Filter by identifier ID.identifier_keys (Optional[List[str]]): Search agents by identifier keys.include_relationships (Optional[List[str]]): List of fields to load for performance optimization.- ascending+ ascending (bool): Sort agents in ascending order.+ sort_by (Optional[str]): Sort agents by this field.Returns:List[PydanticAgentState]: The filtered list of matching agents.@@ -1032,11 +1080,11 @@ class AgentManager:query = _apply_filters(query, name, query_text, project_id, template_id, base_template_id)query = _apply_identity_filters(query, identity_id, identifier_keys)query = _apply_tag_filter(query, tags, match_all_tags)+ query = _apply_relationship_filters(query, include_relationships)query = await _apply_pagination_async(query, before, after, session, ascending=ascending, sort_by=sort_by)if limit:query = query.limit(limit)-result = await session.execute(query)agents = result.scalars().all()return await asyncio.gather(*[agent.to_pydantic_async(include_relationships=include_relationships) for agent in agents])@@ -1168,10 +1216,23 @@ class AgentManager:include_relationships: Optional[List[str]] = None,) -> PydanticAgentState:"""Fetch an agent by its ID."""-async with db_registry.async_session() as session:- agent = await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)- return await agent.to_pydantic_async(include_relationships=include_relationships)+ try:+ query = select(AgentModel)+ query = AgentModel.apply_access_predicate(query, actor, ["read"], AccessType.ORGANIZATION)+ query = query.where(AgentModel.id == agent_id)+ query = _apply_relationship_filters(query, include_relationships)++ result = await session.execute(query)+ agent = result.scalar_one_or_none()++ if agent is None:+ raise NoResultFound(f"Agent with ID {agent_id} not found")++ return await agent.to_pydantic_async(include_relationships=include_relationships)+ except Exception as e:+ logger.error(f"Error fetching agent {agent_id}: {str(e)}")+ raise@enforce_types@trace_method@@ -1183,12 +1244,23 @@ class AgentManager:) -> list[PydanticAgentState]:"""Fetch a list of agents by their IDs."""async with db_registry.async_session() as session:- agents = await AgentModel.read_multiple_async(- db_session=session,- identifiers=agent_ids,- actor=actor,- )- return await asyncio.gather(*[agent.to_pydantic_async(include_relationships=include_relationships) for agent in agents])+ try:+ query = select(AgentModel)+ query = AgentModel.apply_access_predicate(query, actor, ["read"], AccessType.ORGANIZATION)+ query = query.where(AgentModel.id.in_(agent_ids))+ query = _apply_relationship_filters(query, include_relationships)++ result = await session.execute(query)+ agents = result.scalars().all()++ if not agents:+ logger.warning(f"No agents found with IDs: {agent_ids}")+ return []++ return await asyncio.gather(*[agent.to_pydantic_async(include_relationships=include_relationships) for agent in agents])+ except Exception as e:+ logger.error(f"Error fetching agents with IDs {agent_ids}: {str(e)}")+ raise@enforce_types@trace_method@@ -1334,6 +1406,9 @@ class AgentManager:schema = MarshmallowAgentSchema(session=session, actor=actor)agent = schema.load(serialized_agent_dict, session=session)+ agent.organization_id = actor.organization_id+ for block in agent.core_memory:+ block.organization_id = actor.organization_idif append_copy_suffix:agent.name += "_copy"if project_id:@@ -1435,10 +1510,17 @@ class AgentManager:@trace_methoddef list_groups(self, agent_id: str, actor: PydanticUser, manager_type: Optional[str] = None) -> List[PydanticGroup]:with db_registry.session() as session:- agent = AgentModel.read(db_session=session, identifier=agent_id, actor=actor)+ query = (+ select(GroupModel)+ .join(GroupsAgents, GroupModel.id == GroupsAgents.group_id)+ .where(GroupsAgents.agent_id == agent_id, GroupModel.organization_id == actor.organization_id)+ )+if manager_type:- return [group.to_pydantic() for group in agent.groups if group.manager_type == manager_type]- return [group.to_pydantic() for group in agent.groups]+ query = query.where(GroupModel.manager_type == manager_type)++ result = session.execute(query)+ return [group.to_pydantic() for group in result.scalars()]# ======================================================================================================================# In Context Messages Management@@ -1559,15 +1641,9 @@ class AgentManager:Updates to the memory header should *not* trigger a rebuild, since that will simply flood recall storage with excess messages"""- num_messages_task = self.message_manager.size_async(actor=actor, agent_id=agent_id)- num_archival_memories_task = self.passage_manager.agent_passage_size_async(actor=actor, agent_id=agent_id)- agent_state_task = self.get_agent_by_id_async(agent_id=agent_id, include_relationships=["memory", "sources", "tools"], actor=actor)-- num_messages, num_archival_memories, agent_state = await asyncio.gather(- num_messages_task,- num_archival_memories_task,- agent_state_task,- )+ num_messages = await self.message_manager.size_async(actor=actor, agent_id=agent_id)+ num_archival_memories = await self.passage_manager.agent_passage_size_async(actor=actor, agent_id=agent_id)+ agent_state = await self.get_agent_by_id_async(agent_id=agent_id, include_relationships=["memory", "sources", "tools"], actor=actor)if not tool_rules_solver:tool_rules_solver = ToolRulesSolver(agent_state.tool_rules)@@ -1719,7 +1795,7 @@ class AgentManager:logger.error(f"Agent {agent_id} has no message_ids. Agent details: "f"name={agent.name}, created_at={agent.created_at}, "- f"message_ids={agent.message_ids}, organization_id={agent.organization_id}"+ f"message_ids={agent.message_ids}, organization_id={actor.organization_id}")raise ValueError(f"Agent {agent_id} has no message_ids - cannot preserve system message")@@ -1784,9 +1860,10 @@ class AgentManager:)# refresh memory from DB (using block ids)- blocks = await asyncio.gather(- *[self.block_manager.get_block_by_id_async(block.id, actor=actor) for block in agent_state.memory.get_blocks()]+ blocks = await self.block_manager.get_all_blocks_by_ids_async(+ block_ids=[b.id for b in agent_state.memory.get_blocks()], actor=actor)+agent_state.memory = Memory(blocks=blocks,file_blocks=agent_state.memory.file_blocks,@@ -1907,7 +1984,7 @@ class AgentManager:"""async with db_registry.async_session() as session:# Validate agent exists and user has access- await self._validate_agent_exists_async(session, agent_id, actor)+ await validate_agent_exists_async(session, agent_id, actor)# Use raw SQL to efficiently fetch sources - much faster than lazy loading# Fast query without relationship loading@@ -1943,7 +2020,7 @@ class AgentManager:"""async with db_registry.async_session() as session:# Validate agent exists and user has access- await self._validate_agent_exists_async(session, agent_id, actor)+ await validate_agent_exists_async(session, agent_id, actor)# Check if the source is actually attached to this agent using junction tableattachment_check_query = select(SourcesAgents).where(SourcesAgents.agent_id == agent_id, SourcesAgents.source_id == source_id)@@ -2710,7 +2787,7 @@ class AgentManager:"""async with db_registry.async_session() as session:# lightweight check for agent access- await self._validate_agent_exists_async(session, agent_id, actor)+ await validate_agent_exists_async(session, agent_id, actor)# direct query for tools via join - much more performantquery = (@@ -2752,7 +2829,12 @@ class AgentManager:)if query_text:- query = query.filter(AgentsTags.tag.ilike(f"%{query_text}%"))+ if settings.database_engine is DatabaseChoice.POSTGRES:+ # PostgreSQL: Use ILIKE for case-insensitive search+ query = query.filter(AgentsTags.tag.ilike(f"%{query_text}%"))+ else:+ # SQLite: Use LIKE with LOWER for case-insensitive search+ query = query.filter(func.lower(AgentsTags.tag).like(func.lower(f"%{query_text}%")))if after:query = query.filter(AgentsTags.tag > after)@@ -2788,7 +2870,12 @@ class AgentManager:)if query_text:- query = query.where(AgentsTags.tag.ilike(f"%{query_text}%"))+ if settings.database_engine is DatabaseChoice.POSTGRES:+ # PostgreSQL: Use ILIKE for case-insensitive search+ query = query.where(AgentsTags.tag.ilike(f"%{query_text}%"))+ else:+ # SQLite: Use LIKE with LOWER for case-insensitive search+ query = query.where(func.lower(AgentsTags.tag).like(func.lower(f"%{query_text}%")))if after:query = query.where(AgentsTags.tag > after)diff --git a/letta/services/block_manager.py b/letta/services/block_manager.pyindex 0c0203bd6..f4c0e5308 100644--- a/letta/services/block_manager.py+++ b/letta/services/block_manager.py@@ -1,12 +1,14 @@import asynciofrom typing import Dict, List, Optional-from sqlalchemy import select+from sqlalchemy import delete, selectfrom sqlalchemy.orm import Sessionfrom letta.log import get_logger+from letta.orm.agent import Agent as AgentModelfrom letta.orm.block import Block as BlockModelfrom letta.orm.block_history import BlockHistory+from letta.orm.blocks_agents import BlocksAgentsfrom letta.orm.errors import NoResultFoundfrom letta.otel.tracing import trace_methodfrom letta.schemas.agent import AgentState as PydanticAgentState@@ -50,8 +52,10 @@ class BlockManager:async with db_registry.async_session() as session:data = block.model_dump(to_orm=True, exclude_none=True)block = BlockModel(**data, organization_id=actor.organization_id)- await block.create_async(session, actor=actor)- return block.to_pydantic()+ await block.create_async(session, actor=actor, no_commit=True, no_refresh=True)+ pydantic_block = block.to_pydantic()+ await session.commit()+ return pydantic_block@enforce_types@trace_method@@ -95,11 +99,12 @@ class BlockManager:block_models = [BlockModel(**block.model_dump(to_orm=True, exclude_none=True), organization_id=actor.organization_id) for block in blocks]-- created_models = await BlockModel.batch_create_async(items=block_models, db_session=session, actor=actor)-- # Convert back to Pydantic- return [m.to_pydantic() for m in created_models]+ created_models = await BlockModel.batch_create_async(+ items=block_models, db_session=session, actor=actor, no_commit=True, no_refresh=True+ )+ result = [m.to_pydantic() for m in created_models]+ await session.commit()+ return result@enforce_types@trace_method@@ -130,26 +135,36 @@ class BlockManager:for key, value in update_data.items():setattr(block, key, value)- await block.update_async(db_session=session, actor=actor)- return block.to_pydantic()+ await block.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)+ pydantic_block = block.to_pydantic()+ await session.commit()+ return pydantic_block@enforce_types@trace_method- def delete_block(self, block_id: str, actor: PydanticUser) -> PydanticBlock:+ def delete_block(self, block_id: str, actor: PydanticUser) -> None:"""Delete a block by its ID."""with db_registry.session() as session:+ # First, delete all references in blocks_agents table+ session.execute(delete(BlocksAgents).where(BlocksAgents.block_id == block_id))+ session.flush()++ # Then delete the block itselfblock = BlockModel.read(db_session=session, identifier=block_id)block.hard_delete(db_session=session, actor=actor)- return block.to_pydantic()@enforce_types@trace_method- async def delete_block_async(self, block_id: str, actor: PydanticUser) -> PydanticBlock:+ async def delete_block_async(self, block_id: str, actor: PydanticUser) -> None:"""Delete a block by its ID."""async with db_registry.async_session() as session:+ # First, delete all references in blocks_agents table+ await session.execute(delete(BlocksAgents).where(BlocksAgents.block_id == block_id))+ await session.flush()++ # Then delete the block itselfblock = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor)await block.hard_delete_async(db_session=session, actor=actor)- return block.to_pydantic()@enforce_types@trace_method@@ -296,8 +311,14 @@ class BlockManager:Retrieve all agents associated with a given block."""async with db_registry.async_session() as session:- block = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor)- agents_orm = block.agents+ query = (+ select(AgentModel)+ .where(AgentModel.id.in_(select(BlocksAgents.agent_id).where(BlocksAgents.block_id == block_id)))+ .where(AgentModel.organization_id == actor.organization_id)+ )++ result = await session.execute(query)+ agents_orm = result.scalars().all()agents = await asyncio.gather(*[agent.to_pydantic_async(include_relationships=include_relationships) for agent in agents_orm])return agents@@ -531,7 +552,7 @@ class BlockManager:for block in blocks:new_val = updates[block.id]if len(new_val) > block.limit:- logger.warning(f"Value length ({len(new_val)}) exceeds limit " f"({block.limit}) for block {block.id!r}, truncating...")+ logger.warning(f"Value length ({len(new_val)}) exceeds limit ({block.limit}) for block {block.id!r}, truncating...")new_val = new_val[: block.limit]block.value = new_valdiff --git a/letta/services/file_manager.py b/letta/services/file_manager.pyindex 6aa86b16d..293354125 100644--- a/letta/services/file_manager.py+++ b/letta/services/file_manager.py@@ -1,3 +1,4 @@+import asyncioimport osfrom datetime import datetimefrom typing import List, Optional@@ -357,7 +358,9 @@ class FileManager:@enforce_types@trace_method- async def get_organization_sources_metadata(self, actor: PydanticUser) -> OrganizationSourcesStats:+ async def get_organization_sources_metadata(+ self, actor: PydanticUser, include_detailed_per_source_metadata: bool = False+ ) -> OrganizationSourcesStats:"""Get aggregated metadata for all sources in an organization with optimized queries.@@ -365,7 +368,7 @@ class FileManager:- Total number of sources- Total number of files across all sources- Total size of all files- - Per-source breakdown with file details+ - Per-source breakdown with file details (if include_detailed_per_source_metadata is True)"""async with db_registry.async_session() as session:# Import here to avoid circular imports@@ -395,31 +398,113 @@ class FileManager:for row in source_aggregations:source_id, source_name, file_count, total_size = row- # Get individual file details for this source- files_query = (- select(FileMetadataModel.id, FileMetadataModel.file_name, FileMetadataModel.file_size)- .where(- FileMetadataModel.source_id == source_id,- FileMetadataModel.organization_id == actor.organization_id,- FileMetadataModel.is_deleted == False,+ if include_detailed_per_source_metadata:+ # Get individual file details for this source+ files_query = (+ select(FileMetadataModel.id, FileMetadataModel.file_name, FileMetadataModel.file_size)+ .where(+ FileMetadataModel.source_id == source_id,+ FileMetadataModel.organization_id == actor.organization_id,+ FileMetadataModel.is_deleted == False,+ )+ .order_by(FileMetadataModel.file_name))- .order_by(FileMetadataModel.file_name)- )- files_result = await session.execute(files_query)- files_rows = files_result.fetchall()+ files_result = await session.execute(files_query)+ files_rows = files_result.fetchall()- # Build file stats- files = [FileStats(file_id=file_row[0], file_name=file_row[1], file_size=file_row[2]) for file_row in files_rows]+ # Build file stats+ files = [FileStats(file_id=file_row[0], file_name=file_row[1], file_size=file_row[2]) for file_row in files_rows]- # Build source metadata- source_metadata = SourceStats(- source_id=source_id, source_name=source_name, file_count=file_count, total_size=total_size, files=files- )+ # Build source metadata+ source_metadata = SourceStats(+ source_id=source_id, source_name=source_name, file_count=file_count, total_size=total_size, files=files+ )++ metadata.sources.append(source_metadata)- metadata.sources.append(source_metadata)metadata.total_files += file_countmetadata.total_size += total_size- metadata.total_sources = len(metadata.sources)+ metadata.total_sources = len(source_aggregations)return metadata++ @enforce_types+ @trace_method+ async def get_files_by_ids_async(+ self, file_ids: List[str], actor: PydanticUser, *, include_content: bool = False+ ) -> List[PydanticFileMetadata]:+ """+ Get multiple files by their IDs in a single query.++ Args:+ file_ids: List of file IDs to retrieve+ actor: User performing the action+ include_content: Whether to include file content in the response++ Returns:+ List[PydanticFileMetadata]: List of files (may be fewer than requested if some don't exist)+ """+ if not file_ids:+ return []++ async with db_registry.async_session() as session:+ query = select(FileMetadataModel).where(+ FileMetadataModel.id.in_(file_ids),+ FileMetadataModel.organization_id == actor.organization_id,+ FileMetadataModel.is_deleted == False,+ )++ # Eagerly load content if requested+ if include_content:+ query = query.options(selectinload(FileMetadataModel.content))++ result = await session.execute(query)+ files_orm = result.scalars().all()++ return await asyncio.gather(*[file.to_pydantic_async(include_content=include_content) for file in files_orm])++ @enforce_types+ @trace_method+ async def get_files_for_agents_async(+ self, agent_ids: List[str], actor: PydanticUser, *, include_content: bool = False+ ) -> List[PydanticFileMetadata]:+ """+ Get all files associated with the given agents via file-agent relationships.++ Args:+ agent_ids: List of agent IDs to find files for+ actor: User performing the action+ include_content: Whether to include file content in the response++ Returns:+ List[PydanticFileMetadata]: List of unique files associated with these agents+ """+ if not agent_ids:+ return []++ async with db_registry.async_session() as session:+ # We need to import FileAgent here to avoid circular imports+ from letta.orm.file_agent import FileAgent as FileAgentModel++ # Join through file-agent relationships+ query = (+ select(FileMetadataModel)+ .join(FileAgentModel, FileMetadataModel.id == FileAgentModel.file_id)+ .where(+ FileAgentModel.agent_id.in_(agent_ids),+ FileMetadataModel.organization_id == actor.organization_id,+ FileMetadataModel.is_deleted == False,+ FileAgentModel.is_deleted == False,+ )+ .distinct() # Ensure we don't get duplicate files+ )++ # Eagerly load content if requested+ if include_content:+ query = query.options(selectinload(FileMetadataModel.content))++ result = await session.execute(query)+ files_orm = result.scalars().all()++ return await asyncio.gather(*[file.to_pydantic_async(include_content=include_content) for file in files_orm])diff --git a/letta/services/file_processor/file_processor.py b/letta/services/file_processor/file_processor.pyindex 4dec0ac22..09b0e51fc 100644--- a/letta/services/file_processor/file_processor.py+++ b/letta/services/file_processor/file_processor.py@@ -1,5 +1,7 @@from typing import List+from mistralai import OCRPageObject, OCRResponse, OCRUsageInfo+from letta.log import get_loggerfrom letta.otel.context import get_ctx_attributesfrom letta.otel.tracing import log_event, trace_method@@ -221,3 +223,94 @@ class FileProcessor:)return []++ def _create_ocr_response_from_content(self, content: str):+ """Create minimal OCR response from existing content"""+ return OCRResponse(+ model="import-skip-ocr",+ pages=[+ OCRPageObject(+ index=0,+ markdown=content,+ images=[],+ dimensions=None,+ )+ ],+ usage_info=OCRUsageInfo(pages_processed=1),+ document_annotation=None,+ )++ @trace_method+ async def process_imported_file(self, file_metadata: FileMetadata, source_id: str) -> List[Passage]:+ """Process an imported file that already has content - skip OCR, do chunking/embedding"""+ filename = file_metadata.file_name++ if not file_metadata.content:+ logger.warning(f"No content found for imported file {filename}")+ return []++ content = file_metadata.content+ try:+ # Create OCR response from existing content+ ocr_response = self._create_ocr_response_from_content(content)++ # Update file status to embedding+ file_metadata = await self.file_manager.update_file_status(+ file_id=file_metadata.id, actor=self.actor, processing_status=FileProcessingStatus.EMBEDDING+ )++ logger.info(f"Chunking imported file content for {filename}")+ log_event("file_processor.import_chunking_started", {"filename": filename, "content_length": len(content)})++ # Chunk and embed using existing logic+ all_passages = await self._chunk_and_embed_with_fallback(+ file_metadata=file_metadata, ocr_response=ocr_response, source_id=source_id+ )++ # Create passages in database (unless using Pinecone)+ if not self.using_pinecone:+ all_passages = await self.passage_manager.create_many_source_passages_async(+ passages=all_passages, file_metadata=file_metadata, actor=self.actor+ )+ log_event("file_processor.import_passages_created", {"filename": filename, "total_passages": len(all_passages)})++ # Update file status to completed+ if not self.using_pinecone:+ await self.file_manager.update_file_status(+ file_id=file_metadata.id, actor=self.actor, processing_status=FileProcessingStatus.COMPLETED+ )+ else:+ await self.file_manager.update_file_status(+ file_id=file_metadata.id, actor=self.actor, total_chunks=len(all_passages), chunks_embedded=0+ )++ logger.info(f"Successfully processed imported file {filename}: {len(all_passages)} passages")+ log_event(+ "file_processor.import_processing_completed",+ {+ "filename": filename,+ "file_id": str(file_metadata.id),+ "total_passages": len(all_passages),+ "status": FileProcessingStatus.COMPLETED.value,+ },+ )++ return all_passages++ except Exception as e:+ logger.exception("Import file processing failed for %s: %s", filename, e)+ log_event(+ "file_processor.import_processing_failed",+ {+ "filename": filename,+ "file_id": str(file_metadata.id),+ "error": str(e),+ "error_type": type(e).__name__,+ "status": FileProcessingStatus.ERROR.value,+ },+ )+ await self.file_manager.update_file_status(+ file_id=file_metadata.id, actor=self.actor, processing_status=FileProcessingStatus.ERROR, error_message=str(e)+ )++ return []diff --git a/letta/services/files_agents_manager.py b/letta/services/files_agents_manager.pyindex 0264f8dc8..9d8cc838f 100644--- a/letta/services/files_agents_manager.py+++ b/letta/services/files_agents_manager.py@@ -573,3 +573,31 @@ class FileAgentManager:if not assoc:raise NoResultFound(f"FileAgent(agent_id={agent_id}, file_name={file_name}) not found in org {actor.organization_id}")return assoc++ @enforce_types+ @trace_method+ async def get_files_agents_for_agents_async(self, agent_ids: List[str], actor: PydanticUser) -> List[PydanticFileAgent]:+ """+ Get all file-agent relationships for multiple agents in a single query.++ Args:+ agent_ids: List of agent IDs to find file-agent relationships for+ actor: User performing the action++ Returns:+ List[PydanticFileAgent]: List of file-agent relationships for these agents+ """+ if not agent_ids:+ return []++ async with db_registry.async_session() as session:+ query = select(FileAgentModel).where(+ FileAgentModel.agent_id.in_(agent_ids),+ FileAgentModel.organization_id == actor.organization_id,+ FileAgentModel.is_deleted == False,+ )++ result = await session.execute(query)+ file_agents_orm = result.scalars().all()++ return [file_agent.to_pydantic() for file_agent in file_agents_orm]diff --git a/letta/services/group_manager.py b/letta/services/group_manager.pyindex 2be87789c..96684271e 100644--- a/letta/services/group_manager.py+++ b/letta/services/group_manager.py@@ -18,7 +18,6 @@ from letta.utils import enforce_typesclass GroupManager:-@enforce_types@trace_methoddef list_groups(@@ -164,7 +163,7 @@ class GroupManager:manager_agent_id = Noneif group_update.manager_config:if group_update.manager_config.manager_type != group.manager_type:- raise ValueError(f"Cannot change group pattern after creation")+ raise ValueError("Cannot change group pattern after creation")match group_update.manager_config.manager_type:case ManagerType.round_robin:max_turns = group_update.manager_config.max_turns@@ -473,7 +472,7 @@ class GroupManager:# 1) require both-or-noneif (max_value is None) != (min_value is None):raise ValueError(- f"Both '{max_name}' and '{min_name}' must be provided together " f"(got {max_name}={max_value}, {min_name}={min_value})"+ f"Both '{max_name}' and '{min_name}' must be provided together (got {max_name}={max_value}, {min_name}={min_value})")# no further checks if neither is provided@@ -488,9 +487,9 @@ class GroupManager:)if max_value <= 4 or min_value <= 4:raise ValueError(- f"Both '{max_name}' and '{min_name}' must be greater than 4 " f"(got {max_name}={max_value}, {min_name}={min_value})"+ f"Both '{max_name}' and '{min_name}' must be greater than 4 (got {max_name}={max_value}, {min_name}={min_value})")# 3) orderingif max_value <= min_value:- raise ValueError(f"'{max_name}' must be greater than '{min_name}' " f"(got {max_name}={max_value} <= {min_name}={min_value})")+ raise ValueError(f"'{max_name}' must be greater than '{min_name}' (got {max_name}={max_value} <= {min_name}={min_value})")diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.pyindex 4e262de09..7c46219d8 100644--- a/letta/services/helpers/agent_manager_helper.py+++ b/letta/services/helpers/agent_manager_helper.py@@ -4,6 +4,7 @@ from typing import List, Literal, Optional, Setimport numpy as npfrom sqlalchemy import Select, and_, asc, desc, func, literal, nulls_last, or_, select, union_all+from sqlalchemy.orm import noloadfrom sqlalchemy.sql.expression import existsfrom letta import system@@ -37,7 +38,7 @@ from letta.schemas.memory import Memoryfrom letta.schemas.message import Message, MessageCreatefrom letta.schemas.tool_rule import ToolRulefrom letta.schemas.user import User-from letta.settings import settings+from letta.settings import DatabaseChoice, settingsfrom letta.system import get_initial_boot_messages, get_login_event, package_function_response@@ -382,7 +383,6 @@ def package_initial_message_sequence(role=message_create.role,content=[TextContent(text=packed_message)],name=message_create.name,- organization_id=actor.organization_id,agent_id=agent_id,model=model,)@@ -397,7 +397,6 @@ def package_initial_message_sequence(role=message_create.role,content=[TextContent(text=packed_message)],name=message_create.name,- organization_id=actor.organization_id,agent_id=agent_id,model=model,)@@ -418,7 +417,6 @@ def package_initial_message_sequence(role=MessageRole.assistant,content=None,name=message_create.name,- organization_id=actor.organization_id,agent_id=agent_id,model=model,tool_calls=[@@ -438,7 +436,6 @@ def package_initial_message_sequence(role=MessageRole.tool,content=[TextContent(text=function_response)],name=message_create.name,- organization_id=actor.organization_id,agent_id=agent_id,model=model,tool_call_id=tool_call_id,@@ -551,6 +548,9 @@ async def _apply_pagination_async(result = (await session.execute(select(sort_column, AgentModel.id).where(AgentModel.id == after))).first()if result:after_sort_value, after_id = result+ # SQLite does not support as granular timestamping, so we need to round the timestamp+ if settings.database_engine is DatabaseChoice.SQLITE and isinstance(after_sort_value, datetime):+ after_sort_value = after_sort_value.strftime("%Y-%m-%d %H:%M:%S")query = query.where(_cursor_filter(sort_column, AgentModel.id, after_sort_value, after_id, forward=ascending, nulls_last=sort_nulls_last))@@ -559,6 +559,9 @@ async def _apply_pagination_async(result = (await session.execute(select(sort_column, AgentModel.id).where(AgentModel.id == before))).first()if result:before_sort_value, before_id = result+ # SQLite does not support as granular timestamping, so we need to round the timestamp+ if settings.database_engine is DatabaseChoice.SQLITE and isinstance(before_sort_value, datetime):+ before_sort_value = before_sort_value.strftime("%Y-%m-%d %H:%M:%S")query = query.where(_cursor_filter(sort_column, AgentModel.id, before_sort_value, before_id, forward=not ascending, nulls_last=sort_nulls_last))@@ -649,7 +652,12 @@ def _apply_filters(query = query.where(AgentModel.name == name)# Apply a case-insensitive partial match for the agent's name.if query_text:- query = query.where(AgentModel.name.ilike(f"%{query_text}%"))+ if settings.database_engine is DatabaseChoice.POSTGRES:+ # PostgreSQL: Use ILIKE for case-insensitive search+ query = query.where(AgentModel.name.ilike(f"%{query_text}%"))+ else:+ # SQLite: Use LIKE with LOWER for case-insensitive search+ query = query.where(func.lower(AgentModel.name).like(func.lower(f"%{query_text}%")))# Filter agents by project ID.if project_id:query = query.where(AgentModel.project_id == project_id)@@ -662,6 +670,24 @@ def _apply_filters(return query+def _apply_relationship_filters(query, include_relationships: Optional[List[str]] = None):+ if include_relationships is None:+ return query++ if "memory" not in include_relationships:+ query = query.options(noload(AgentModel.core_memory), noload(AgentModel.file_agents))+ if "identity_ids" not in include_relationships:+ query = query.options(noload(AgentModel.identities))++ relationships = ["tool_exec_environment_variables", "tools", "sources", "tags", "multi_agent_group"]++ for rel in relationships:+ if rel not in include_relationships:+ query = query.options(noload(getattr(AgentModel, rel)))++ return query++def build_passage_query(actor: User,agent_id: Optional[str] = None,@@ -790,7 +816,7 @@ def build_passage_query(# Vector searchif embedded_text:- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:# PostgreSQL with pgvectormain_query = main_query.order_by(combined_query.c.embedding.cosine_distance(embedded_text).asc())else:@@ -917,7 +943,7 @@ def build_source_passage_query(# Handle text search or vector searchif embedded_text:- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:# PostgreSQL with pgvectorquery = query.order_by(SourcePassage.embedding.cosine_distance(embedded_text).asc())else:@@ -1004,7 +1030,7 @@ def build_agent_passage_query(# Handle text search or vector searchif embedded_text:- if settings.letta_pg_uri_no_default:+ if settings.database_engine is DatabaseChoice.POSTGRES:# PostgreSQL with pgvectorquery = query.order_by(AgentPassage.embedding.cosine_distance(embedded_text).asc())else:@@ -1070,3 +1096,25 @@ def calculate_multi_agent_tools() -> Set[str]:return set(MULTI_AGENT_TOOLS) - set(LOCAL_ONLY_MULTI_AGENT_TOOLS)else:return set(MULTI_AGENT_TOOLS)+++@trace_method+async def validate_agent_exists_async(session, agent_id: str, actor: User) -> None:+ """+ Validate that an agent exists and user has access to it using raw SQL for efficiency.++ Args:+ session: Database session+ agent_id: ID of the agent to validate+ actor: User performing the action++ Raises:+ NoResultFound: If agent doesn't exist or user doesn't have access+ """+ agent_exists_query = select(+ exists().where(and_(AgentModel.id == agent_id, AgentModel.organization_id == actor.organization_id, AgentModel.is_deleted == False))+ )+ result = await session.execute(agent_exists_query)++ if not result.scalar():+ raise NoResultFound(f"Agent with ID {agent_id} not found")diff --git a/letta/services/identity_manager.py b/letta/services/identity_manager.pyindex abf637bac..da04e9071 100644--- a/letta/services/identity_manager.py+++ b/letta/services/identity_manager.py@@ -6,12 +6,14 @@ from sqlalchemy.exc import NoResultFoundfrom letta.orm.agent import Agent as AgentModelfrom letta.orm.block import Block as BlockModel+from letta.orm.errors import UniqueConstraintViolationErrorfrom letta.orm.identity import Identity as IdentityModelfrom letta.otel.tracing import trace_methodfrom letta.schemas.identity import Identity as PydanticIdentityfrom letta.schemas.identity import IdentityCreate, IdentityProperty, IdentityType, IdentityUpdate, IdentityUpsertfrom letta.schemas.user import User as PydanticUserfrom letta.server.db import db_registry+from letta.settings import DatabaseChoice, settingsfrom letta.utils import enforce_types@@ -64,6 +66,26 @@ class IdentityManager:async def _create_identity_async(self, db_session, identity: IdentityCreate, actor: PydanticUser) -> PydanticIdentity:new_identity = IdentityModel(**identity.model_dump(exclude={"agent_ids", "block_ids"}, exclude_unset=True))new_identity.organization_id = actor.organization_id++ # For SQLite compatibility: check for unique constraint violation manually+ # since SQLite doesn't support postgresql_nulls_not_distinct=True+ if settings.database_engine is DatabaseChoice.SQLITE:+ # Check if an identity with the same identifier_key, project_id, and organization_id exists+ query = select(IdentityModel).where(+ IdentityModel.identifier_key == new_identity.identifier_key,+ IdentityModel.project_id == new_identity.project_id,+ IdentityModel.organization_id == new_identity.organization_id,+ )+ result = await db_session.execute(query)+ existing_identity = result.scalar_one_or_none()+ if existing_identity is not None:+ raise UniqueConstraintViolationError(+ f"A unique constraint was violated for Identity. "+ f"An identity with identifier_key='{new_identity.identifier_key}', "+ f"project_id='{new_identity.project_id}', and "+ f"organization_id='{new_identity.organization_id}' already exists."+ )+await self._process_relationship_async(db_session=db_session,identity=new_identity,diff --git a/letta/services/job_manager.py b/letta/services/job_manager.pyindex dbba4a91d..b192afa8e 100644--- a/letta/services/job_manager.py+++ b/letta/services/job_manager.py@@ -1,3 +1,4 @@+from datetime import datetimefrom functools import partial, reducefrom operator import addfrom typing import List, Literal, Optional, Union@@ -27,6 +28,7 @@ from letta.schemas.step import Step as PydanticStepfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.schemas.user import User as PydanticUserfrom letta.server.db import db_registry+from letta.settings import DatabaseChoice, settingsfrom letta.utils import enforce_typeslogger = get_logger(__name__)@@ -60,15 +62,29 @@ class JobManager:pydantic_job.user_id = actor.idjob_data = pydantic_job.model_dump(to_orm=True)job = JobModel(**job_data)- await job.create_async(session, actor=actor) # Save job in the database- return job.to_pydantic()+ job = await job.create_async(session, actor=actor, no_commit=True, no_refresh=True) # Save job in the database+ result = job.to_pydantic()+ await session.commit()+ return result@enforce_types@trace_methoddef update_job_by_id(self, job_id: str, job_update: JobUpdate, actor: PydanticUser) -> PydanticJob:"""Update a job by its ID with the given JobUpdate object."""+ # First check if we need to dispatch a callback+ needs_callback = False+ callback_url = None+ with db_registry.session() as session:+ job = self._verify_job_access(session=session, job_id=job_id, actor=actor, access=["write"])+ not_completed_before = not bool(job.completed_at)++ # Check if we'll need to dispatch callback+ if job_update.status in {JobStatus.completed, JobStatus.failed} and not_completed_before and job.callback_url:+ needs_callback = True+ callback_url = job.callback_url++ # Update the job first to get the final metadatawith db_registry.session() as session:- # Fetch the job by IDjob = self._verify_job_access(session=session, job_id=job_id, actor=actor, access=["write"])not_completed_before = not bool(job.completed_at)@@ -84,24 +100,66 @@ class JobManager:if job_update.status in {JobStatus.completed, JobStatus.failed} and not_completed_before:job.completed_at = get_utc_time().replace(tzinfo=None)- if job.callback_url:- self._dispatch_callback(job)- # Save the updated job to the database- job.update(db_session=session, actor=actor)-- return job.to_pydantic()+ # Save the updated job to the database first+ job = job.update(db_session=session, actor=actor)++ # Get the updated metadata for callback+ final_metadata = job.metadata_+ result = job.to_pydantic()++ # Dispatch callback outside of database session if needed+ if needs_callback:+ callback_info = {+ "job_id": job_id,+ "callback_url": callback_url,+ "status": job_update.status,+ "completed_at": get_utc_time().replace(tzinfo=None),+ "metadata": final_metadata,+ }+ callback_result = self._dispatch_callback_sync(callback_info)++ # Update callback status in a separate transaction+ with db_registry.session() as session:+ job = self._verify_job_access(session=session, job_id=job_id, actor=actor, access=["write"])+ job.callback_sent_at = callback_result["callback_sent_at"]+ job.callback_status_code = callback_result.get("callback_status_code")+ job.callback_error = callback_result.get("callback_error")+ job.update(db_session=session, actor=actor)+ result = job.to_pydantic()++ return result@enforce_types@trace_method- async def update_job_by_id_async(self, job_id: str, job_update: JobUpdate, actor: PydanticUser) -> PydanticJob:+ async def update_job_by_id_async(+ self, job_id: str, job_update: JobUpdate, actor: PydanticUser, safe_update: bool = False+ ) -> PydanticJob:"""Update a job by its ID with the given JobUpdate object asynchronously."""- callback_func = None-+ # First check if we need to dispatch a callback+ needs_callback = False+ callback_url = Noneasync with db_registry.async_session() as session:- # Fetch the job by IDjob = await self._verify_job_access_async(session=session, job_id=job_id, actor=actor, access=["write"])+ # Safely update job status with state transition guards: Created -> Pending -> Running --> <Terminal>+ if safe_update:+ current_status = JobStatus(job.status)+ if not any(+ (+ job_update.status.is_terminal and not current_status.is_terminal,+ current_status == JobStatus.created and job_update.status != JobStatus.created,+ current_status == JobStatus.pending and job_update.status == JobStatus.running,+ )+ ):+ logger.error(f"Invalid job status transition from {current_status} to {job_update.status} for job {job_id}")+ raise ValueError(f"Invalid job status transition from {current_status} to {job_update.status}")++ # Check if we'll need to dispatch callback+ if job_update.status in {JobStatus.completed, JobStatus.failed} and job.callback_url:+ needs_callback = True+ callback_url = job.callback_url+# Update job attributes with only the fields that were explicitly setupdate_data = job_update.model_dump(to_orm=True, exclude_unset=True, exclude_none=True)@@ -116,25 +174,37 @@ class JobManager:if job_update.status in {JobStatus.completed, JobStatus.failed}:logger.info(f"Current job completed at: {job.completed_at}")job.completed_at = get_utc_time().replace(tzinfo=None)- if job.callback_url:- callback_func = self._dispatch_callback_async(- callback_url=job.callback_url,- payload={- "job_id": job.id,- "status": job.status,- "completed_at": job.completed_at.isoformat() if job.completed_at else None,- "metadata": job.metadata_,- },- actor=actor,- )- # Save the updated job to the database- await job.update_async(db_session=session, actor=actor)+ # Save the updated job to the database first+ job = await job.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)- if callback_func:- return await callback_func+ # Get the updated metadata for callback+ final_metadata = job.metadata_+ result = job.to_pydantic()+ await session.commit()- return job.to_pydantic()+ # Dispatch callback outside of database session if needed+ if needs_callback:+ callback_info = {+ "job_id": job_id,+ "callback_url": callback_url,+ "status": job_update.status,+ "completed_at": get_utc_time().replace(tzinfo=None),+ "metadata": final_metadata,+ }+ callback_result = await self._dispatch_callback_async(callback_info)++ # Update callback status in a separate transaction+ async with db_registry.async_session() as session:+ job = await self._verify_job_access_async(session=session, job_id=job_id, actor=actor, access=["write"])+ job.callback_sent_at = callback_result["callback_sent_at"]+ job.callback_status_code = callback_result.get("callback_status_code")+ job.callback_error = callback_result.get("callback_error")+ await job.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)+ result = job.to_pydantic()+ await session.commit()++ return result@enforce_types@trace_method@@ -149,20 +219,6 @@ class JobManager:True if update was successful, False if update was skipped due to invalid transition"""try:- # Get current job state- current_job = await self.get_job_by_id_async(job_id=job_id, actor=actor)-- current_status = current_job.status- if not any(- (- new_status.is_terminal and not current_status.is_terminal,- current_status == JobStatus.created and new_status != JobStatus.created,- current_status == JobStatus.pending and new_status == JobStatus.running,- )- ):- logger.warning(f"Invalid job status transition from {current_job.status} to {new_status} for job {job_id}")- return False-job_update_builder = partial(JobUpdate, status=new_status)if metadata:job_update_builder = partial(job_update_builder, metadata=metadata)@@ -238,24 +294,90 @@ class JobManager:source_id: Optional[str] = None,) -> List[PydanticJob]:"""List all jobs with optional pagination and status filter."""+ from sqlalchemy import and_, or_, select+async with db_registry.async_session() as session:- filter_kwargs = {"user_id": actor.id, "job_type": job_type}+ # build base query+ query = select(JobModel).where(JobModel.user_id == actor.id).where(JobModel.job_type == job_type)- # Add status filter if provided+ # add status filter if providedif statuses:- filter_kwargs["status"] = statuses+ query = query.where(JobModel.status.in_(statuses))+ # add source_id filter if providedif source_id:- filter_kwargs["metadata_.source_id"] = source_id+ column = getattr(JobModel, "metadata_")+ column = column.op("->>")("source_id")+ query = query.where(column == source_id)++ # handle cursor-based pagination+ if before or after:+ # get cursor objects+ before_obj = None+ after_obj = None++ if before:+ before_obj = await session.get(JobModel, before)+ if not before_obj:+ raise ValueError(f"Job with id {before} not found")++ if after:+ after_obj = await session.get(JobModel, after)+ if not after_obj:+ raise ValueError(f"Job with id {after} not found")++ # validate cursors+ if before_obj and after_obj:+ if before_obj.created_at < after_obj.created_at:+ raise ValueError("'before' reference must be later than 'after' reference")+ elif before_obj.created_at == after_obj.created_at and before_obj.id < after_obj.id:+ raise ValueError("'before' reference must be later than 'after' reference")++ # build cursor conditions+ conditions = []+ if before_obj:+ # records before this cursor (older)++ before_timestamp = before_obj.created_at+ # SQLite does not support as granular timestamping, so we need to round the timestamp+ if settings.database_engine is DatabaseChoice.SQLITE and isinstance(before_timestamp, datetime):+ before_timestamp = before_timestamp.strftime("%Y-%m-%d %H:%M:%S")++ conditions.append(+ or_(+ JobModel.created_at < before_timestamp,+ and_(JobModel.created_at == before_timestamp, JobModel.id < before_obj.id),+ )+ )++ if after_obj:+ # records after this cursor (newer)+ after_timestamp = after_obj.created_at+ # SQLite does not support as granular timestamping, so we need to round the timestamp+ if settings.database_engine is DatabaseChoice.SQLITE and isinstance(after_timestamp, datetime):+ after_timestamp = after_timestamp.strftime("%Y-%m-%d %H:%M:%S")++ conditions.append(+ or_(JobModel.created_at > after_timestamp, and_(JobModel.created_at == after_timestamp, JobModel.id > after_obj.id))+ )++ if conditions:+ query = query.where(and_(*conditions))++ # apply ordering+ if ascending:+ query = query.order_by(JobModel.created_at.asc(), JobModel.id.asc())+ else:+ query = query.order_by(JobModel.created_at.desc(), JobModel.id.desc())++ # apply limit+ if limit:+ query = query.limit(limit)++ # execute query+ result = await session.execute(query)+ jobs = result.scalars().all()- jobs = await JobModel.list_async(- db_session=session,- before=before,- after=after,- limit=limit,- ascending=ascending,- **filter_kwargs,- )return [job.to_pydantic() for job in jobs]@enforce_types@@ -617,7 +739,7 @@ class JobManager:session: Session,job_id: str,actor: PydanticUser,- access: List[Literal["read", "write", "delete"]] = ["read"],+ access: List[Literal["read", "write", "admin"]] = ["read"],) -> JobModel:"""Verify that a job exists and the user has the required access.@@ -685,61 +807,58 @@ class JobManager:return request_config@trace_method- def _dispatch_callback(self, job: JobModel) -> None:+ def _dispatch_callback_sync(self, callback_info: dict) -> dict:"""- POST a standard JSON payload to job.callback_url- and record timestamp + HTTP status.+ POST a standard JSON payload to callback_url and return callback status."""-payload = {- "job_id": job.id,- "status": job.status,- "completed_at": job.completed_at.isoformat() if job.completed_at else None,- "metadata": job.metadata_,+ "job_id": callback_info["job_id"],+ "status": callback_info["status"],+ "completed_at": callback_info["completed_at"].isoformat() if callback_info["completed_at"] else None,+ "metadata": callback_info["metadata"],}++ callback_sent_at = get_utc_time().replace(tzinfo=None)+ result = {"callback_sent_at": callback_sent_at}+try:log_event("POST callback dispatched", payload)- resp = post(job.callback_url, json=payload, timeout=5.0)+ resp = post(callback_info["callback_url"], json=payload, timeout=5.0)log_event("POST callback finished")- job.callback_sent_at = get_utc_time().replace(tzinfo=None)- job.callback_status_code = resp.status_code-+ result["callback_status_code"] = resp.status_codeexcept Exception as e:- error_message = f"Failed to dispatch callback for job {job.id} to {job.callback_url}: {e!s}"+ error_message = f"Failed to dispatch callback for job {callback_info['job_id']} to {callback_info['callback_url']}: {e!s}"logger.error(error_message)- # Record the failed attempt- job.callback_sent_at = get_utc_time().replace(tzinfo=None)- job.callback_error = error_message+ result["callback_error"] = error_message# Continue silently - callback failures should not affect job completion+ return result+@trace_method- async def _dispatch_callback_async(self, callback_url: str, payload: dict, actor: PydanticUser) -> PydanticJob:+ async def _dispatch_callback_async(self, callback_info: dict) -> dict:"""- POST a standard JSON payload to job.callback_url and record timestamp + HTTP status asynchronously.+ POST a standard JSON payload to callback_url and return callback status asynchronously."""- job_id = payload["job_id"]- callback_sent_at, callback_status_code, callback_error = None, None, None+ payload = {+ "job_id": callback_info["job_id"],+ "status": callback_info["status"],+ "completed_at": callback_info["completed_at"].isoformat() if callback_info["completed_at"] else None,+ "metadata": callback_info["metadata"],+ }++ callback_sent_at = get_utc_time().replace(tzinfo=None)+ result = {"callback_sent_at": callback_sent_at}try:async with AsyncClient() as client:log_event("POST callback dispatched", payload)- resp = await client.post(callback_url, json=payload, timeout=5.0)+ resp = await client.post(callback_info["callback_url"], json=payload, timeout=5.0)log_event("POST callback finished")- # Ensure timestamp is timezone-naive for DB compatibility- callback_sent_at = get_utc_time().replace(tzinfo=None)- callback_status_code = resp.status_code+ result["callback_status_code"] = resp.status_codeexcept Exception as e:- error_message = f"Failed to dispatch callback for job {job_id} to {callback_url}: {e!s}"+ error_message = f"Failed to dispatch callback for job {callback_info['job_id']} to {callback_info['callback_url']}: {e!s}"logger.error(error_message)- # Record the failed attempt- callback_sent_at = get_utc_time().replace(tzinfo=None)- callback_error = error_message+ result["callback_error"] = error_message# Continue silently - callback failures should not affect job completion- async with db_registry.async_session() as session:- job = await JobModel.read_async(db_session=session, identifier=job_id, actor=actor, access_type=AccessType.USER)- job.callback_sent_at = callback_sent_at- job.callback_status_code = callback_status_code- job.callback_error = callback_error- await job.update_async(db_session=session, actor=actor)- return job.to_pydantic()+ return resultdiff --git a/letta/services/llm_batch_manager.py b/letta/services/llm_batch_manager.pyindex b2241e446..bce52aeba 100644--- a/letta/services/llm_batch_manager.py+++ b/letta/services/llm_batch_manager.py@@ -45,8 +45,10 @@ class LLMBatchManager:organization_id=actor.organization_id,letta_batch_job_id=letta_batch_job_id,)- await batch.create_async(session, actor=actor)- return batch.to_pydantic()+ await batch.create_async(session, actor=actor, no_commit=True, no_refresh=True)+ pydantic_batch = batch.to_pydantic()+ await session.commit()+ return pydantic_batch@enforce_types@trace_method@@ -282,10 +284,11 @@ class LLMBatchManager:)orm_items.append(orm_item)- created_items = await LLMBatchItem.batch_create_async(orm_items, session, actor=actor)+ created_items = await LLMBatchItem.batch_create_async(orm_items, session, actor=actor, no_commit=True, no_refresh=True)- # Convert back to Pydantic models- return [item.to_pydantic() for item in created_items]+ pydantic_items = [item.to_pydantic() for item in created_items]+ await session.commit()+ return pydantic_items@enforce_types@trace_method@@ -403,7 +406,7 @@ class LLMBatchManager:missing = requested - foundif missing:raise ValueError(- f"Cannot bulk-update batch items: no records for the following " f"(llm_batch_id, agent_id) pairs: {missing}"+ f"Cannot bulk-update batch items: no records for the following (llm_batch_id, agent_id) pairs: {missing}")# Build mappings, skipping any missing when strict=Falsediff --git a/letta/services/mcp/stdio_client.py b/letta/services/mcp/stdio_client.pyindex 166ee06c1..f7b2c716a 100644--- a/letta/services/mcp/stdio_client.py+++ b/letta/services/mcp/stdio_client.py@@ -11,11 +11,10 @@ logger = get_logger(__name__)# TODO: Get rid of Async prefix on this class name once we deprecate old sync codeclass AsyncStdioMCPClient(AsyncBaseMCPClient):async def _initialize_connection(self, server_config: StdioServerConfig) -> None:-args = [arg.split() for arg in server_config.args]# flattenargs = [arg for sublist in args for arg in sublist]- server_params = StdioServerParameters(command=server_config.command, args=args)+ server_params = StdioServerParameters(command=server_config.command, args=args, env=server_config.env)stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))self.stdio, self.write = stdio_transportself.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))diff --git a/letta/services/mcp_manager.py b/letta/services/mcp_manager.pyindex 63a825bd0..b542e22bf 100644--- a/letta/services/mcp_manager.py+++ b/letta/services/mcp_manager.py@@ -274,7 +274,6 @@ class MCPManager:mcp_config_path = os.path.join(constants.LETTA_DIR, constants.MCP_CONFIG_NAME)if os.path.exists(mcp_config_path):with open(mcp_config_path, "r") as f:-try:mcp_config = json.load(f)except Exception as e:diff --git a/letta/services/message_manager.py b/letta/services/message_manager.pyindex 5e1620cf3..408abba71 100644--- a/letta/services/message_manager.py+++ b/letta/services/message_manager.py@@ -17,6 +17,8 @@ from letta.schemas.message import MessageUpdatefrom letta.schemas.user import User as PydanticUserfrom letta.server.db import db_registryfrom letta.services.file_manager import FileManager+from letta.services.helpers.agent_manager_helper import validate_agent_exists_async+from letta.settings import DatabaseChoice, settingsfrom letta.utils import enforce_typeslogger = get_logger(__name__)@@ -86,8 +88,8 @@ class MessageManager:"""Create a new message."""with db_registry.session() as session:# Set the organization id of the Pydantic message- pydantic_msg.organization_id = actor.organization_idmsg_data = pydantic_msg.model_dump(to_orm=True)+ msg_data["organization_id"] = actor.organization_idmsg = MessageModel(**msg_data)msg.create(session, actor=actor) # Persist to databasereturn msg.to_pydantic()@@ -97,8 +99,8 @@ class MessageManager:orm_messages = []for pydantic_msg in pydantic_msgs:# Set the organization id of the Pydantic message- pydantic_msg.organization_id = actor.organization_idmsg_data = pydantic_msg.model_dump(to_orm=True)+ msg_data["organization_id"] = actor.organization_idorm_messages.append(MessageModel(**msg_data))return orm_messages@@ -165,8 +167,10 @@ class MessageManager:)orm_messages = self._create_many_preprocess(pydantic_msgs, actor)async with db_registry.async_session() as session:- created_messages = await MessageModel.batch_create_async(orm_messages, session, actor=actor)- return [msg.to_pydantic() for msg in created_messages]+ created_messages = await MessageModel.batch_create_async(orm_messages, session, actor=actor, no_commit=True, no_refresh=True)+ result = [msg.to_pydantic() for msg in created_messages]+ await session.commit()+ return result@enforce_types@trace_method@@ -280,8 +284,10 @@ class MessageManager:)message = self._update_message_by_id_impl(message_id, message_update, actor, message)- await message.update_async(db_session=session, actor=actor)- return message.to_pydantic()+ await message.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)+ pydantic_message = message.to_pydantic()+ await session.commit()+ return pydantic_messagedef _update_message_by_id_impl(self, message_id: str, message_update: MessageUpdate, actor: PydanticUser, message: MessageModel@@ -453,17 +459,23 @@ class MessageManager:if group_id:query = query.filter(MessageModel.group_id == group_id)- # If query_text is provided, filter messages using subquery + json_array_elements.+ # If query_text is provided, filter messages using database-specific JSON search.if query_text:- content_element = func.json_array_elements(MessageModel.content).alias("content_element")- query = query.filter(- exists(- select(1)- .select_from(content_element)- .where(text("content_element->>'type' = 'text' AND content_element->>'text' ILIKE :query_text"))- .params(query_text=f"%{query_text}%")+ if settings.database_engine is DatabaseChoice.POSTGRES:+ # PostgreSQL: Use json_array_elements and ILIKE+ content_element = func.json_array_elements(MessageModel.content).alias("content_element")+ query = query.filter(+ exists(+ select(1)+ .select_from(content_element)+ .where(text("content_element->>'type' = 'text' AND content_element->>'text' ILIKE :query_text"))+ .params(query_text=f"%{query_text}%")+ ))- )+ else:+ # SQLite: Use JSON_EXTRACT with individual array indices for case-insensitive search+ # Since SQLite doesn't support $[*] syntax, we'll use a different approach+ query = query.filter(text("JSON_EXTRACT(content, '$') LIKE :query_text")).params(query_text=f"%{query_text}%")# If role(s) are provided, filter messages by those roles.if roles:@@ -512,6 +524,7 @@ class MessageManager:limit: Optional[int] = 50,ascending: bool = True,group_id: Optional[str] = None,+ include_err: Optional[bool] = None,) -> List[PydanticMessage]:"""Most performant query to list messages for an agent by directly querying the Message table.@@ -531,6 +544,7 @@ class MessageManager:limit: Maximum number of messages to return.ascending: If True, sort by sequence_id ascending; if False, sort descending.group_id: Optional group ID to filter messages by group_id.+ include_err: Optional boolean to include errors and error statuses. Used for debugging only.Returns:List[PydanticMessage]: A list of messages (converted via .to_pydantic()).@@ -541,7 +555,7 @@ class MessageManager:async with db_registry.async_session() as session:# Permission check: raise if the agent doesn't exist or actor is not allowed.- await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)+ await validate_agent_exists_async(session, agent_id, actor)# Build a query that directly filters the Message table by agent_id.query = select(MessageModel).where(MessageModel.agent_id == agent_id)@@ -550,17 +564,26 @@ class MessageManager:if group_id:query = query.where(MessageModel.group_id == group_id)- # If query_text is provided, filter messages using subquery + json_array_elements.+ if not include_err:+ query = query.where((MessageModel.is_err == False) | (MessageModel.is_err.is_(None)))++ # If query_text is provided, filter messages using database-specific JSON search.if query_text:- content_element = func.json_array_elements(MessageModel.content).alias("content_element")- query = query.where(- exists(- select(1)- .select_from(content_element)- .where(text("content_element->>'type' = 'text' AND content_element->>'text' ILIKE :query_text"))- .params(query_text=f"%{query_text}%")+ if settings.database_engine is DatabaseChoice.POSTGRES:+ # PostgreSQL: Use json_array_elements and ILIKE+ content_element = func.json_array_elements(MessageModel.content).alias("content_element")+ query = query.where(+ exists(+ select(1)+ .select_from(content_element)+ .where(text("content_element->>'type' = 'text' AND content_element->>'text' ILIKE :query_text"))+ .params(query_text=f"%{query_text}%")+ ))- )+ else:+ # SQLite: Use JSON_EXTRACT with individual array indices for case-insensitive search+ # Since SQLite doesn't support $[*] syntax, we'll use a different approach+ query = query.where(text("JSON_EXTRACT(content, '$') LIKE :query_text")).params(query_text=f"%{query_text}%")# If role(s) are provided, filter messages by those roles.if roles:@@ -611,7 +634,7 @@ class MessageManager:"""async with db_registry.async_session() as session:# 1) verify the agent exists and the actor has access- await AgentModel.read_async(db_session=session, identifier=agent_id, actor=actor)+ await validate_agent_exists_async(session, agent_id, actor)# 2) issue a CORE DELETE against the mapped classstmt = (diff --git a/letta/services/passage_manager.py b/letta/services/passage_manager.pyindex 8206f0480..675807767 100644--- a/letta/services/passage_manager.py+++ b/letta/services/passage_manager.py@@ -476,7 +476,6 @@ class PassageManager:try:# breakup string into passagesfor text in parse_and_chunk_text(text, embedding_chunk_size):-if agent_state.embedding_config.embedding_endpoint_type != "openai":embedding = embed_model.get_text_embedding(text)else:diff --git a/letta/services/provider_manager.py b/letta/services/provider_manager.pyindex e919b93f8..610ffb2e8 100644--- a/letta/services/provider_manager.py+++ b/letta/services/provider_manager.py@@ -213,7 +213,7 @@ class ProviderManager:provider_type=provider_check.provider_type,api_key=provider_check.api_key,provider_category=ProviderCategory.byok,- secret_key=provider_check.api_secret,+ access_id_key=provider_check.access_id_key, # This contains the access key ID for Bedrockregion=provider_check.region,).cast_to_subtype()diff --git a/letta/services/source_manager.py b/letta/services/source_manager.pyindex b3cd2c04b..e3287130c 100644--- a/letta/services/source_manager.py+++ b/letta/services/source_manager.py@@ -1,7 +1,7 @@import asynciofrom typing import List, Optional-from sqlalchemy import select+from sqlalchemy import and_, exists, selectfrom letta.orm import Agent as AgentModelfrom letta.orm.errors import NoResultFound@@ -19,6 +19,30 @@ from letta.utils import enforce_types, printdclass SourceManager:"""Manager class to handle business logic related to Sources."""+ @trace_method+ async def _validate_source_exists_async(self, session, source_id: str, actor: PydanticUser) -> None:+ """+ Validate that a source exists and user has access to it using raw SQL for efficiency.++ Args:+ session: Database session+ source_id: ID of the source to validate+ actor: User performing the action++ Raises:+ NoResultFound: If source doesn't exist or user doesn't have access+ """+ source_exists_query = select(+ exists().where(+ and_(SourceModel.id == source_id, SourceModel.organization_id == actor.organization_id, SourceModel.is_deleted == False)+ )+ )++ result = await session.execute(source_exists_query)++ if not result.scalar():+ raise NoResultFound(f"Source with ID {source_id} not found")+@enforce_types@trace_methodasync def create_source(self, source: PydanticSource, actor: PydanticUser) -> PydanticSource:@@ -93,20 +117,20 @@ class SourceManager:@enforce_types@trace_method- async def list_attached_agents(self, source_id: str, actor: Optional[PydanticUser] = None) -> List[PydanticAgentState]:+ async def list_attached_agents(self, source_id: str, actor: PydanticUser) -> List[PydanticAgentState]:"""Lists all agents that have the specified source attached.Args:source_id: ID of the source to find attached agents for- actor: User performing the action (optional for now, following existing pattern)+ actor: User performing the actionReturns:List[PydanticAgentState]: List of agents that have this source attached"""async with db_registry.async_session() as session:# Verify source exists and user has permission to access it- source = await SourceModel.read_async(db_session=session, identifier=source_id, actor=actor)+ await self._validate_source_exists_async(session, source_id, actor)# Use junction table query instead of relationship to avoid performance issuesquery = (@@ -114,7 +138,7 @@ class SourceManager:.join(SourcesAgents, AgentModel.id == SourcesAgents.agent_id).where(SourcesAgents.source_id == source_id,- AgentModel.organization_id == actor.organization_id if actor else True,+ AgentModel.organization_id == actor.organization_id,AgentModel.is_deleted == False,).order_by(AgentModel.created_at.desc(), AgentModel.id)@@ -125,6 +149,31 @@ class SourceManager:return await asyncio.gather(*[agent.to_pydantic_async() for agent in agents_orm])+ @enforce_types+ @trace_method+ async def get_agents_for_source_id(self, source_id: str, actor: PydanticUser) -> List[str]:+ """+ Get all agent IDs associated with a given source ID.++ Args:+ source_id: ID of the source to find agents for+ actor: User performing the action++ Returns:+ List[str]: List of agent IDs that have this source attached+ """+ async with db_registry.async_session() as session:+ # Verify source exists and user has permission to access it+ await self._validate_source_exists_async(session, source_id, actor)++ # Query the junction table directly for performance+ query = select(SourcesAgents.agent_id).where(SourcesAgents.source_id == source_id)++ result = await session.execute(query)+ agent_ids = result.scalars().all()++ return list(agent_ids)+# TODO: We make actor optional for now, but should most likely be enforced due to security reasons@enforce_types@trace_method@@ -152,3 +201,63 @@ class SourceManager:return Noneelse:return sources[0].to_pydantic()++ @enforce_types+ @trace_method+ async def get_sources_by_ids_async(self, source_ids: List[str], actor: PydanticUser) -> List[PydanticSource]:+ """+ Get multiple sources by their IDs in a single query.++ Args:+ source_ids: List of source IDs to retrieve+ actor: User performing the action++ Returns:+ List[PydanticSource]: List of sources (may be fewer than requested if some don't exist)+ """+ if not source_ids:+ return []++ async with db_registry.async_session() as session:+ query = select(SourceModel).where(+ SourceModel.id.in_(source_ids), SourceModel.organization_id == actor.organization_id, SourceModel.is_deleted == False+ )++ result = await session.execute(query)+ sources_orm = result.scalars().all()++ return [source.to_pydantic() for source in sources_orm]++ @enforce_types+ @trace_method+ async def get_sources_for_agents_async(self, agent_ids: List[str], actor: PydanticUser) -> List[PydanticSource]:+ """+ Get all sources associated with the given agents via sources-agents relationships.++ Args:+ agent_ids: List of agent IDs to find sources for+ actor: User performing the action++ Returns:+ List[PydanticSource]: List of unique sources associated with these agents+ """+ if not agent_ids:+ return []++ async with db_registry.async_session() as session:+ # Join through sources-agents junction table+ query = (+ select(SourceModel)+ .join(SourcesAgents, SourceModel.id == SourcesAgents.source_id)+ .where(+ SourcesAgents.agent_id.in_(agent_ids),+ SourceModel.organization_id == actor.organization_id,+ SourceModel.is_deleted == False,+ )+ .distinct() # Ensure we don't get duplicate sources+ )++ result = await session.execute(query)+ sources_orm = result.scalars().all()++ return [source.to_pydantic() for source in sources_orm]diff --git a/letta/services/step_manager.py b/letta/services/step_manager.pyindex b95de67dd..32be82759 100644--- a/letta/services/step_manager.py+++ b/letta/services/step_manager.py@@ -12,6 +12,7 @@ from letta.orm.job import Job as JobModelfrom letta.orm.sqlalchemy_base import AccessTypefrom letta.orm.step import Step as StepModelfrom letta.otel.tracing import get_trace_id, trace_method+from letta.schemas.letta_stop_reason import LettaStopReason, StopReasonTypefrom letta.schemas.openai.chat_completion_response import UsageStatisticsfrom letta.schemas.step import Step as PydanticStepfrom letta.schemas.user import User as PydanticUser@@ -131,6 +132,7 @@ class StepManager:job_id: Optional[str] = None,step_id: Optional[str] = None,project_id: Optional[str] = None,+ stop_reason: Optional[LettaStopReason] = None,) -> PydanticStep:step_data = {"origin": None,@@ -153,12 +155,14 @@ class StepManager:}if step_id:step_data["id"] = step_id+ if stop_reason:+ step_data["stop_reason"] = stop_reason.stop_reasonasync with db_registry.async_session() as session:- if job_id:- await self._verify_job_access_async(session, job_id, actor, access=["write"])new_step = StepModel(**step_data)- await new_step.create_async(session)- return new_step.to_pydantic()+ await new_step.create_async(session, no_commit=True, no_refresh=True)+ pydantic_step = new_step.to_pydantic()+ await session.commit()+ return pydantic_step@enforce_types@trace_method@@ -205,6 +209,33 @@ class StepManager:await session.commit()return step.to_pydantic()+ @enforce_types+ @trace_method+ async def update_step_stop_reason(self, actor: PydanticUser, step_id: str, stop_reason: StopReasonType) -> PydanticStep:+ """Update the stop reason for a step.++ Args:+ actor: The user making the request+ step_id: The ID of the step to update+ stop_reason: The stop reason to set++ Returns:+ The updated step++ Raises:+ NoResultFound: If the step does not exist+ """+ async with db_registry.async_session() as session:+ step = await session.get(StepModel, step_id)+ if not step:+ raise NoResultFound(f"Step with id {step_id} does not exist")+ if step.organization_id != actor.organization_id:+ raise Exception("Unauthorized")++ step.stop_reason = stop_reason+ await session.commit()+ return step+def _verify_job_access(self,session: Session,@@ -307,5 +338,6 @@ class NoopStepManager(StepManager):job_id: Optional[str] = None,step_id: Optional[str] = None,project_id: Optional[str] = None,+ stop_reason: Optional[LettaStopReason] = None,) -> PydanticStep:returndiff --git a/letta/services/telemetry_manager.py b/letta/services/telemetry_manager.pyindex 213bdb09b..bf8efd80e 100644--- a/letta/services/telemetry_manager.py+++ b/letta/services/telemetry_manager.py@@ -1,6 +1,7 @@from letta.helpers.json_helpers import json_dumps, json_loadsfrom letta.helpers.singleton import singletonfrom letta.orm.provider_trace import ProviderTrace as ProviderTraceModel+from letta.otel.tracing import trace_methodfrom letta.schemas.provider_trace import ProviderTrace as PydanticProviderTracefrom letta.schemas.provider_trace import ProviderTraceCreatefrom letta.schemas.step import Step as PydanticStep@@ -10,7 +11,9 @@ from letta.utils import enforce_typesclass TelemetryManager:+@enforce_types+ @trace_methodasync def get_provider_trace_by_step_id_async(self,step_id: str,@@ -21,6 +24,7 @@ class TelemetryManager:return provider_trace.to_pydantic()@enforce_types+ @trace_methodasync def create_provider_trace_async(self, actor: PydanticUser, provider_trace_create: ProviderTraceCreate) -> PydanticProviderTrace:async with db_registry.async_session() as session:provider_trace = ProviderTraceModel(**provider_trace_create.model_dump())@@ -31,10 +35,13 @@ class TelemetryManager:if provider_trace_create.response_json:response_json_str = json_dumps(provider_trace_create.response_json)provider_trace.response_json = json_loads(response_json_str)- await provider_trace.create_async(session, actor=actor)- return provider_trace.to_pydantic()+ await provider_trace.create_async(session, actor=actor, no_commit=True, no_refresh=True)+ pydantic_provider_trace = provider_trace.to_pydantic()+ await session.commit()+ return pydantic_provider_trace@enforce_types+ @trace_methoddef create_provider_trace(self, actor: PydanticUser, provider_trace_create: ProviderTraceCreate) -> PydanticProviderTrace:with db_registry.session() as session:provider_trace = ProviderTraceModel(**provider_trace_create.model_dump())diff --git a/letta/services/tool_executor/builtin_tool_executor.py b/letta/services/tool_executor/builtin_tool_executor.pyindex 22c0a38dd..d8cd24a6b 100644--- a/letta/services/tool_executor/builtin_tool_executor.py+++ b/letta/services/tool_executor/builtin_tool_executor.py@@ -1,10 +1,12 @@import asyncioimport json+import osimport timefrom typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel+from letta.constants import WEB_SEARCH_MODEL_ENV_VAR_DEFAULT_VALUE, WEB_SEARCH_MODEL_ENV_VAR_NAMEfrom letta.functions.prompts import FIRECRAWL_SEARCH_SYSTEM_PROMPT, get_firecrawl_search_user_promptfrom letta.functions.types import SearchTaskfrom letta.log import get_logger@@ -322,8 +324,10 @@ class LettaBuiltinToolExecutor(ToolExecutor):# Time the OpenAI requeststart_time = time.time()+ model = os.getenv(WEB_SEARCH_MODEL_ENV_VAR_NAME, WEB_SEARCH_MODEL_ENV_VAR_DEFAULT_VALUE)+ logger.info(f"Using model {model} for web search result parsing")response = await client.beta.chat.completions.parse(- model="gpt-4.1-mini-2025-04-14",+ model=model,messages=[{"role": "system", "content": FIRECRAWL_SEARCH_SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}],response_format=DocumentAnalysis,temperature=0.1,diff --git a/letta/services/tool_executor/core_tool_executor.py b/letta/services/tool_executor/core_tool_executor.pyindex 8883890f1..bff2545d8 100644--- a/letta/services/tool_executor/core_tool_executor.py+++ b/letta/services/tool_executor/core_tool_executor.py@@ -96,7 +96,7 @@ class LettaCoreToolExecutor(ToolExecutor):try:page = int(page)except:- raise ValueError(f"'page' argument must be an integer")+ raise ValueError("'page' argument must be an integer")count = RETRIEVAL_QUERY_DEFAULT_PAGE_SIZEmessages = await MessageManager().list_user_messages_for_agent_async(@@ -110,7 +110,7 @@ class LettaCoreToolExecutor(ToolExecutor):num_pages = math.ceil(total / count) - 1 # 0 indexif len(messages) == 0:- results_str = f"No results found."+ results_str = "No results found."else:results_pref = f"Showing {len(messages)} of {total} results (page {page}/{num_pages}):"results_formatted = [message.content[0].text for message in messages]@@ -137,7 +137,7 @@ class LettaCoreToolExecutor(ToolExecutor):try:page = int(page)except:- raise ValueError(f"'page' argument must be an integer")+ raise ValueError("'page' argument must be an integer")count = RETRIEVAL_QUERY_DEFAULT_PAGE_SIZEdiff --git a/letta/services/tool_manager.py b/letta/services/tool_manager.pyindex 6bd231724..132540496 100644--- a/letta/services/tool_manager.py+++ b/letta/services/tool_manager.py@@ -1,5 +1,5 @@-import asyncioimport importlib+import osimport warningsfrom typing import List, Optional, Set, Union@@ -14,6 +14,7 @@ from letta.constants import (FILES_TOOLS,LETTA_TOOL_MODULE_NAMES,LETTA_TOOL_SET,+ LOCAL_ONLY_MULTI_AGENT_TOOLS,MCP_TOOL_TAG_NAME_PREFIX,)from letta.functions.functions import derive_openai_json_schema, load_function_set@@ -30,6 +31,7 @@ from letta.schemas.user import User as PydanticUserfrom letta.server.db import db_registryfrom letta.services.helpers.agent_manager_helper import calculate_multi_agent_toolsfrom letta.services.mcp.types import SSEServerConfig, StdioServerConfig+from letta.settings import settingsfrom letta.utils import enforce_types, printdlogger = get_logger(__name__)@@ -74,6 +76,7 @@ class ToolManager:if tool_id:# Put to dict and remove fields that should not be resetupdate_data = pydantic_tool.model_dump(exclude_unset=True, exclude_none=True)+ update_data["organization_id"] = actor.organization_id# If there's anything to updateif update_data:@@ -146,12 +149,12 @@ class ToolManager:def create_tool(self, pydantic_tool: PydanticTool, actor: PydanticUser) -> PydanticTool:"""Create a new tool based on the ToolCreate schema."""with db_registry.session() as session:- # Set the organization id at the ORM layer- pydantic_tool.organization_id = actor.organization_id# Auto-generate description if not providedif pydantic_tool.description is None:pydantic_tool.description = pydantic_tool.json_schema.get("description", None)tool_data = pydantic_tool.model_dump(to_orm=True)+ # Set the organization id at the ORM layer+ tool_data["organization_id"] = actor.organization_idtool = ToolModel(**tool_data)tool.create(session, actor=actor) # Re-raise other database-related errors@@ -162,12 +165,12 @@ class ToolManager:async def create_tool_async(self, pydantic_tool: PydanticTool, actor: PydanticUser) -> PydanticTool:"""Create a new tool based on the ToolCreate schema."""async with db_registry.async_session() as session:- # Set the organization id at the ORM layer- pydantic_tool.organization_id = actor.organization_id# Auto-generate description if not providedif pydantic_tool.description is None:pydantic_tool.description = pydantic_tool.json_schema.get("description", None)tool_data = pydantic_tool.model_dump(to_orm=True)+ # Set the organization id at the ORM layer+ tool_data["organization_id"] = actor.organization_idtool = ToolModel(**tool_data)await tool.create_async(session, actor=actor) # Re-raise other database-related errors@@ -250,7 +253,10 @@ class ToolManager:# TODO: This requires a deeper rethink about how we keep all our internal tools up-to-dateif not after and upsert_base_tools:existing_tool_names = {tool.name for tool in tools}- missing_base_tools = LETTA_TOOL_SET - existing_tool_names+ base_tool_names = (+ LETTA_TOOL_SET - set(LOCAL_ONLY_MULTI_AGENT_TOOLS) if os.getenv("LETTA_ENVIRONMENT") == "PRODUCTION" else LETTA_TOOL_SET+ )+ missing_base_tools = base_tool_names - existing_tool_names# If any base tools are missing, upsert all base toolsif missing_base_tools:@@ -462,7 +468,10 @@ class ToolManager:actor: PydanticUser,allowed_types: Optional[Set[ToolType]] = None,) -> List[PydanticTool]:- """Add default tools defined in the various function_sets modules, optionally filtered by ToolType."""+ """Add default tools defined in the various function_sets modules, optionally filtered by ToolType.++ Optimized bulk implementation using single database session and batch operations.+ """functions_to_schema = {}for module_name in LETTA_TOOL_MODULE_NAMES:@@ -474,7 +483,8 @@ class ToolManager:except Exception as e:raise e- tools = []+ # prepare tool data for bulk operations+ tool_data_list = []for name, schema in functions_to_schema.items():if name not in LETTA_TOOL_SET:continue@@ -500,17 +510,82 @@ class ToolManager:if allowed_types is not None and tool_type not in allowed_types:continue- tools.append(- self.create_or_update_tool_async(- PydanticTool(- name=name,- tags=[tool_type.value],- source_type="python",- tool_type=tool_type,- return_char_limit=BASE_FUNCTION_RETURN_CHAR_LIMIT,- ),- actor=actor,- )+ # create pydantic tool for validation and conversion+ pydantic_tool = PydanticTool(+ name=name,+ tags=[tool_type.value],+ source_type="python",+ tool_type=tool_type,+ return_char_limit=BASE_FUNCTION_RETURN_CHAR_LIMIT,)- return await asyncio.gather(*tools)+ # auto-generate description if not provided+ if pydantic_tool.description is None:+ pydantic_tool.description = pydantic_tool.json_schema.get("description", None)++ tool_data_list.append(pydantic_tool)++ if not tool_data_list:+ return []++ if settings.letta_pg_uri_no_default:+ async with db_registry.async_session() as session:+ return await self._bulk_upsert_postgresql(session, tool_data_list, actor)+ else:+ return await self._upsert_tools_individually(tool_data_list, actor)++ @trace_method+ async def _bulk_upsert_postgresql(self, session, tool_data_list: List[PydanticTool], actor: PydanticUser) -> List[PydanticTool]:+ """hyper-optimized postgresql bulk upsert using on_conflict_do_update."""+ from sqlalchemy import func, select+ from sqlalchemy.dialects.postgresql import insert++ # prepare data for bulk insert+ table = ToolModel.__table__+ valid_columns = {col.name for col in table.columns}++ insert_data = []+ for tool in tool_data_list:+ tool_dict = tool.model_dump(to_orm=True)+ # set created/updated by fields+ if actor:+ tool_dict["_created_by_id"] = actor.id+ tool_dict["_last_updated_by_id"] = actor.id+ tool_dict["organization_id"] = actor.organization_id++ # filter to only include columns that exist in the table+ filtered_dict = {k: v for k, v in tool_dict.items() if k in valid_columns}+ insert_data.append(filtered_dict)++ # use postgresql's native bulk upsert+ stmt = insert(table).values(insert_data)++ # on conflict, update all columns except id, created_at, and _created_by_id+ excluded = stmt.excluded+ update_dict = {}+ for col in table.columns:+ if col.name not in ("id", "created_at", "_created_by_id"):+ if col.name == "updated_at":+ update_dict[col.name] = func.now()+ else:+ update_dict[col.name] = excluded[col.name]++ upsert_stmt = stmt.on_conflict_do_update(index_elements=["name", "organization_id"], set_=update_dict)++ await session.execute(upsert_stmt)+ await session.commit()++ # fetch results+ tool_names = [tool.name for tool in tool_data_list]+ result_query = select(ToolModel).where(ToolModel.name.in_(tool_names), ToolModel.organization_id == actor.organization_id)+ result = await session.execute(result_query)+ return [tool.to_pydantic() for tool in result.scalars()]++ @trace_method+ async def _upsert_tools_individually(self, tool_data_list: List[PydanticTool], actor: PydanticUser) -> List[PydanticTool]:+ """fallback to individual upserts for sqlite (original approach)."""+ tools = []+ for tool in tool_data_list:+ upserted_tool = await self.create_or_update_tool_async(tool, actor)+ tools.append(upserted_tool)+ return toolsdiff --git a/letta/services/user_manager.py b/letta/services/user_manager.pyindex 0f05e41f2..ea3919537 100644--- a/letta/services/user_manager.py+++ b/letta/services/user_manager.py@@ -1,6 +1,6 @@from typing import List, Optional-from sqlalchemy import select, text+from sqlalchemy import selectfrom letta.constants import DEFAULT_ORG_IDfrom letta.data_sources.redis_client import get_redis_client@@ -8,7 +8,6 @@ from letta.helpers.decorators import async_redis_cachefrom letta.log import get_loggerfrom letta.orm.errors import NoResultFoundfrom letta.orm.organization import Organization as OrganizationModel-from letta.orm.sqlalchemy_base import is_postgresql_sessionfrom letta.orm.user import User as UserModelfrom letta.otel.tracing import trace_methodfrom letta.schemas.user import User as PydanticUser@@ -157,16 +156,9 @@ class UserManager:async def get_actor_by_id_async(self, actor_id: str) -> PydanticUser:"""Fetch a user by ID asynchronously."""async with db_registry.async_session() as session:- # Turn off seqscan to force use pk index- if is_postgresql_session(session):- await session.execute(text("SET LOCAL enable_seqscan = OFF"))- try:- stmt = select(UserModel).where(UserModel.id == actor_id)- result = await session.execute(stmt)- user = result.scalar_one_or_none()- finally:- if is_postgresql_session(session):- await session.execute(text("SET LOCAL enable_seqscan = ON"))+ stmt = select(UserModel).where(UserModel.id == actor_id)+ result = await session.execute(stmt)+ user = result.scalar_one_or_none()if not user:raise NoResultFound(f"User not found with id={actor_id}")diff --git a/letta/settings.py b/letta/settings.pyindex 7a86605ef..e438faa21 100644--- a/letta/settings.py+++ b/letta/settings.py@@ -1,4 +1,5 @@import os+from enum import Enumfrom pathlib import Pathfrom typing import Optional@@ -182,6 +183,11 @@ if "--use-file-pg-uri" in sys.argv:pass+class DatabaseChoice(str, Enum):+ POSTGRES = "postgres"+ SQLITE = "sqlite"++class Settings(BaseSettings):model_config = SettingsConfigDict(env_prefix="letta_", extra="ignore")@@ -220,21 +226,24 @@ class Settings(BaseSettings):multi_agent_concurrent_sends: int = 50# telemetry logging- otel_exporter_otlp_endpoint: Optional[str] = None # otel default: "http://localhost:4317"- otel_preferred_temporality: Optional[int] = Field(+ otel_exporter_otlp_endpoint: str | None = None # otel default: "http://localhost:4317"+ otel_preferred_temporality: int | None = Field(default=1, ge=0, le=2, description="Exported metric temporality. {0: UNSPECIFIED, 1: DELTA, 2: CUMULATIVE}")disable_tracing: bool = Field(default=False, description="Disable OTEL Tracing")llm_api_logging: bool = Field(default=True, description="Enable LLM API logging at each step")track_last_agent_run: bool = Field(default=False, description="Update last agent run metrics")+ track_errored_messages: bool = Field(default=True, description="Enable tracking for errored messages")+ track_stop_reason: bool = Field(default=True, description="Enable tracking stop reason on steps.")+ track_agent_run: bool = Field(default=True, description="Enable tracking agent run with cancellation support")- # uvicorn settings+ # FastAPI Application Settingsuvicorn_workers: int = 1uvicorn_reload: bool = Falseuvicorn_timeout_keep_alive: int = 5- use_uvloop: bool = False- use_granian: bool = False+ use_uvloop: bool = Field(default=True, description="Enable uvloop as asyncio event loop.")+ use_granian: bool = Field(default=False, description="Use Granian for workers")sqlalchemy_tracing: bool = False# event loop parallelism@@ -244,6 +253,10 @@ class Settings(BaseSettings):use_experimental: bool = Falseuse_vertex_structured_outputs_experimental: bool = False+ # Database pool monitoring+ enable_db_pool_monitoring: bool = True # Enable connection pool monitoring+ db_pool_monitoring_interval: int = 30 # Seconds between pool stats collection+# cron job parametersenable_batch_job_polling: bool = Falsepoll_running_llm_batches_interval_seconds: int = 5 * 60@@ -272,7 +285,7 @@ class Settings(BaseSettings):elif self.pg_db and self.pg_user and self.pg_password and self.pg_host and self.pg_port:return f"postgresql+pg8000://{self.pg_user}:{self.pg_password}@{self.pg_host}:{self.pg_port}/{self.pg_db}"else:- return f"postgresql+pg8000://letta:letta@localhost:5432/letta"+ return "postgresql+pg8000://letta:letta@localhost:5432/letta"# add this property to avoid being returned the default# reference: https://github.com/letta-ai/letta/issues/1362@@ -285,6 +298,10 @@ class Settings(BaseSettings):else:return None+ @property+ def database_engine(self) -> DatabaseChoice:+ return DatabaseChoice.POSTGRES if self.letta_pg_uri_no_default else DatabaseChoice.SQLITE+@propertydef plugin_register_dict(self) -> dict:plugins = {}diff --git a/letta/system.py b/letta/system.pyindex e4031bccd..888cc304a 100644--- a/letta/system.py+++ b/letta/system.py@@ -66,7 +66,7 @@ def get_initial_boot_messages(version, timezone):"type": "function","function": {"name": "send_message",- "arguments": '{\n "message": "' + f"Hi, is anyone there?" + '"\n}',+ "arguments": '{\n "message": "' + "Hi, is anyone there?" + '"\n}',},}],diff --git a/letta/utils.py b/letta/utils.pyindex 4ddf0a61a..29699bd6e 100644--- a/letta/utils.py+++ b/letta/utils.py@@ -23,6 +23,7 @@ from urllib.parse import urljoin, urlparseimport demjson3 as demjsonimport tiktokenfrom pathvalidate import sanitize_filename as pathvalidate_sanitize_filename+from sqlalchemy import textimport lettafrom letta.constants import (@@ -35,8 +36,12 @@ from letta.constants import (TOOL_CALL_ID_MAX_LEN,)from letta.helpers.json_helpers import json_dumps, json_loads+from letta.log import get_loggerfrom letta.schemas.openai.chat_completion_response import ChatCompletionResponse+logger = get_logger(__name__)++DEBUG = Falseif "LOG_LEVEL" in os.environ:if os.environ["LOG_LEVEL"] == "DEBUG":@@ -578,7 +583,7 @@ def annotate_message_json_list_with_tool_calls(messages: list[dict], allow_tool_# If we find a function call w/o a tool call ID annotation, annotate itif message["role"] == "assistant" and "function_call" in message:if "tool_call_id" in message and message["tool_call_id"] is not None:- printd(f"Message already has tool_call_id")+ printd("Message already has tool_call_id")tool_call_id = message["tool_call_id"]else:tool_call_id = str(uuid.uuid4())@@ -620,7 +625,7 @@ def annotate_message_json_list_with_tool_calls(messages: list[dict], allow_tool_assistant_tool_call = message["tool_calls"][0]if "id" in assistant_tool_call and assistant_tool_call["id"] is not None:- printd(f"Message already has id (tool_call_id)")+ printd("Message already has id (tool_call_id)")tool_call_id = assistant_tool_call["id"]else:tool_call_id = str(uuid.uuid4())@@ -1182,3 +1187,22 @@ class NullCancellationSignal(CancellationSignal):async def check_and_raise_if_cancelled(self):pass+++async def get_latest_alembic_revision() -> str:+ """Get the current alembic revision ID from the alembic_version table."""+ from letta.server.db import db_registry++ try:+ async with db_registry.async_session() as session:+ result = await session.execute(text("SELECT version_num FROM alembic_version"))+ row = result.fetchone()++ if row:+ return row[0]+ else:+ return "unknown"++ except Exception as e:+ logger.error(f"Error getting latest alembic revision: {e}")+ return "unknown"diff --git a/performance_tests/test_insert_archival_memory.py b/performance_tests/test_insert_archival_memory.pyindex 4ce296646..93deedce5 100644--- a/performance_tests/test_insert_archival_memory.py+++ b/performance_tests/test_insert_archival_memory.py@@ -97,7 +97,7 @@ async def test_insert_archival_memories_concurrent(client):durs = np.array([t[2] for t in timeline])start_offset = starts - starts.min()- print(f"Latency stats (s): min={durs.min():.3f}, mean={durs.mean():.3f}, " f"max={durs.max():.3f}, std={durs.std():.3f}")+ print(f"Latency stats (s): min={durs.min():.3f}, mean={durs.mean():.3f}, max={durs.max():.3f}, std={durs.std():.3f}")# 4) Generate improved plots# Helper: concurrency over time@@ -182,4 +182,4 @@ async def test_insert_large_archival_memory(client):await client.agents.passages.create(agent_id=agent.id, text=text)t1 = time.perf_counter()- print(f"Total time: {t1-t0}")+ print(f"Total time: {t1 - t0}")diff --git a/poetry.lock b/poetry.lockindex a27db5d98..5e404e181 100644--- a/poetry.lock+++ b/poetry.lock@@ -253,7 +253,7 @@ version = "0.21.0"description = "asyncio bridge to the standard sqlite3 module"optional = falsepython-versions = ">=3.9"-groups = ["main"]+groups = ["main", "sqlite"]files = [{file = "aiosqlite-0.21.0-py3-none-any.whl", hash = "sha256:2549cf4057f95f53dcba16f2b64e8e2791d7e1adedb13197dd8ed77bb226d7d0"},{file = "aiosqlite-0.21.0.tar.gz", hash = "sha256:131bb8056daa3bc875608c631c678cda73922a2d4ba8aec373b19f18c17e7aa3"},@@ -4748,6 +4748,28 @@ opentelemetry-util-http = "0.51b0"[package.extras]instruments = ["requests (>=2.0,<3.0)"]+[[package]]+name = "opentelemetry-instrumentation-sqlalchemy"+version = "0.51b0"+description = "OpenTelemetry SQLAlchemy instrumentation"+optional = false+python-versions = ">=3.8"+groups = ["main"]+files = [+ {file = "opentelemetry_instrumentation_sqlalchemy-0.51b0-py3-none-any.whl", hash = "sha256:5ff4816228b496aef1511149e2b17a25e0faacec4d5eb65bf18a9964af40f1af"},+ {file = "opentelemetry_instrumentation_sqlalchemy-0.51b0.tar.gz", hash = "sha256:dbfe95b69006017f903dda194606be458d54789e6b3419d37161fb8861bb98a5"},+]++[package.dependencies]+opentelemetry-api = ">=1.12,<2.0"+opentelemetry-instrumentation = "0.51b0"+opentelemetry-semantic-conventions = "0.51b0"+packaging = ">=21.0"+wrapt = ">=1.11.2"++[package.extras]+instruments = ["sqlalchemy (>=1.0.0,<2.1.0)"]+[[package]]name = "opentelemetry-proto"version = "1.30.0"@@ -7472,7 +7494,7 @@ version = "4.14.1"description = "Backported and Experimental Type Hints for Python 3.9+"optional = falsepython-versions = ">=3.9"-groups = ["main", "dev", "dev,tests"]+groups = ["main", "dev", "dev,tests", "sqlite"]files = [{file = "typing_extensions-4.14.1-py3-none-any.whl", hash = "sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76"},{file = "typing_extensions-4.14.1.tar.gz", hash = "sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36"},@@ -7582,10 +7604,10 @@ standard = ["colorama (>=0.4) ; sys_platform == \"win32\"", "httptools (>=0.5.0)name = "uvloop"version = "0.21.0"description = "Fast implementation of asyncio event loop on top of libuv"-optional = true+optional = falsepython-versions = ">=3.8.0"groups = ["main"]-markers = "extra == \"experimental\" or extra == \"all\""+markers = "(sys_platform != \"win32\" or extra == \"all\") and (extra == \"experimental\" or extra == \"all\") and (platform_python_implementation == \"CPython\" or extra == \"all\")"files = [{file = "uvloop-0.21.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ec7e6b09a6fdded42403182ab6b832b71f4edaf7f37a9a0e371a01db5f0cb45f"},{file = "uvloop-0.21.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:196274f2adb9689a289ad7d65700d37df0c0930fd8e4e743fa4834e850d7719d"},@@ -8357,7 +8379,7 @@ bedrock = ["aioboto3", "boto3"]cloud-tool-sandbox = ["e2b-code-interpreter"]desktop = ["docker", "fastapi", "langchain", "langchain-community", "locust", "pg8000", "pgvector", "psycopg2", "psycopg2-binary", "pyright", "uvicorn", "wikipedia"]dev = ["autoflake", "black", "isort", "locust", "pexpect", "pre-commit", "pyright", "pytest-asyncio", "pytest-order"]-experimental = ["granian", "uvloop"]+experimental = ["granian"]external-tools = ["docker", "firecrawl-py", "langchain", "langchain-community", "wikipedia"]google = ["google-genai"]pinecone = ["pinecone"]@@ -8369,4 +8391,4 @@ tests = ["wikipedia"][metadata]lock-version = "2.1"python-versions = "<3.14,>=3.10"-content-hash = "c4fa225d582dac743e5eb8a1338a71c32bd8c8eb8283dec2331c28599bdf7698"+content-hash = "e4cfc6de5cbf4203f7c10401c531f22101f16ebe49bce595bf16b692cd15f5ac"diff --git a/pyproject.toml b/pyproject.tomlindex fdc989006..0e1070044 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "letta"-version = "0.8.15"+version = "0.8.16"packages = [{include = "letta"},]@@ -77,6 +77,7 @@ openai = "^1.60.0"opentelemetry-api = "1.30.0"opentelemetry-sdk = "1.30.0"opentelemetry-instrumentation-requests = "0.51b0"+opentelemetry-instrumentation-sqlalchemy = "0.51b0"opentelemetry-exporter-otlp = "1.30.0"google-genai = {version = "^1.15.0", optional = true}faker = "^36.1.0"@@ -92,7 +93,7 @@ matplotlib = "^3.10.1"asyncpg = {version = "^0.30.0", optional = true}tavily-python = "^0.7.2"mistralai = "^1.8.1"-uvloop = {version = "^0.21.0", optional = true}+uvloop = {version = "^0.21.0"}granian = {version = "^2.3.2", extras = ["uvloop", "reload"], optional = true}redis = {version = "^6.2.0", optional = true}structlog = "^25.4.0"@@ -106,7 +107,7 @@ postgres = ["pgvector", "pg8000", "psycopg2-binary", "psycopg2", "asyncpg"]redis = ["redis"]pinecone = ["pinecone"]dev = ["pytest", "pytest-asyncio", "pexpect", "black", "pre-commit", "pyright", "pytest-order", "autoflake", "isort", "locust"]-experimental = ["uvloop", "granian"]+experimental = ["granian"]server = ["websockets", "fastapi", "uvicorn"]cloud-tool-sandbox = ["e2b-code-interpreter"]external-tools = ["docker", "langchain", "wikipedia", "langchain-community", "firecrawl-py"]@@ -125,6 +126,10 @@ pytest-mock = "^3.14.0"[tool.poetry.group."dev,tests".dependencies]pytest-json-report = "^1.5.0"++[tool.poetry.group.sqlite.dependencies]+aiosqlite = "^0.21.0"+[tool.black]line-length = 140target-version = ['py310', 'py311', 'py312', 'py313']diff --git a/tests/integration_test_batch_sdk.py b/tests/integration_test_batch_sdk.pyindex d36c5422f..e70435ded 100644--- a/tests/integration_test_batch_sdk.py+++ b/tests/integration_test_batch_sdk.py@@ -70,7 +70,6 @@ def client(server_url):@pytest.mark.asyncioasync def test_create_batch(client: Letta, server: SyncServer):-# create agentsagent1 = client.agents.create(name="agent1_batch",diff --git a/tests/integration_test_builtin_tools.py b/tests/integration_test_builtin_tools.pyindex f9c6df6ad..4e8538257 100644--- a/tests/integration_test_builtin_tools.py+++ b/tests/integration_test_builtin_tools.py@@ -4,6 +4,7 @@ import threadingimport timeimport uuidfrom typing import List+from unittest.mock import AsyncMock, MagicMock, patchimport pytestimport requests@@ -11,8 +12,11 @@ from dotenv import load_dotenvfrom letta_client import Letta, MessageCreatefrom letta_client.types import ToolReturnMessage+from letta.constants import WEB_SEARCH_MODEL_ENV_VAR_NAME+from letta.functions.types import SearchTaskfrom letta.schemas.agent import AgentStatefrom letta.schemas.llm_config import LLMConfig+from letta.services.tool_executor.builtin_tool_executor import LettaBuiltinToolExecutorfrom letta.settings import tool_settings# ------------------------------@@ -109,6 +113,28 @@ def agent_state_with_firecrawl_key(client: Letta) -> AgentState:yield agent_state_instance[email protected](scope="module")+def agent_state_with_web_search_env_var(client: Letta) -> AgentState:+ """+ Creates and returns an agent state for testing with a pre-configured agent.+ """+ client.tools.upsert_base_tools()++ send_message_tool = client.tools.list(name="send_message")[0]+ run_code_tool = client.tools.list(name="run_code")[0]+ web_search_tool = client.tools.list(name="web_search")[0]+ agent_state_instance = client.agents.create(+ name="test_builtin_tools_agent",+ include_base_tools=False,+ tool_ids=[send_message_tool.id, run_code_tool.id, web_search_tool.id],+ model="openai/gpt-4o",+ embedding="letta/letta-free",+ tags=["test_builtin_tools_agent"],+ tool_exec_environment_variables={WEB_SEARCH_MODEL_ENV_VAR_NAME: "gpt-4o"},+ )+ yield agent_state_instance++# ------------------------------# Helper Functions and Constants# ------------------------------@@ -273,6 +299,57 @@ def test_web_search(], f"Invalid api_key_source: {response_json['api_key_source']}"+async def test_web_search_uses_agent_env_var_model():+ """Test that web search uses the model specified in agent tool exec env vars."""++ # create mock agent state with web search model env var+ mock_agent_state = MagicMock()+ mock_agent_state.get_agent_env_vars_as_dict.return_value = {WEB_SEARCH_MODEL_ENV_VAR_NAME: "gpt-4o"}++ # mock openai response+ mock_openai_response = MagicMock()+ mock_openai_response.usage = MagicMock()+ mock_openai_response.usage.total_tokens = 100+ mock_openai_response.usage.prompt_tokens = 80+ mock_openai_response.usage.completion_tokens = 20+ mock_openai_response.choices = [MagicMock()]+ mock_openai_response.choices[0].message.parsed = MagicMock()+ mock_openai_response.choices[0].message.parsed.citations = []++ with (+ patch("openai.AsyncOpenAI") as mock_openai_class,+ patch("letta.services.tool_executor.builtin_tool_executor.model_settings") as mock_model_settings,+ patch.dict(os.environ, {WEB_SEARCH_MODEL_ENV_VAR_NAME: "gpt-4o"}),+ ):++ # setup mocks+ mock_model_settings.openai_api_key = "test-key"++ mock_openai_client = AsyncMock()+ mock_openai_class.return_value = mock_openai_client+ mock_openai_client.beta.chat.completions.parse.return_value = mock_openai_response++ # create executor with mock dependencies+ executor = LettaBuiltinToolExecutor(+ message_manager=MagicMock(),+ agent_manager=MagicMock(),+ block_manager=MagicMock(),+ job_manager=MagicMock(),+ passage_manager=MagicMock(),+ actor=MagicMock(),+ )++ task = SearchTask(query="test query", question="test question")++ await executor.web_search(agent_state=mock_agent_state, tasks=[task], limit=1)++ # verify correct model was used+ mock_openai_client.beta.chat.completions.parse.assert_called_once()+ call_args = mock_openai_client.beta.chat.completions.parse.call_args+ assert call_args[1]["model"] == "gpt-4o"++@pytest.mark.parametrize("llm_config", TESTED_LLM_CONFIGS, ids=[c.model for c in TESTED_LLM_CONFIGS])def test_web_search_using_agent_state_env_var(client: Letta,diff --git a/tests/integration_test_send_message.py b/tests/integration_test_send_message.pyindex 9f6a250e7..4493c6b50 100644--- a/tests/integration_test_send_message.py+++ b/tests/integration_test_send_message.py@@ -752,14 +752,15 @@ def test_step_stream_agent_loop_error("""last_message = client.agents.messages.list(agent_id=agent_state_no_tools.id, limit=1)agent_state_no_tools = client.agents.modify(agent_id=agent_state_no_tools.id, llm_config=llm_config)+ response = client.agents.messages.create_stream(+ agent_id=agent_state_no_tools.id,+ messages=USER_MESSAGE_FORCE_REPLY,+ )with pytest.raises(Exception) as exc_info:- response = client.agents.messages.create_stream(- agent_id=agent_state_no_tools.id,- messages=USER_MESSAGE_FORCE_REPLY,- )- list(response)+ for chunk in response:+ print(chunk)+ print("error info:", exc_info)assert type(exc_info.value) in (ApiError, ValueError)- print(exc_info.value)messages_from_db = client.agents.messages.list(agent_id=agent_state_no_tools.id, after=last_message[0].id)assert len(messages_from_db) == 0diff --git a/tests/integration_test_summarizer.py b/tests/integration_test_summarizer.pyindex 7143f9acd..2f0965c92 100644--- a/tests/integration_test_summarizer.py+++ b/tests/integration_test_summarizer.py@@ -228,7 +228,7 @@ def test_auto_summarize(server, default_user):actor=default_user,)- def summarize_message_exists(messages: List[Message]) -> bool:+ def summarize_message_exists(messages: list[Message]) -> bool:for message in messages:if message.content[0].text and "The following is a summary of the previous" in message.content[0].text:return Truediff --git a/tests/integration_test_voice_agent.py b/tests/integration_test_voice_agent.pyindex 49149cbe6..4390e9789 100644--- a/tests/integration_test_voice_agent.py+++ b/tests/integration_test_voice_agent.py@@ -492,7 +492,6 @@ async def test_voice_sleeptime_agent(disable_e2b_api_key, voice_agent):@pytest.mark.asyncio(loop_scope="module")async def test_init_voice_convo_agent(voice_agent, server, actor):-assert voice_agent.enable_sleeptime == Truemain_agent_tools = [tool.name for tool in voice_agent.tools]assert len(main_agent_tools) == 4diff --git a/tests/mcp/test_mcp.py b/tests/mcp/test_mcp.pyindex d17b9f388..6d8edaca9 100644--- a/tests/mcp/test_mcp.py+++ b/tests/mcp/test_mcp.py@@ -192,7 +192,7 @@ def test_stdio_mcp_server(client, agent_state):messages=[MessageCreate(role="user",- content=[TextContent(text=(f"Use the `{letta_tool.name}` tool with these arguments: " f"{{'state': 'CA'}}."))],+ content=[TextContent(text=(f"Use the `{letta_tool.name}` tool with these arguments: {{'state': 'CA'}}."))],)],)diff --git a/tests/test_agent_serialization_v2.py b/tests/test_agent_serialization_v2.pynew file mode 100644index 000000000..4842a6589--- /dev/null+++ b/tests/test_agent_serialization_v2.py@@ -0,0 +1,1307 @@+import asyncio+from typing import List, Optional++import pytest++from letta.config import LettaConfig+from letta.errors import AgentFileExportError, AgentFileImportError+from letta.orm import Base+from letta.schemas.agent import CreateAgent+from letta.schemas.agent_file import (+ AgentFileSchema,+ AgentSchema,+ BlockSchema,+ FileSchema,+ GroupSchema,+ MessageSchema,+ SourceSchema,+ ToolSchema,+)+from letta.schemas.block import Block, CreateBlock+from letta.schemas.embedding_config import EmbeddingConfig+from letta.schemas.enums import MessageRole+from letta.schemas.llm_config import LLMConfig+from letta.schemas.message import MessageCreate+from letta.schemas.organization import Organization+from letta.schemas.source import Source+from letta.schemas.user import User+from letta.server.server import SyncServer+from letta.services.agent_file_manager import AgentFileManager+from letta.services.file_processor.embedder.openai_embedder import OpenAIEmbedder+from letta.services.file_processor.parser.mistral_parser import MistralFileParser+from tests.utils import create_tool_from_func++# ------------------------------+# Fixtures+# ------------------------------++[email protected](scope="module")+def event_loop():+ """Use a single asyncio loop for the entire test session."""+ loop = asyncio.new_event_loop()+ yield loop+ loop.close()+++def _clear_tables():+ from letta.server.db import db_context++ with db_context() as session:+ for table in reversed(Base.metadata.sorted_tables): # Reverse to avoid FK issues+ session.execute(table.delete()) # Truncate table+ session.commit()++[email protected](autouse=True)+def clear_tables():+ _clear_tables()+++def server():+ config = LettaConfig.load()+ config.save()+ server = SyncServer(init_with_default_org_and_user=True)+ server.tool_manager.upsert_base_tools(actor=server.default_user)++ yield server+++def default_organization(server: SyncServer):+ """Fixture to create and return the default organization."""+ org = server.organization_manager.create_default_organization()+ yield org+++def default_user(server: SyncServer, default_organization):+ """Fixture to create and return the default user within the default organization."""+ user = server.user_manager.create_default_user(org_id=default_organization.id)+ yield user+++def other_organization(server: SyncServer):+ """Fixture to create and return another organization."""+ org = server.organization_manager.create_organization(pydantic_org=Organization(name="test_org"))+ yield org+++def other_user(server: SyncServer, other_organization):+ """Fixture to create and return another user within the other organization."""+ user = server.user_manager.create_user(pydantic_user=User(organization_id=other_organization.id, name="test_user"))+ yield user+++def weather_tool_func():+ def get_weather(location: str) -> str:+ """Get the current weather for a given location.++ Args:+ location: The city and state, e.g. San Francisco, CA++ Returns:+ Weather description+ """+ return f"The weather in {location} is sunny and 72 degrees."++ return get_weather+++def print_tool_func():+ def print_message(message: str) -> str:+ """Print a message to the console.++ Args:+ message: The message to print++ Returns:+ Confirmation message+ """+ print(message)+ return f"Printed: {message}"++ return print_tool_func+++def weather_tool(server, weather_tool_func, default_user):+ weather_tool = server.tool_manager.create_or_update_tool(create_tool_from_func(func=weather_tool_func), actor=default_user)+ yield weather_tool+++def print_tool(server, print_tool_func, default_user):+ print_tool = server.tool_manager.create_or_update_tool(create_tool_from_func(func=print_tool_func), actor=default_user)+ yield print_tool+++def test_block(server: SyncServer, default_user):+ """Fixture to create and return a test block."""+ block_data = Block(+ label="test_block",+ value="Test Block Content",+ description="A test block for agent file tests",+ limit=1000,+ metadata={"type": "test", "category": "demo"},+ )+ block = server.block_manager.create_or_update_block(block_data, actor=default_user)+ yield block+++def agent_file_manager(server, default_user):+ """Fixture to create AgentFileManager with all required services including file processing."""+ manager = AgentFileManager(+ agent_manager=server.agent_manager,+ tool_manager=server.tool_manager,+ source_manager=server.source_manager,+ block_manager=server.block_manager,+ group_manager=server.group_manager,+ mcp_manager=server.mcp_manager,+ file_manager=server.file_manager,+ file_agent_manager=server.file_agent_manager,+ message_manager=server.message_manager,+ embedder=OpenAIEmbedder(),+ file_parser=MistralFileParser(),+ using_pinecone=False,+ )+ yield manager+++def test_agent(server: SyncServer, default_user, default_organization, test_block, weather_tool):+ """Fixture to create and return a test agent with messages."""+ memory_blocks = [+ CreateBlock(label="human", value="User is a test user"),+ CreateBlock(label="persona", value="I am a helpful test assistant"),+ ]++ create_agent_request = CreateAgent(+ name="test_agent_v2",+ system="You are a helpful assistant for testing agent file export/import.",+ memory_blocks=memory_blocks,+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ block_ids=[test_block.id],+ tool_ids=[weather_tool.id],+ tags=["test", "v2", "export"],+ description="Test agent for agent file v2 testing",+ metadata={"test_key": "test_value", "version": "v2"},+ initial_message_sequence=[+ MessageCreate(role=MessageRole.system, content="You are a helpful assistant."),+ MessageCreate(role=MessageRole.user, content="Hello!"),+ MessageCreate(role=MessageRole.assistant, content="Hello! How can I help you today?"),+ ],+ tool_exec_environment_variables={"TEST_VAR": "test_value"},+ message_buffer_autoclear=False,+ )++ agent_state = server.agent_manager.create_agent(+ agent_create=create_agent_request,+ actor=default_user,+ )++ server.send_messages(+ actor=default_user,+ agent_id=agent_state.id,+ input_messages=[MessageCreate(role=MessageRole.user, content="What's the weather like?")],+ )++ agent_state = server.agent_manager.get_agent_by_id(agent_id=agent_state.id, actor=default_user)+ yield agent_state+++async def test_source(server: SyncServer, default_user):+ """Fixture to create and return a test source."""+ source_data = Source(+ name="test_source",+ description="Test source for file export tests",+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ )+ source = await server.source_manager.create_source(source_data, default_user)+ yield source+++async def test_file(server: SyncServer, default_user, test_source):+ """Fixture to create and return a test file attached to test_source."""+ from letta.schemas.file import FileMetadata++ file_data = FileMetadata(+ source_id=test_source.id,+ file_name="test.txt",+ original_file_name="test.txt",+ file_type="text/plain",+ file_size=46,+ )+ file_metadata = await server.file_manager.create_file(file_data, default_user, text="This is a test file for export testing.")+ yield file_metadata+++async def agent_with_files(server: SyncServer, default_user, test_block, weather_tool, test_source, test_file):+ """Fixture to create and return an agent with attached files."""+ memory_blocks = [+ CreateBlock(label="human", value="User is a test user"),+ CreateBlock(label="persona", value="I am a helpful test assistant"),+ ]++ create_agent_request = CreateAgent(+ name="test_agent_v2",+ system="You are a helpful assistant for testing agent file export/import.",+ memory_blocks=memory_blocks,+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ block_ids=[test_block.id],+ tool_ids=[weather_tool.id],+ tags=["test", "v2", "export"],+ description="Test agent for agent file v2 testing",+ metadata={"test_key": "test_value", "version": "v2"},+ initial_message_sequence=[+ MessageCreate(role=MessageRole.system, content="You are a helpful assistant."),+ MessageCreate(role=MessageRole.user, content="Hello!"),+ MessageCreate(role=MessageRole.assistant, content="Hello! How can I help you today?"),+ ],+ tool_exec_environment_variables={"TEST_VAR": "test_value"},+ message_buffer_autoclear=False,+ source_ids=[test_source.id],+ )++ agent_state = await server.agent_manager.create_agent_async(+ agent_create=create_agent_request,+ actor=default_user,+ )++ await server.insert_files_into_context_window(agent_state=agent_state, file_metadata_with_content=[test_file], actor=default_user)++ return (agent_state.id, test_source.id, test_file.id)+++# ------------------------------+# Helper Functions+# ------------------------------+++async def create_test_source(server: SyncServer, name: str, user: User):+ """Helper function to create a test source using server."""+ source_data = Source(+ name=name,+ description=f"Test source {name}",+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ )+ return await server.source_manager.create_source(source_data, user)+++async def create_test_file(server: SyncServer, filename: str, source_id: str, user: User, content: Optional[str] = None):+ """Helper function to create a test file using server."""+ from letta.schemas.file import FileMetadata++ content = content or f"Content of {filename}"+ file_data = FileMetadata(+ source_id=source_id,+ file_name=filename,+ original_file_name=filename,+ file_type="text/plain",+ file_size=len(content),+ )+ return await server.file_manager.create_file(file_data, user, text=content)+++async def create_test_agent_with_files(server: SyncServer, name: str, user: User, file_relationships: List[tuple]):+ """Helper function to create agent with attached files using server.++ Args:+ server: SyncServer instance+ name: Agent name+ user: User creating the agent+ file_relationships: List of (source_id, file_id) tuples+ """+ memory_blocks = [+ CreateBlock(label="human", value="User is a test user"),+ CreateBlock(label="persona", value="I am a helpful test assistant"),+ ]++ create_agent_request = CreateAgent(+ name=name,+ system="You are a helpful assistant for testing file export.",+ memory_blocks=memory_blocks,+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ tags=["test", "files"],+ description="Test agent with files",+ )++ agent_state = await server.agent_manager.create_agent_async(+ agent_create=create_agent_request,+ actor=user,+ )++ for source_id, file_id in file_relationships:+ file_metadata = await server.file_manager.get_file_by_id(file_id, user)+ await server.insert_files_into_context_window(agent_state=agent_state, file_metadata_with_content=[file_metadata], actor=user)++ return agent_state+++def compare_agent_files(original: AgentFileSchema, imported: AgentFileSchema) -> bool:+ """Compare two AgentFileSchema objects for logical equivalence."""+ errors = []++ if len(original.agents) != len(imported.agents):+ errors.append(f"Agent count mismatch: {len(original.agents)} vs {len(imported.agents)}")++ if len(original.tools) != len(imported.tools):+ errors.append(f"Tool count mismatch: {len(original.tools)} vs {len(imported.tools)}")++ if len(original.blocks) != len(imported.blocks):+ errors.append(f"Block count mismatch: {len(original.blocks)} vs {len(imported.blocks)}")++ if len(original.groups) != len(imported.groups):+ errors.append(f"Group count mismatch: {len(original.groups)} vs {len(imported.groups)}")++ if len(original.files) != len(imported.files):+ errors.append(f"File count mismatch: {len(original.files)} vs {len(imported.files)}")++ if len(original.sources) != len(imported.sources):+ errors.append(f"Source count mismatch: {len(original.sources)} vs {len(imported.sources)}")++ for i, (orig_agent, imp_agent) in enumerate(zip(original.agents, imported.agents)):+ agent_errors = _compare_agents(orig_agent, imp_agent, i)+ errors.extend(agent_errors)++ orig_tools_sorted = sorted(original.tools, key=lambda x: x.name)+ imp_tools_sorted = sorted(imported.tools, key=lambda x: x.name)+ for i, (orig_tool, imp_tool) in enumerate(zip(orig_tools_sorted, imp_tools_sorted)):+ tool_errors = _compare_tools(orig_tool, imp_tool, i)+ errors.extend(tool_errors)++ orig_blocks_sorted = sorted(original.blocks, key=lambda x: x.label)+ imp_blocks_sorted = sorted(imported.blocks, key=lambda x: x.label)+ for i, (orig_block, imp_block) in enumerate(zip(orig_blocks_sorted, imp_blocks_sorted)):+ block_errors = _compare_blocks(orig_block, imp_block, i)+ errors.extend(block_errors)++ for i, (orig_group, imp_group) in enumerate(zip(original.groups, imported.groups)):+ group_errors = _compare_groups(orig_group, imp_group, i)+ errors.extend(group_errors)++ for i, (orig_file, imp_file) in enumerate(zip(original.files, imported.files)):+ file_errors = _compare_files(orig_file, imp_file, i)+ errors.extend(file_errors)++ for i, (orig_source, imp_source) in enumerate(zip(original.sources, imported.sources)):+ source_errors = _compare_sources(orig_source, imp_source, i)+ errors.extend(source_errors)++ if errors:+ print("Agent file comparison errors:")+ for error in errors:+ print(f" - {error}")+ return False++ return True+++def _compare_agents(orig: AgentSchema, imp: AgentSchema, index: int) -> List[str]:+ """Compare two AgentSchema objects for logical equivalence."""+ errors = []++ if orig.name != imp.name:+ errors.append(f"Agent {index}: name mismatch: '{orig.name}' vs '{imp.name}'")++ if orig.system != imp.system:+ errors.append(f"Agent {index}: system mismatch")++ if orig.description != imp.description:+ errors.append(f"Agent {index}: description mismatch")++ if orig.agent_type != imp.agent_type:+ errors.append(f"Agent {index}: agent_type mismatch: '{orig.agent_type}' vs '{imp.agent_type}'")++ if sorted(orig.tags or []) != sorted(imp.tags or []):+ errors.append(f"Agent {index}: tags mismatch: {orig.tags} vs {imp.tags}")++ if orig.metadata != imp.metadata:+ errors.append(f"Agent {index}: metadata mismatch")++ if orig.llm_config != imp.llm_config:+ errors.append(f"Agent {index}: llm_config mismatch")++ if orig.embedding_config != imp.embedding_config:+ errors.append(f"Agent {index}: embedding_config mismatch")++ # Tool rules+ if orig.tool_rules != imp.tool_rules:+ errors.append(f"Agent {index}: tool_rules mismatch")++ # Environment variables+ if orig.tool_exec_environment_variables != imp.tool_exec_environment_variables:+ errors.append(f"Agent {index}: tool_exec_environment_variables mismatch")++ # Messages+ if len(orig.messages) != len(imp.messages):+ errors.append(f"Agent {index}: message count mismatch: {len(orig.messages)} vs {len(imp.messages)}")+ else:+ for j, (orig_msg, imp_msg) in enumerate(zip(orig.messages, imp.messages)):+ msg_errors = _compare_messages(orig_msg, imp_msg, index, j)+ errors.extend(msg_errors)++ # In-context messages+ if len(orig.in_context_message_ids) != len(imp.in_context_message_ids):+ errors.append(+ f"Agent {index}: in-context message count mismatch: {len(orig.in_context_message_ids)} vs {len(imp.in_context_message_ids)}"+ )++ # Relationship IDs (lengths should match)+ if len(orig.tool_ids or []) != len(imp.tool_ids or []):+ errors.append(f"Agent {index}: tool_ids count mismatch: {len(orig.tool_ids or [])} vs {len(imp.tool_ids or [])}")++ if len(orig.block_ids or []) != len(imp.block_ids or []):+ errors.append(f"Agent {index}: block_ids count mismatch: {len(orig.block_ids or [])} vs {len(imp.block_ids or [])}")++ if len(orig.source_ids or []) != len(imp.source_ids or []):+ errors.append(f"Agent {index}: source_ids count mismatch: {len(orig.source_ids or [])} vs {len(imp.source_ids or [])}")++ return errors+++def _compare_messages(orig: MessageSchema, imp: MessageSchema, agent_index: int, msg_index: int) -> List[str]:+ """Compare two MessageSchema objects for logical equivalence."""+ errors = []++ if orig.role != imp.role:+ errors.append(f"Agent {agent_index}, Message {msg_index}: role mismatch: '{orig.role}' vs '{imp.role}'")++ if orig.content != imp.content:+ errors.append(f"Agent {agent_index}, Message {msg_index}: content mismatch")++ if orig.name != imp.name:+ errors.append(f"Agent {agent_index}, Message {msg_index}: name mismatch: '{orig.name}' vs '{imp.name}'")++ if orig.model != imp.model:+ errors.append(f"Agent {agent_index}, Message {msg_index}: model mismatch: '{orig.model}' vs '{imp.model}'")++ # Skip agent_id comparison - expected to be different between original and imported++ return errors+++def _compare_tools(orig: ToolSchema, imp: ToolSchema, index: int) -> List[str]:+ """Compare two ToolSchema objects for logical equivalence."""+ errors = []++ if orig.name != imp.name:+ errors.append(f"Tool {index}: name mismatch: '{orig.name}' vs '{imp.name}'")++ if orig.description != imp.description:+ errors.append(f"Tool {index}: description mismatch")++ if orig.source_code != imp.source_code:+ errors.append(f"Tool {index}: source_code mismatch")++ if orig.json_schema != imp.json_schema:+ errors.append(f"Tool {index}: json_schema mismatch")++ if sorted(orig.tags or []) != sorted(imp.tags or []):+ errors.append(f"Tool {index}: tags mismatch: {orig.tags} vs {imp.tags}")++ if orig.metadata_ != imp.metadata_:+ errors.append(f"Tool {index}: metadata mismatch")++ # Skip organization_id comparison - expected to be different between orgs++ return errors+++def _compare_blocks(orig: BlockSchema, imp: BlockSchema, index: int) -> List[str]:+ """Compare two BlockSchema objects for logical equivalence."""+ errors = []++ if orig.label != imp.label:+ errors.append(f"Block {index}: label mismatch: '{orig.label}' vs '{imp.label}'")++ if orig.value != imp.value:+ errors.append(f"Block {index}: value mismatch")++ if orig.limit != imp.limit:+ errors.append(f"Block {index}: limit mismatch: {orig.limit} vs {imp.limit}")++ if orig.description != imp.description:+ errors.append(f"Block {index}: description mismatch")++ if orig.metadata != imp.metadata:+ errors.append(f"Block {index}: metadata mismatch")++ if orig.template_name != imp.template_name:+ errors.append(f"Block {index}: template_name mismatch: '{orig.template_name}' vs '{imp.template_name}'")++ if orig.is_template != imp.is_template:+ errors.append(f"Block {index}: is_template mismatch: {orig.is_template} vs {imp.is_template}")++ return errors+++def _compare_groups(orig: GroupSchema, imp: GroupSchema, index: int) -> List[str]:+ """Compare two GroupSchema objects for logical equivalence."""+ errors = []++ if orig.name != imp.name:+ errors.append(f"Group {index}: name mismatch: '{orig.name}' vs '{imp.name}'")++ if orig.description != imp.description:+ errors.append(f"Group {index}: description mismatch")++ if orig.metadata != imp.metadata:+ errors.append(f"Group {index}: metadata mismatch")++ return errors+++def _compare_files(orig: FileSchema, imp: FileSchema, index: int) -> List[str]:+ """Compare two FileSchema objects for logical equivalence."""+ errors = []++ if orig.file_name != imp.file_name:+ errors.append(f"File {index}: file_name mismatch: '{orig.file_name}' vs '{imp.file_name}'")++ if orig.original_file_name != imp.original_file_name:+ errors.append(f"File {index}: original_file_name mismatch: '{orig.original_file_name}' vs '{imp.original_file_name}'")++ if orig.file_size != imp.file_size:+ errors.append(f"File {index}: file_size mismatch: {orig.file_size} vs {imp.file_size}")++ if orig.file_type != imp.file_type:+ errors.append(f"File {index}: file_type mismatch: '{orig.file_type}' vs '{imp.file_type}'")++ if orig.processing_status != imp.processing_status:+ errors.append(f"File {index}: processing_status mismatch: '{orig.processing_status}' vs '{imp.processing_status}'")++ if orig.metadata != imp.metadata:+ errors.append(f"File {index}: metadata mismatch")++ # Check source_id reference format (should be remapped)+ if not imp.source_id.startswith("source-"):+ errors.append(f"File {index}: source_id not properly remapped: {imp.source_id}")++ return errors+++def _compare_sources(orig: SourceSchema, imp: SourceSchema, index: int) -> List[str]:+ """Compare two SourceSchema objects for logical equivalence."""+ errors = []++ if orig.name != imp.name:+ errors.append(f"Source {index}: name mismatch: '{orig.name}' vs '{imp.name}'")++ if orig.description != imp.description:+ errors.append(f"Source {index}: description mismatch")++ if orig.instructions != imp.instructions:+ errors.append(f"Source {index}: instructions mismatch")++ if orig.metadata != imp.metadata:+ errors.append(f"Source {index}: metadata mismatch")++ if orig.embedding_config != imp.embedding_config:+ errors.append(f"Source {index}: embedding_config mismatch")++ return errors+++def _validate_entity_id(entity_id: str, expected_prefix: str) -> bool:+ """Helper function to validate that an ID follows the expected format (prefix-N)."""+ if not entity_id.startswith(f"{expected_prefix}-"):+ print(f"Invalid {expected_prefix} ID format: {entity_id} should start with '{expected_prefix}-'")+ return False++ try:+ suffix = entity_id[len(expected_prefix) + 1 :]+ int(suffix)+ return True+ except ValueError:+ print(f"Invalid {expected_prefix} ID format: {entity_id} should have integer suffix")+ return False+++def validate_id_format(schema: AgentFileSchema) -> bool:+ """Validate that all IDs follow the expected format (entity-N)."""+ for agent in schema.agents:+ if not _validate_entity_id(agent.id, "agent"):+ return False++ for message in agent.messages:+ if not _validate_entity_id(message.id, "message"):+ return False++ for msg_id in agent.in_context_message_ids:+ if not _validate_entity_id(msg_id, "message"):+ return False++ for tool in schema.tools:+ if not _validate_entity_id(tool.id, "tool"):+ return False++ for block in schema.blocks:+ if not _validate_entity_id(block.id, "block"):+ return False++ for file in schema.files:+ if not _validate_entity_id(file.id, "file"):+ return False++ for source in schema.sources:+ if not _validate_entity_id(source.id, "source"):+ return False++ return True+++# ------------------------------+# Tests+# ------------------------------+++class TestFileExport:+ """Test file export functionality with comprehensive validation"""++ async def test_basic_file_export(self, default_user, agent_file_manager, agent_with_files):+ """Test basic file export functionality"""+ agent_id, source_id, file_id = agent_with_files++ exported = await agent_file_manager.export([agent_id], actor=default_user)++ assert len(exported.agents) == 1+ assert len(exported.sources) == 1+ assert len(exported.files) == 1++ agent = exported.agents[0]+ assert len(agent.files_agents) == 1++ assert _validate_entity_id(agent.id, "agent")+ assert _validate_entity_id(exported.sources[0].id, "source")+ assert _validate_entity_id(exported.files[0].id, "file")++ file_agent = agent.files_agents[0]+ assert file_agent.agent_id == agent.id+ assert file_agent.file_id == exported.files[0].id+ assert file_agent.source_id == exported.sources[0].id++ async def test_multiple_files_per_source(self, server, default_user, agent_file_manager):+ """Test export with multiple files from the same source"""+ source = await create_test_source(server, "multi-file-source", default_user)+ file1 = await create_test_file(server, "file1.txt", source.id, default_user)+ file2 = await create_test_file(server, "file2.txt", source.id, default_user)++ agent = await create_test_agent_with_files(server, "multi-file-agent", default_user, [(source.id, file1.id), (source.id, file2.id)])++ exported = await agent_file_manager.export([agent.id], actor=default_user)++ assert len(exported.agents) == 1+ assert len(exported.sources) == 1+ assert len(exported.files) == 2++ agent = exported.agents[0]+ assert len(agent.files_agents) == 2++ source_id = exported.sources[0].id+ for file_schema in exported.files:+ assert file_schema.source_id == source_id++ file_ids = {f.id for f in exported.files}+ for file_agent in agent.files_agents:+ assert file_agent.file_id in file_ids+ assert file_agent.source_id == source_id++ async def test_multiple_sources_export(self, server, default_user, agent_file_manager):+ """Test export with files from multiple sources"""+ source1 = await create_test_source(server, "source-1", default_user)+ source2 = await create_test_source(server, "source-2", default_user)+ file1 = await create_test_file(server, "file1.txt", source1.id, default_user)+ file2 = await create_test_file(server, "file2.txt", source2.id, default_user)++ agent = await create_test_agent_with_files(+ server, "multi-source-agent", default_user, [(source1.id, file1.id), (source2.id, file2.id)]+ )++ exported = await agent_file_manager.export([agent.id], actor=default_user)++ assert len(exported.agents) == 1+ assert len(exported.sources) == 2+ assert len(exported.files) == 2++ source_ids = {s.id for s in exported.sources}+ for file_schema in exported.files:+ assert file_schema.source_id in source_ids++ async def test_cross_agent_file_deduplication(self, server, default_user, agent_file_manager):+ """Test that files shared across agents are deduplicated in export"""+ source = await create_test_source(server, "shared-source", default_user)+ shared_file = await create_test_file(server, "shared.txt", source.id, default_user)++ agent1 = await create_test_agent_with_files(server, "agent-1", default_user, [(source.id, shared_file.id)])+ agent2 = await create_test_agent_with_files(server, "agent-2", default_user, [(source.id, shared_file.id)])++ exported = await agent_file_manager.export([agent1.id, agent2.id], actor=default_user)++ assert len(exported.agents) == 2+ assert len(exported.sources) == 1+ assert len(exported.files) == 1++ file_id = exported.files[0].id+ source_id = exported.sources[0].id++ for agent in exported.agents:+ assert len(agent.files_agents) == 1+ file_agent = agent.files_agents[0]+ assert file_agent.file_id == file_id+ assert file_agent.source_id == source_id++ async def test_file_agent_relationship_preservation(self, server, default_user, agent_file_manager):+ """Test that file-agent relationship details are preserved"""+ source = await create_test_source(server, "test-source", default_user)+ file = await create_test_file(server, "test.txt", source.id, default_user)++ agent = await create_test_agent_with_files(server, "test-agent", default_user, [(source.id, file.id)])++ exported = await agent_file_manager.export([agent.id], actor=default_user)++ agent = exported.agents[0]+ file_agent = agent.files_agents[0]++ assert file_agent.file_name == file.file_name+ assert file_agent.is_open is True+ assert hasattr(file_agent, "last_accessed_at")++ async def test_id_remapping_consistency(self, server, default_user, agent_file_manager):+ """Test that ID remapping is consistent across all references"""+ source = await create_test_source(server, "consistency-source", default_user)+ file = await create_test_file(server, "consistency.txt", source.id, default_user)+ agent = await create_test_agent_with_files(server, "consistency-agent", default_user, [(source.id, file.id)])++ exported = await agent_file_manager.export([agent.id], actor=default_user)++ agent_schema = exported.agents[0]+ source_schema = exported.sources[0]+ file_schema = exported.files[0]+ file_agent = agent_schema.files_agents[0]++ assert file_schema.source_id == source_schema.id+ assert file_agent.agent_id == agent_schema.id+ assert file_agent.file_id == file_schema.id+ assert file_agent.source_id == source_schema.id++ async def test_empty_file_relationships(self, server, default_user, agent_file_manager):+ """Test export of agent with no file relationships"""+ agent_create = CreateAgent(+ name="no-files-agent",+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ )+ agent = await server.agent_manager.create_agent_async(agent_create, actor=default_user)++ exported = await agent_file_manager.export([agent.id], actor=default_user)++ assert len(exported.agents) == 1+ assert len(exported.sources) == 0+ assert len(exported.files) == 0++ agent_schema = exported.agents[0]+ assert len(agent_schema.files_agents) == 0++ async def test_file_content_inclusion_in_export(self, default_user, agent_file_manager, agent_with_files):+ """Test that file content is included in export"""+ agent_id, source_id, file_id = agent_with_files++ exported = await agent_file_manager.export([agent_id], actor=default_user)++ file_schema = exported.files[0]+ assert hasattr(file_schema, "content") or file_schema.content is not None+++class TestAgentFileExport:+ """Tests for agent file export functionality."""++ async def test_basic_export(self, agent_file_manager, test_agent, default_user):+ """Test basic agent export functionality."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ assert isinstance(agent_file, AgentFileSchema)+ assert len(agent_file.agents) == 1+ assert len(agent_file.tools) > 0 # Should include base tools + weather tool+ assert len(agent_file.blocks) > 0 # Should include memory blocks + test block++ assert agent_file.metadata.get("revision_id") is not None+ assert agent_file.metadata.get("revision_id") != "unknown"+ assert len(agent_file.metadata.get("revision_id")) > 0++ assert validate_id_format(agent_file)++ exported_agent = agent_file.agents[0]+ assert exported_agent.name == test_agent.name+ assert exported_agent.system == test_agent.system+ assert len(exported_agent.messages) > 0+ assert len(exported_agent.in_context_message_ids) > 0++ async def test_export_multiple_agents(self, server, agent_file_manager, test_agent, default_user, weather_tool):+ """Test exporting multiple agents."""+ create_agent_request = CreateAgent(+ name="second_test_agent",+ system="Second test agent",+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ tool_ids=[weather_tool.id],+ initial_message_sequence=[+ MessageCreate(role=MessageRole.user, content="Second agent message"),+ ],+ )++ second_agent = server.agent_manager.create_agent(+ agent_create=create_agent_request,+ actor=default_user,+ )++ agent_file = await agent_file_manager.export([test_agent.id, second_agent.id], default_user)++ assert len(agent_file.agents) == 2+ assert validate_id_format(agent_file)++ agent_ids = {agent.id for agent in agent_file.agents}+ assert len(agent_ids) == 2++ async def test_export_id_remapping(self, agent_file_manager, test_agent, default_user):+ """Test that IDs are properly remapped during export."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ exported_agent = agent_file.agents[0]++ assert exported_agent.id == "agent-0"+ assert exported_agent.id != test_agent.id++ if exported_agent.tool_ids:+ for tool_id in exported_agent.tool_ids:+ assert tool_id.startswith("tool-")++ if exported_agent.block_ids:+ for block_id in exported_agent.block_ids:+ assert block_id.startswith("block-")++ message_ids = {msg.id for msg in exported_agent.messages}+ for in_context_id in exported_agent.in_context_message_ids:+ assert in_context_id in message_ids, f"In-context message ID {in_context_id} not found in messages"++ async def test_message_agent_id_remapping(self, agent_file_manager, test_agent, default_user):+ """Test that message.agent_id is properly remapped during export."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ exported_agent = agent_file.agents[0]++ for message in exported_agent.messages:+ assert (+ message.agent_id == exported_agent.id+ ), f"Message {message.id} has agent_id {message.agent_id}, expected {exported_agent.id}"++ assert exported_agent.id == "agent-0"+ assert exported_agent.id != test_agent.id++ async def test_export_empty_agent_list(self, agent_file_manager, default_user):+ """Test exporting empty agent list."""+ agent_file = await agent_file_manager.export([], default_user)++ assert len(agent_file.agents) == 0+ assert len(agent_file.tools) == 0+ assert len(agent_file.blocks) == 0++ async def test_export_nonexistent_agent(self, agent_file_manager, default_user):+ """Test exporting non-existent agent raises error."""+ with pytest.raises(AgentFileExportError): # Should raise AgentFileExportError for non-existent agent+ await agent_file_manager.export(["non-existent-id"], default_user)++ async def test_revision_id_automatic_setting(self, agent_file_manager, test_agent, default_user):+ """Test that revision_id is automatically set to the latest alembic revision."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ from letta.utils import get_latest_alembic_revision++ expected_revision = await get_latest_alembic_revision()++ assert agent_file.metadata.get("revision_id") == expected_revision++ assert agent_file.metadata.get("revision_id") != "unknown"++ assert len(agent_file.metadata.get("revision_id")) == 12+ assert all(c in "0123456789abcdef" for c in agent_file.metadata.get("revision_id"))+++class TestAgentFileImport:+ """Tests for agent file import functionality."""++ async def test_basic_import(self, agent_file_manager, test_agent, default_user, other_user):+ """Test basic agent import functionality."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ result = await agent_file_manager.import_file(agent_file, other_user)++ assert result.success+ assert result.imported_count > 0+ assert len(result.id_mappings) > 0++ for file_id, db_id in result.id_mappings.items():+ if file_id.startswith("agent-"):+ assert db_id != test_agent.id # New agent should have different ID++ async def test_import_preserves_data(self, server, agent_file_manager, test_agent, default_user, other_user):+ """Test that import preserves all important data."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ result = await agent_file_manager.import_file(agent_file, other_user)++ imported_agent_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id == "agent-0")+ imported_agent = server.agent_manager.get_agent_by_id(imported_agent_id, other_user)++ assert imported_agent.name == test_agent.name+ assert imported_agent.system == test_agent.system+ assert imported_agent.description == test_agent.description+ assert imported_agent.metadata == test_agent.metadata+ assert imported_agent.tags == test_agent.tags++ assert len(imported_agent.tools) == len(test_agent.tools)+ assert len(imported_agent.memory.blocks) == len(test_agent.memory.blocks)++ original_messages = server.message_manager.list_messages_for_agent(test_agent.id, default_user)+ imported_messages = server.message_manager.list_messages_for_agent(imported_agent_id, other_user)++ assert len(imported_messages) == len(original_messages)++ for orig_msg, imp_msg in zip(original_messages, imported_messages):+ assert orig_msg.role == imp_msg.role+ assert orig_msg.content == imp_msg.content+ assert imp_msg.agent_id == imported_agent_id # Should be remapped to new agent++ async def test_import_message_context_preservation(self, server, agent_file_manager, test_agent, default_user, other_user):+ """Test that in-context message references are preserved during import."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ result = await agent_file_manager.import_file(agent_file, other_user)++ imported_agent_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id == "agent-0")+ imported_agent = server.agent_manager.get_agent_by_id(imported_agent_id, other_user)++ assert len(imported_agent.message_ids) == len(test_agent.message_ids)++ imported_messages = server.message_manager.list_messages_for_agent(imported_agent_id, other_user)+ imported_message_ids = {msg.id for msg in imported_messages}++ for in_context_id in imported_agent.message_ids:+ assert in_context_id in imported_message_ids++ async def test_dry_run_import(self, agent_file_manager, test_agent, default_user, other_user):+ """Test dry run import validation."""+ agent_file = await agent_file_manager.export([test_agent.id], default_user)++ result = await agent_file_manager.import_file(agent_file, other_user, dry_run=True)++ assert result.success+ assert result.imported_count == 0 # No actual imports in dry run+ assert len(result.id_mappings) == 0+ assert "dry run" in result.message.lower()++ async def test_import_validation_errors(self, agent_file_manager, other_user):+ """Test import validation catches errors."""+ from letta.utils import get_latest_alembic_revision++ current_revision = await get_latest_alembic_revision()++ invalid_agent_file = AgentFileSchema(+ metadata={"revision_id": current_revision},+ agents=[+ AgentSchema(id="agent-0", name="agent1"),+ AgentSchema(id="agent-0", name="agent2"), # Duplicate ID+ ],+ groups=[],+ blocks=[],+ files=[],+ sources=[],+ tools=[],+ )++ with pytest.raises(AgentFileImportError):+ await agent_file_manager.import_file(invalid_agent_file, other_user)+++class TestAgentFileImportWithProcessing:+ """Tests for agent file import with file processing (chunking/embedding)."""++ async def test_import_with_file_processing(self, server, agent_file_manager, default_user, other_user):+ """Test that import processes files for chunking and embedding."""+ source = await create_test_source(server, "processing-source", default_user)+ file_content = "This is test content for processing. It should be chunked and embedded during import."+ file_metadata = await create_test_file(server, "process.txt", source.id, default_user, content=file_content)++ agent = await create_test_agent_with_files(server, "processing-agent", default_user, [(source.id, file_metadata.id)])++ exported = await agent_file_manager.export([agent.id], default_user)++ result = await agent_file_manager.import_file(exported, other_user)++ assert result.success+ assert result.imported_count > 0++ imported_file_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id.startswith("file-"))++ imported_file = await server.file_manager.get_file_by_id(imported_file_id, other_user)+ assert imported_file.processing_status.value == "completed"++ async def test_import_passage_creation(self, server, agent_file_manager, default_user, other_user):+ """Test that import creates passages for file content."""+ source = await create_test_source(server, "passage-source", default_user)+ file_content = "This content should create passages. Each sentence should be chunked separately."+ file_metadata = await create_test_file(server, "passages.txt", source.id, default_user, content=file_content)++ agent = await create_test_agent_with_files(server, "passage-agent", default_user, [(source.id, file_metadata.id)])++ exported = await agent_file_manager.export([agent.id], default_user)++ result = await agent_file_manager.import_file(exported, other_user)++ imported_file_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id.startswith("file-"))++ passages = await server.passage_manager.list_passages_by_file_id_async(imported_file_id, other_user)+ assert len(passages) > 0++ for passage in passages:+ assert passage.embedding is not None+ assert len(passage.embedding) > 0++ async def test_import_file_status_updates(self, server, agent_file_manager, default_user, other_user):+ """Test that file processing status is updated correctly during import."""+ source = await create_test_source(server, "status-source", default_user)+ file_metadata = await create_test_file(server, "status.txt", source.id, default_user)++ agent = await create_test_agent_with_files(server, "status-agent", default_user, [(source.id, file_metadata.id)])++ exported = await agent_file_manager.export([agent.id], default_user)++ result = await agent_file_manager.import_file(exported, other_user)++ imported_file_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id.startswith("file-"))+ imported_file = await server.file_manager.get_file_by_id(imported_file_id, other_user)++ assert imported_file.processing_status.value == "completed"+ assert imported_file.total_chunks is None+ assert imported_file.chunks_embedded is None++ async def test_import_multiple_files_processing(self, server, agent_file_manager, default_user, other_user):+ """Test import processes multiple files efficiently."""+ source = await create_test_source(server, "multi-source", default_user)+ file1 = await create_test_file(server, "file1.txt", source.id, default_user)+ file2 = await create_test_file(server, "file2.txt", source.id, default_user)++ agent = await create_test_agent_with_files(server, "multi-agent", default_user, [(source.id, file1.id), (source.id, file2.id)])++ exported = await agent_file_manager.export([agent.id], default_user)++ result = await agent_file_manager.import_file(exported, other_user)++ imported_file_ids = [db_id for file_id, db_id in result.id_mappings.items() if file_id.startswith("file-")]+ assert len(imported_file_ids) == 2++ for file_id in imported_file_ids:+ imported_file = await server.file_manager.get_file_by_id(file_id, other_user)+ assert imported_file.processing_status.value == "completed"+++class TestAgentFileRoundTrip:+ """Tests for complete export -> import -> export cycles."""++ async def test_roundtrip_consistency(self, server, agent_file_manager, test_agent, default_user, other_user):+ """Test that export -> import -> export produces consistent results."""+ original_export = await agent_file_manager.export([test_agent.id], default_user)+ result = await agent_file_manager.import_file(original_export, other_user)+ imported_agent_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id == "agent-0")+ second_export = await agent_file_manager.export([imported_agent_id], other_user)+ assert compare_agent_files(original_export, second_export)++ async def test_multiple_roundtrips(self, server, agent_file_manager, test_agent, default_user, other_user):+ """Test multiple rounds of export/import maintain consistency."""+ current_agent_id = test_agent.id+ current_user = default_user++ for i in range(3):+ agent_file = await agent_file_manager.export([current_agent_id], current_user)++ target_user = other_user if current_user == default_user else default_user+ result = await agent_file_manager.import_file(agent_file, target_user)++ current_agent_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id == "agent-0")+ current_user = target_user++ imported_agent = server.agent_manager.get_agent_by_id(current_agent_id, current_user)+ assert imported_agent.name == test_agent.name+++class TestAgentFileEdgeCases:+ """Tests for edge cases and error conditions."""++ async def test_agent_with_no_messages(self, server, agent_file_manager, default_user, other_user):+ """Test exporting/importing agent with no messages."""+ # Create agent with no initial messages+ create_agent_request = CreateAgent(+ name="no_messages_agent",+ system="Agent with no messages",+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ initial_message_sequence=[],+ )++ agent_state = await server.agent_manager.create_agent_async(+ agent_create=create_agent_request,+ actor=default_user,+ _init_with_no_messages=True, # Create with truly no messages+ )++ # Export+ agent_file = await agent_file_manager.export([agent_state.id], default_user)++ # Import+ result = await agent_file_manager.import_file(agent_file, other_user)++ # Verify+ assert result.success+ imported_agent_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id == "agent-0")+ imported_agent = server.agent_manager.get_agent_by_id(imported_agent_id, other_user)++ assert len(imported_agent.message_ids) == 0++ async def test_large_agent_file(self, server, agent_file_manager, default_user, other_user, weather_tool):+ """Test handling of larger agent files with many messages."""+ # Create agent+ create_agent_request = CreateAgent(+ name="large_agent",+ system="Agent with many messages",+ llm_config=LLMConfig.default_config("gpt-4o-mini"),+ embedding_config=EmbeddingConfig.default_config(provider="openai"),+ tool_ids=[weather_tool.id],+ )++ agent_state = server.agent_manager.create_agent(+ agent_create=create_agent_request,+ actor=default_user,+ )++ # Add many messages+ for i in range(10):+ server.send_messages(+ actor=default_user,+ agent_id=agent_state.id,+ input_messages=[MessageCreate(role=MessageRole.user, content=f"Message {i}")],+ )++ # Export+ agent_file = await agent_file_manager.export([agent_state.id], default_user)++ # Verify large file+ exported_agent = agent_file.agents[0]+ assert len(exported_agent.messages) >= 10++ # Import+ result = await agent_file_manager.import_file(agent_file, other_user)++ # Verify all messages imported correctly+ assert result.success+ imported_agent_id = next(db_id for file_id, db_id in result.id_mappings.items() if file_id == "agent-0")+ imported_messages = server.message_manager.list_messages_for_agent(imported_agent_id, other_user)++ assert len(imported_messages) >= 10+++class TestAgentFileValidation:+ """Tests for agent file validation and schema compliance."""++ def test_agent_file_schema_validation(self, test_agent):+ """Test AgentFileSchema validation."""+ # Use a dummy revision for this test since we can't await in sync test+ current_revision = "495f3f474131" # Use a known valid revision format++ # Valid schema+ valid_schema = AgentFileSchema(+ metadata={"revision_id": current_revision},+ agents=[AgentSchema(id="agent-0", name="test")],+ groups=[],+ blocks=[],+ files=[],+ sources=[],+ tools=[],+ # mcp_servers=[],+ )++ # Should not raise+ assert valid_schema.agents[0].id == "agent-0"+ assert valid_schema.metadata.get("revision_id") == current_revision++ def test_message_schema_conversion(self, test_agent, server, default_user):+ """Test MessageSchema.from_message conversion."""+ # Get a message from the test agent+ messages = server.message_manager.list_messages_for_agent(test_agent.id, default_user)+ if messages:+ original_message = messages[0]++ # Convert to MessageSchema+ message_schema = MessageSchema.from_message(original_message)++ # Verify conversion+ assert message_schema.role == original_message.role+ assert message_schema.content == original_message.content+ assert message_schema.model == original_message.model+ assert message_schema.agent_id == original_message.agent_id++ def test_id_format_validation(self):+ """Test ID format validation helper."""+ # Use a dummy revision for this test since we can't await in sync test+ current_revision = "495f3f474131" # Use a known valid revision format++ # Valid schema+ valid_schema = AgentFileSchema(+ metadata={"revision_id": current_revision},+ agents=[AgentSchema(id="agent-0", name="test")],+ groups=[],+ blocks=[BlockSchema(id="block-0", label="test", value="test")],+ files=[],+ sources=[],+ tools=[+ ToolSchema(+ id="tool-0",+ name="test_tool",+ source_code="test",+ json_schema={"name": "test_tool", "parameters": {"type": "object", "properties": {}}},+ )+ ],+ # mcp_servers=[],+ )++ assert validate_id_format(valid_schema)++ # Invalid schema+ invalid_schema = AgentFileSchema(+ metadata={"revision_id": current_revision},+ agents=[AgentSchema(id="invalid-id-format", name="test")],+ groups=[],+ blocks=[],+ files=[],+ sources=[],+ tools=[],+ # mcp_servers=[],+ )++ assert not validate_id_format(invalid_schema)+++if __name__ == "__main__":+ pytest.main([__file__])diff --git a/tests/test_client_legacy.py b/tests/test_client_legacy.pyindex c5dc2e896..3d0c264a3 100644--- a/tests/test_client_legacy.py+++ b/tests/test_client_legacy.py@@ -236,28 +236,6 @@ def test_humans_personas(client: RESTClient, agent: AgentState):assert human.value == "Human text", "Creating human failed"-def test_list_tools_pagination(client: RESTClient):- tools = client.list_tools()- visited_ids = {t.id: False for t in tools}-- cursor = None- # Choose 3 for uneven buckets (only 7 default tools)- num_tools = 3- # Construct a complete pagination test to see if we can return all the tools eventually- for _ in range(0, len(tools), num_tools):- curr_tools = client.list_tools(cursor, num_tools)- assert len(curr_tools) <= num_tools-- for curr_tool in curr_tools:- assert curr_tool.id in visited_ids- visited_ids[curr_tool.id] = True-- cursor = curr_tools[-1].id-- # Assert that everything has been visited- assert all(visited_ids.values())--def test_organization(client: RESTClient):# create an organizationorg_name = "test-org"diff --git a/tests/test_letta_agent_batch.py b/tests/test_letta_agent_batch.pyindex 8e798cb6e..40d68170f 100644--- a/tests/test_letta_agent_batch.py+++ b/tests/test_letta_agent_batch.py@@ -350,7 +350,7 @@ async def test_rethink_tool_modify_agent_state(disable_e2b_api_key, server, defaactor = server.user_manager.get_user_or_default()agent = await server.create_agent_async(request=CreateAgent(- name=f"test_agent_rethink",+ name="test_agent_rethink",include_base_tools=True,model=MODELS["sonnet"],tags=["test_agents"],diff --git a/tests/test_managers.py b/tests/test_managers.pyindex f8833f8fc..7fac3af35 100644--- a/tests/test_managers.py+++ b/tests/test_managers.py@@ -85,7 +85,7 @@ from letta.schemas.user import UserUpdatefrom letta.server.db import db_registryfrom letta.server.server import SyncServerfrom letta.services.block_manager import BlockManager-from letta.services.helpers.agent_manager_helper import calculate_base_tools, calculate_multi_agent_tools+from letta.services.helpers.agent_manager_helper import calculate_base_tools, calculate_multi_agent_tools, validate_agent_exists_asyncfrom letta.services.step_manager import FeedbackTypefrom letta.settings import tool_settingsfrom tests.helpers.utils import comprehensive_agent_checks, validate_context_window_overview@@ -119,6 +119,13 @@ async def async_session():@pytest.fixture(autouse=True)async def _clear_tables(async_session):+ from sqlalchemy import text++ # Temporarily disable foreign key constraints for SQLite only+ engine_name = async_session.bind.dialect.name+ if engine_name == "sqlite":+ await async_session.execute(text("PRAGMA foreign_keys = OFF"))+for table in reversed(Base.metadata.sorted_tables): # Reverse to avoid FK issues# If this is the block_history table, skip itif table.name == "block_history":@@ -126,6 +133,10 @@ async def _clear_tables(async_session):await async_session.execute(table.delete()) # Truncate tableawait async_session.commit()+ # Re-enable foreign key constraints for SQLite only+ if engine_name == "sqlite":+ await async_session.execute(text("PRAGMA foreign_keys = ON"))+@pytest.fixtureasync def default_organization(server: SyncServer):@@ -367,7 +378,6 @@ def hello_world_message_fixture(server: SyncServer, default_user, sarah_agent):"""Fixture to create a tool with default settings and clean up after the test."""# Set up messagemessage = PydanticMessage(- organization_id=default_user.organization_id,agent_id=sarah_agent.id,role="user",content=[TextContent(text="Hello, world!")],@@ -693,6 +703,22 @@ async def another_file(server, default_source, default_user, default_organizatio# ======================================================================================================================# AgentManager Tests - Basic# ======================================================================================================================+async def test_validate_agent_exists_async(server: SyncServer, comprehensive_test_agent_fixture, default_user):+ """Test the validate_agent_exists_async helper function"""+ created_agent, _ = comprehensive_test_agent_fixture++ # test with valid agent+ async with db_registry.async_session() as session:+ # should not raise exception+ await validate_agent_exists_async(session, created_agent.id, default_user)++ # test with non-existent agent+ async with db_registry.async_session() as session:+ with pytest.raises(NoResultFound):+ await validate_agent_exists_async(session, "non-existent-id", default_user)++@pytest.mark.asyncioasync def test_create_get_list_agent(server: SyncServer, comprehensive_test_agent_fixture, default_user, event_loop):# Test agent creation@@ -1651,6 +1677,12 @@ async def test_list_agents_by_tags_pagination(server: SyncServer, default_user,@pytest.mark.asyncio+ not hasattr(__import__("letta.settings"), "settings")+ or not getattr(__import__("letta.settings").settings, "letta_pg_uri_no_default", None)+ or USING_SQLITE,+ reason="Skipping vector-related tests when using SQLite (vector search requires PostgreSQL)",+)async def test_list_agents_query_text_pagination(server: SyncServer, default_user, default_organization, event_loop):"""Test listing agents with query text filtering and pagination."""# Create test agents with specific names and descriptions@@ -1782,7 +1814,6 @@ async def test_reset_messages_with_existing_messages(server: SyncServer, sarah_amsg1 = server.message_manager.create_message(PydanticMessage(agent_id=sarah_agent.id,- organization_id=default_user.organization_id,role="user",content=[TextContent(text="Hello, Sarah!")],),@@ -1791,7 +1822,6 @@ async def test_reset_messages_with_existing_messages(server: SyncServer, sarah_amsg2 = server.message_manager.create_message(PydanticMessage(agent_id=sarah_agent.id,- organization_id=default_user.organization_id,role="assistant",content=[TextContent(text="Hello, user!")],),@@ -1826,7 +1856,6 @@ async def test_reset_messages_idempotency(server: SyncServer, sarah_agent, defauserver.message_manager.create_message(PydanticMessage(agent_id=sarah_agent.id,- organization_id=default_user.organization_id,role="user",content=[TextContent(text="Hello, Sarah!")],),@@ -1856,7 +1885,6 @@ async def test_reset_messages_preserves_system_message_id(server: SyncServer, saserver.message_manager.create_message(PydanticMessage(agent_id=sarah_agent.id,- organization_id=default_user.organization_id,role="user",content=[TextContent(text="Hello!")],),@@ -1890,7 +1918,6 @@ async def test_reset_messages_preserves_system_message_content(server: SyncServeserver.message_manager.create_message(PydanticMessage(agent_id=sarah_agent.id,- organization_id=default_user.organization_id,role="user",content=[TextContent(text="Hello!")],),@@ -2248,6 +2275,11 @@ async def test_agent_list_passages_filtering(server, default_user, sarah_agent,@pytest.mark.asyncio+ not hasattr(__import__("letta.settings"), "settings")+ or not getattr(__import__("letta.settings").settings, "letta_pg_uri_no_default", None),+ reason="Skipping vector-related tests when using SQLite (vector search requires PostgreSQL)",+)async def test_agent_list_passages_vector_search(server, default_user, sarah_agent, default_source, default_file, event_loop):"""Test vector search functionality of agent passages"""embed_model = embedding_model(DEFAULT_EMBEDDING_CONFIG)@@ -2485,11 +2517,6 @@ async def test_passage_cascade_deletion(agentic_passages = await server.agent_manager.list_passages_async(actor=default_user, agent_id=sarah_agent.id, agent_only=True)assert len(agentic_passages) == 0- # Delete source and verify its passages are deleted- await server.source_manager.delete_source(default_source.id, default_user)- with pytest.raises(NoResultFound):- server.passage_manager.get_passage_by_id(source_passage_fixture.id, default_user)-def test_create_agent_passage_specific(server: SyncServer, default_user, sarah_agent):"""Test creating an agent passage using the new agent-specific method."""@@ -2998,21 +3025,18 @@ async def test_user_caching(server: SyncServer, event_loop, default_user, perfordef test_create_tool(server: SyncServer, print_tool, default_user, default_organization):# Assertions to ensure the created tool matches the expected valuesassert print_tool.created_by_id == default_user.id- assert print_tool.organization_id == default_organization.idassert print_tool.tool_type == ToolType.CUSTOMdef test_create_composio_tool(server: SyncServer, composio_github_star_tool, default_user, default_organization):# Assertions to ensure the created tool matches the expected valuesassert composio_github_star_tool.created_by_id == default_user.id- assert composio_github_star_tool.organization_id == default_organization.idassert composio_github_star_tool.tool_type == ToolType.EXTERNAL_COMPOSIOdef test_create_mcp_tool(server: SyncServer, mcp_tool, default_user, default_organization):# Assertions to ensure the created tool matches the expected valuesassert mcp_tool.created_by_id == default_user.id- assert mcp_tool.organization_id == default_organization.idassert mcp_tool.tool_type == ToolType.EXTERNAL_MCPassert mcp_tool.metadata_[MCP_TOOL_TAG_NAME_PREFIX]["server_name"] == "test"@@ -3493,7 +3517,6 @@ def test_message_size(server: SyncServer, hello_world_message_fixture, default_u# Create additional test messagesmessages = [PydanticMessage(- organization_id=default_user.organization_id,agent_id=base_message.agent_id,role=base_message.role,content=[TextContent(text=f"Test message {i}")],@@ -3524,7 +3547,6 @@ def create_test_messages(server: SyncServer, base_message: PydanticMessage, defa"""Helper function to create test messages for all tests"""messages = [PydanticMessage(- organization_id=default_user.organization_id,agent_id=base_message.agent_id,role=base_message.role,content=[TextContent(text=f"Test message {i}")],@@ -3643,7 +3665,6 @@ def test_create_block(server: SyncServer, default_user):assert block.description == block_create.descriptionassert block.limit == block_create.limitassert block.metadata == block_create.metadata- assert block.organization_id == default_user.organization_id@pytest.mark.asyncio@@ -3853,7 +3874,6 @@ async def test_batch_create_multiple_blocks(server: SyncServer, default_user, evassert label in created_by_label, f"Missing label: {label}"blk = created_by_label[label]assert blk.value == value- assert blk.organization_id == default_user.organization_idassert blk.id is not None# Confirm all created blocks exist in the full list from get_blocks@@ -5427,7 +5447,111 @@ async def test_upsert_file_content_basic(server: SyncServer, default_user, defau# Ensure `updated_at` is bumpedorm_file = await async_session.get(FileMetadataModel, created.id)- assert orm_file.updated_at > orm_file.created_at+ assert orm_file.updated_at >= orm_file.created_at+++async def test_get_organization_sources_metadata(server, default_user):+ """Test getting organization sources metadata with aggregated file information."""+ # Create test sources+ source1 = await server.source_manager.create_source(+ source=PydanticSource(+ name="test_source_1",+ embedding_config=DEFAULT_EMBEDDING_CONFIG,+ ),+ actor=default_user,+ )++ source2 = await server.source_manager.create_source(+ source=PydanticSource(+ name="test_source_2",+ embedding_config=DEFAULT_EMBEDDING_CONFIG,+ ),+ actor=default_user,+ )++ # Create test files for source1+ file1_meta = PydanticFileMetadata(+ source_id=source1.id,+ file_name="file1.txt",+ file_type="text/plain",+ file_size=1024,+ )+ file1 = await server.file_manager.create_file(file_metadata=file1_meta, actor=default_user)++ file2_meta = PydanticFileMetadata(+ source_id=source1.id,+ file_name="file2.txt",+ file_type="text/plain",+ file_size=2048,+ )+ file2 = await server.file_manager.create_file(file_metadata=file2_meta, actor=default_user)++ # Create test file for source2+ file3_meta = PydanticFileMetadata(+ source_id=source2.id,+ file_name="file3.txt",+ file_type="text/plain",+ file_size=512,+ )+ file3 = await server.file_manager.create_file(file_metadata=file3_meta, actor=default_user)++ # Test 1: Get organization metadata without detailed per-source metadata (default behavior)+ metadata_summary = await server.file_manager.get_organization_sources_metadata(+ actor=default_user, include_detailed_per_source_metadata=False+ )++ # Verify top-level aggregations are present+ assert metadata_summary.total_sources >= 2 # May have other sources from other tests+ assert metadata_summary.total_files >= 3+ assert metadata_summary.total_size >= 3584++ # Verify sources list is empty when include_detailed_per_source_metadata=False+ assert len(metadata_summary.sources) == 0++ # Test 2: Get organization metadata with detailed per-source metadata+ metadata_detailed = await server.file_manager.get_organization_sources_metadata(+ actor=default_user, include_detailed_per_source_metadata=True+ )++ # Verify top-level aggregations are the same+ assert metadata_detailed.total_sources == metadata_summary.total_sources+ assert metadata_detailed.total_files == metadata_summary.total_files+ assert metadata_detailed.total_size == metadata_summary.total_size++ # Find our test sources in the detailed results+ source1_meta = next((s for s in metadata_detailed.sources if s.source_id == source1.id), None)+ source2_meta = next((s for s in metadata_detailed.sources if s.source_id == source2.id), None)++ assert source1_meta is not None+ assert source1_meta.source_name == "test_source_1"+ assert source1_meta.file_count == 2+ assert source1_meta.total_size == 3072 # 1024 + 2048+ assert len(source1_meta.files) == 2++ # Verify file details in source1+ file1_stats = next((f for f in source1_meta.files if f.file_id == file1.id), None)+ file2_stats = next((f for f in source1_meta.files if f.file_id == file2.id), None)++ assert file1_stats is not None+ assert file1_stats.file_name == "file1.txt"+ assert file1_stats.file_size == 1024++ assert file2_stats is not None+ assert file2_stats.file_name == "file2.txt"+ assert file2_stats.file_size == 2048++ assert source2_meta is not None+ assert source2_meta.source_name == "test_source_2"+ assert source2_meta.file_count == 1+ assert source2_meta.total_size == 512+ assert len(source2_meta.files) == 1++ # Verify file details in source2+ file3_stats = source2_meta.files[0]+ assert file3_stats.file_id == file3.id+ assert file3_stats.file_name == "file3.txt"+ assert file3_stats.file_size == 512@pytest.mark.asyncio@@ -5780,6 +5904,7 @@ async def test_list_jobs(server: SyncServer, default_user, event_loop):assert all(job.metadata["type"].startswith("test") for job in jobs)async def test_list_jobs_with_metadata(server: SyncServer, default_user, event_loop):for i in range(3):job_data = PydanticJob(status=JobStatus.created, metadata={"source_id": f"source-test-{i}"})@@ -6056,7 +6181,6 @@ def test_job_messages_pagination(server: SyncServer, default_run, default_user,message_ids = []for i in range(5):message = PydanticMessage(- organization_id=default_user.organization_id,agent_id=sarah_agent.id,role=MessageRole.user,content=[TextContent(text=f"Test message {i}")],@@ -6173,7 +6297,6 @@ def test_job_messages_ordering(server: SyncServer, default_run, default_user, samessage = PydanticMessage(role=MessageRole.user,content=[TextContent(text="Test message")],- organization_id=default_user.organization_id,agent_id=sarah_agent.id,created_at=created_at,)@@ -6242,19 +6365,16 @@ def test_job_messages_filter(server: SyncServer, default_run, default_user, saraPydanticMessage(role=MessageRole.user,content=[TextContent(text="Hello")],- organization_id=default_user.organization_id,agent_id=sarah_agent.id,),PydanticMessage(role=MessageRole.assistant,content=[TextContent(text="Hi there!")],- organization_id=default_user.organization_id,agent_id=sarah_agent.id,),PydanticMessage(role=MessageRole.assistant,content=[TextContent(text="Let me help you with that")],- organization_id=default_user.organization_id,agent_id=sarah_agent.id,tool_calls=[OpenAIToolCall(@@ -6305,7 +6425,6 @@ def test_get_run_messages(server: SyncServer, default_user: PydanticUser, sarah_# Add some messagesmessages = [PydanticMessage(- organization_id=default_user.organization_id,agent_id=sarah_agent.id,role=MessageRole.tool if i % 2 == 0 else MessageRole.assistant,content=[TextContent(text=f"Test message {i}" if i % 2 == 1 else '{"status": "OK"}')],@@ -6356,7 +6475,6 @@ def test_get_run_messages_with_assistant_message(server: SyncServer, default_use# Add some messagesmessages = [PydanticMessage(- organization_id=default_user.organization_id,agent_id=sarah_agent.id,role=MessageRole.tool if i % 2 == 0 else MessageRole.assistant,content=[TextContent(text=f"Test message {i}" if i % 2 == 1 else '{"status": "OK"}')],@@ -6531,30 +6649,6 @@ def test_job_usage_stats_get_nonexistent_job(server: SyncServer, default_user):job_manager.get_job_usage(job_id="nonexistent_job", actor=default_user)-async def test_job_usage_stats_add_nonexistent_job(server: SyncServer, sarah_agent, default_user, event_loop):- """Test adding usage statistics for a nonexistent job."""- step_manager = server.step_manager-- with pytest.raises(NoResultFound):- await step_manager.log_step_async(- agent_id=sarah_agent.id,- provider_name="openai",- provider_category="base",- model="gpt-4o-mini",- model_endpoint="https://api.openai.com/v1",- context_window_limit=8192,- job_id="nonexistent_job",- usage=UsageStatistics(- completion_tokens=100,- prompt_tokens=50,- total_tokens=150,- ),- actor=default_user,- project_id=sarah_agent.project_id,- )--def test_list_tags(server: SyncServer, default_user, default_organization):"""Test listing tags functionality."""# Create multiple agents with different tags@@ -6650,7 +6744,12 @@ async def test_update_batch_status(server, default_user, dummy_beta_message_batcupdated = await server.batch_manager.get_llm_batch_job_by_id_async(batch.id, actor=default_user)assert updated.status == JobStatus.completedassert updated.latest_polling_response == dummy_beta_message_batch- assert updated.last_polled_at >= before++ # Handle timezone comparison: if last_polled_at is naive, assume it's UTC+ last_polled_at = updated.last_polled_at+ if last_polled_at.tzinfo is None:+ last_polled_at = last_polled_at.replace(tzinfo=timezone.utc)+ assert last_polled_at >= before@pytest.mark.asyncio@@ -6774,13 +6873,24 @@ async def test_list_running_batches(server, default_user, dummy_beta_message_batrecent_batches = await server.batch_manager.list_running_llm_batches_async(actor=default_user, weeks=1)assert len(recent_batches) == num_runningassert all(batch.status == JobStatus.running for batch in recent_batches)- assert all(batch.created_at >= datetime.now(timezone.utc) - timedelta(weeks=1) for batch in recent_batches)++ # Handle timezone comparison: if created_at is naive, assume it's UTC+ cutoff_time = datetime.now(timezone.utc) - timedelta(weeks=1)+ assert all(+ (batch.created_at.replace(tzinfo=timezone.utc) if batch.created_at.tzinfo is None else batch.created_at) >= cutoff_time+ for batch in recent_batches+ )# Filter by sizerecent_batches = await server.batch_manager.list_running_llm_batches_async(actor=default_user, weeks=1, batch_size=2)assert len(recent_batches) == 2assert all(batch.status == JobStatus.running for batch in recent_batches)- assert all(batch.created_at >= datetime.now(timezone.utc) - timedelta(weeks=1) for batch in recent_batches)+ # Handle timezone comparison: if created_at is naive, assume it's UTC+ cutoff_time = datetime.now(timezone.utc) - timedelta(weeks=1)+ assert all(+ (batch.created_at.replace(tzinfo=timezone.utc) if batch.created_at.tzinfo is None else batch.created_at) >= cutoff_time+ for batch in recent_batches+ )# Should return nothing if filtering by a very small timeframe (e.g., 0 weeks)future_batches = await server.batch_manager.list_running_llm_batches_async(actor=default_user, weeks=0)@@ -7990,226 +8100,229 @@ async def test_attach_files_bulk_oversized_bulk(server, default_user, sarah_agen# ======================================================================================================================# Race Condition Tests - Blocks# ======================================================================================================================---async def test_concurrent_block_updates_race_condition(- server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop-):- """Test that concurrent block updates don't cause race conditions."""- agent, _ = comprehensive_test_agent_fixture-- # Create multiple blocks to use in concurrent updates- blocks = []- for i in range(5):- block = await server.block_manager.create_or_update_block_async(- PydanticBlock(label=f"test_block_{i}", value=f"Test block content {i}", limit=1000), actor=default_user- )- blocks.append(block)-- # Test concurrent updates with different block combinations- async def update_agent_blocks(block_subset):- """Update agent with a specific subset of blocks."""- update_request = UpdateAgent(block_ids=[b.id for b in block_subset])- try:- return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)- except Exception as e:- # Capture any errors that occur during concurrent updates- return {"error": str(e)}-- # Run concurrent updates with different block combinations- tasks = [- update_agent_blocks(blocks[:2]), # blocks 0, 1- update_agent_blocks(blocks[1:3]), # blocks 1, 2- update_agent_blocks(blocks[2:4]), # blocks 2, 3- update_agent_blocks(blocks[3:5]), # blocks 3, 4- update_agent_blocks(blocks[:1]), # block 0 only- ]-- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Verify no exceptions occurred- errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]- assert len(errors) == 0, f"Concurrent updates failed with errors: {errors}"-- # Verify all results are valid agent states- valid_results = [r for r in results if not isinstance(r, Exception) and not (isinstance(r, dict) and "error" in r)]- assert len(valid_results) == 5, "All concurrent updates should succeed"-- # Verify final state is consistent- final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)- assert final_agent is not None- assert len(final_agent.memory.blocks) > 0-- # Clean up- for block in blocks:- await server.block_manager.delete_block_async(block.id, actor=default_user)---async def test_concurrent_same_block_updates_race_condition(- server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop-):- """Test that multiple concurrent updates to the same block configuration don't cause issues."""- agent, _ = comprehensive_test_agent_fixture-- # Create a single block configuration to use in all updates- block = await server.block_manager.create_or_update_block_async(- PydanticBlock(label="shared_block", value="Shared block content", limit=1000), actor=default_user- )-- # Test multiple concurrent updates with the same block configuration- async def update_agent_with_same_blocks():- """Update agent with the same block configuration."""- update_request = UpdateAgent(block_ids=[block.id])- try:- return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)- except Exception as e:- return {"error": str(e)}-- # Run 10 concurrent identical updates- tasks = [update_agent_with_same_blocks() for _ in range(10)]- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Verify no exceptions occurred- errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]- assert len(errors) == 0, f"Concurrent identical updates failed with errors: {errors}"-- # Verify final state is consistent- final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)- assert len(final_agent.memory.blocks) == 1- assert final_agent.memory.blocks[0].id == block.id-- # Clean up- await server.block_manager.delete_block_async(block.id, actor=default_user)---async def test_concurrent_empty_block_updates_race_condition(- server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop-):- """Test concurrent updates that remove all blocks."""- agent, _ = comprehensive_test_agent_fixture-- # Test concurrent updates that clear all blocks- async def clear_agent_blocks():- """Update agent to have no blocks."""- update_request = UpdateAgent(block_ids=[])- try:- return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)- except Exception as e:- return {"error": str(e)}-- # Run concurrent clear operations- tasks = [clear_agent_blocks() for _ in range(5)]- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Verify no exceptions occurred- errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]- assert len(errors) == 0, f"Concurrent clear operations failed with errors: {errors}"-- # Verify final state is consistent (no blocks)- final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)- assert len(final_agent.memory.blocks) == 0---async def test_concurrent_mixed_block_operations_race_condition(- server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop-):- """Test mixed concurrent operations: some adding blocks, some removing."""- agent, _ = comprehensive_test_agent_fixture-- # Create test blocks- blocks = []- for i in range(3):- block = await server.block_manager.create_or_update_block_async(- PydanticBlock(label=f"mixed_block_{i}", value=f"Mixed block content {i}", limit=1000), actor=default_user- )- blocks.append(block)-- # Mix of operations: add blocks, remove blocks, clear all- async def mixed_operation(operation_type):- """Perform different types of block operations."""- if operation_type == "add_all":- update_request = UpdateAgent(block_ids=[b.id for b in blocks])- elif operation_type == "add_subset":- update_request = UpdateAgent(block_ids=[blocks[0].id])- elif operation_type == "clear":- update_request = UpdateAgent(block_ids=[])- else:- update_request = UpdateAgent(block_ids=[blocks[1].id, blocks[2].id])-- try:- return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)- except Exception as e:- return {"error": str(e)}-- # Run mixed concurrent operations- tasks = [- mixed_operation("add_all"),- mixed_operation("add_subset"),- mixed_operation("clear"),- mixed_operation("add_two"),- mixed_operation("add_all"),- ]-- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Verify no exceptions occurred- errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]- assert len(errors) == 0, f"Mixed concurrent operations failed with errors: {errors}"-- # Verify final state is consistent (any valid state is acceptable)- final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)- assert final_agent is not None-- # Clean up- for block in blocks:- await server.block_manager.delete_block_async(block.id, actor=default_user)---async def test_high_concurrency_stress_test(server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop):- """Stress test with high concurrency to catch race conditions."""- agent, _ = comprehensive_test_agent_fixture-- # Create many blocks for stress testing- blocks = []- for i in range(10):- block = await server.block_manager.create_or_update_block_async(- PydanticBlock(label=f"stress_block_{i}", value=f"Stress test content {i}", limit=1000), actor=default_user- )- blocks.append(block)-- # Create many concurrent update tasks- async def stress_update(task_id):- """Perform a random block update operation."""- import random-- # Random subset of blocks- num_blocks = random.randint(0, len(blocks))- selected_blocks = random.sample(blocks, num_blocks)-- update_request = UpdateAgent(block_ids=[b.id for b in selected_blocks])-- try:- return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)- except Exception as e:- return {"error": str(e), "task_id": task_id}-- # Run 20 concurrent stress updates- tasks = [stress_update(i) for i in range(20)]- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Verify no exceptions occurred- errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]- assert len(errors) == 0, f"High concurrency stress test failed with errors: {errors}"-- # Verify final state is consistent- final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)- assert final_agent is not None-- # Clean up- for block in blocks:- await server.block_manager.delete_block_async(block.id, actor=default_user)+# TODO: These fail intermittently, need to investigate+"""+FAILED tests/test_managers.py::test_high_concurrency_stress_test - AssertionError: High concurrency stress test failed with errors: [{'error': "(sqlalchemy.dialects.postgresql.asyncpg.Error) <class 'asyncpg.exceptions.DeadlockDetectedError'>: deadlock detected\nDETAIL: Process ***04 waits for ShareLock on transaction 30***3; blocked by process 84.\nProcess 84 waits for ShareLock on transaction 30***5; blocked by process ***04.\nHINT: See server log for query details.\n[SQL: INSERT INTO blocks_agents (agent_id, block_id, block_label) VALUES ($***::VARCHAR, $2::VARCHAR, $3::VARCHAR), ($4::VARCHAR, $5::VARCHAR, $6::VARCHAR), ($7::VARCHAR, $8::VARCHAR, $9::VARCHAR), ($***0::VARCHAR, $***::VARCHAR, $***2::VARCHAR) ON CONFLICT DO NOTHING]\n[parameters: ('agent-f69c0ffc-48ea-47f3-a6e0-e26a4***de764d', 'block-4506d355-b84a-44cd-bfdb-63a5039***07f***', 'stress_block_7', 'agent-f69c0ffc-48ea-47f3-a6e0-e26a4***de764d', 'block-cf32229c-9b43-4ed9-b65f-fc7cb***3567bf', 'stress_block_6', 'agent-f69c0ffc-48ea-47f3-a6e0-e26a4***de764d', 'block-02a***8***e7-44d6-402***-85a0-2c3dc20d9fae', 'stress_block_8', 'agent-f69c0ffc-48ea-47f3-a6e0-e26a4***de764d', 'block-4cba5***c***-42b8-4afa-aa59-97022c29f7a2', 'stress_block_0')]\n(Background on this error at: https://sqlalche.me/e/20/dbapi)", 'task_id': 4}]+"""+#+# @pytest.mark.asyncio+# async def test_concurrent_block_updates_race_condition(+# server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop+# ):+# """Test that concurrent block updates don't cause race conditions."""+# agent, _ = comprehensive_test_agent_fixture+#+# # Create multiple blocks to use in concurrent updates+# blocks = []+# for i in range(5):+# block = await server.block_manager.create_or_update_block_async(+# PydanticBlock(label=f"test_block_{i}", value=f"Test block content {i}", limit=1000), actor=default_user+# )+# blocks.append(block)+#+# # Test concurrent updates with different block combinations+# async def update_agent_blocks(block_subset):+# """Update agent with a specific subset of blocks."""+# update_request = UpdateAgent(block_ids=[b.id for b in block_subset])+# try:+# return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)+# except Exception as e:+# # Capture any errors that occur during concurrent updates+# return {"error": str(e)}+#+# # Run concurrent updates with different block combinations+# tasks = [+# update_agent_blocks(blocks[:2]), # blocks 0, 1+# update_agent_blocks(blocks[1:3]), # blocks 1, 2+# update_agent_blocks(blocks[2:4]), # blocks 2, 3+# update_agent_blocks(blocks[3:5]), # blocks 3, 4+# update_agent_blocks(blocks[:1]), # block 0 only+# ]+#+# results = await asyncio.gather(*tasks, return_exceptions=True)+#+# # Verify no exceptions occurred+# errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]+# assert len(errors) == 0, f"Concurrent updates failed with errors: {errors}"+#+# # Verify all results are valid agent states+# valid_results = [r for r in results if not isinstance(r, Exception) and not (isinstance(r, dict) and "error" in r)]+# assert len(valid_results) == 5, "All concurrent updates should succeed"+#+# # Verify final state is consistent+# final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)+# assert final_agent is not None+# assert len(final_agent.memory.blocks) > 0+#+# # Clean up+# for block in blocks:+# await server.block_manager.delete_block_async(block.id, actor=default_user)+#+#+# @pytest.mark.asyncio+# async def test_concurrent_same_block_updates_race_condition(+# server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop+# ):+# """Test that multiple concurrent updates to the same block configuration don't cause issues."""+# agent, _ = comprehensive_test_agent_fixture+#+# # Create a single block configuration to use in all updates+# block = await server.block_manager.create_or_update_block_async(+# PydanticBlock(label="shared_block", value="Shared block content", limit=1000), actor=default_user+# )+#+# # Test multiple concurrent updates with the same block configuration+# async def update_agent_with_same_blocks():+# """Update agent with the same block configuration."""+# update_request = UpdateAgent(block_ids=[block.id])+# try:+# return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)+# except Exception as e:+# return {"error": str(e)}+#+# # Run 10 concurrent identical updates+# tasks = [update_agent_with_same_blocks() for _ in range(10)]+# results = await asyncio.gather(*tasks, return_exceptions=True)+#+# # Verify no exceptions occurred+# errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]+# assert len(errors) == 0, f"Concurrent identical updates failed with errors: {errors}"+#+# # Verify final state is consistent+# final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)+# assert len(final_agent.memory.blocks) == 1+# assert final_agent.memory.blocks[0].id == block.id+#+# # Clean up+# await server.block_manager.delete_block_async(block.id, actor=default_user)+#+#+# @pytest.mark.asyncio+# async def test_concurrent_empty_block_updates_race_condition(+# server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop+# ):+# """Test concurrent updates that remove all blocks."""+# agent, _ = comprehensive_test_agent_fixture+#+# # Test concurrent updates that clear all blocks+# async def clear_agent_blocks():+# """Update agent to have no blocks."""+# update_request = UpdateAgent(block_ids=[])+# try:+# return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)+# except Exception as e:+# return {"error": str(e)}+#+# # Run concurrent clear operations+# tasks = [clear_agent_blocks() for _ in range(5)]+# results = await asyncio.gather(*tasks, return_exceptions=True)+#+# # Verify no exceptions occurred+# errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]+# assert len(errors) == 0, f"Concurrent clear operations failed with errors: {errors}"+#+# # Verify final state is consistent (no blocks)+# final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)+# assert len(final_agent.memory.blocks) == 0+#+#+# @pytest.mark.asyncio+# async def test_concurrent_mixed_block_operations_race_condition(+# server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop+# ):+# """Test mixed concurrent operations: some adding blocks, some removing."""+# agent, _ = comprehensive_test_agent_fixture+#+# # Create test blocks+# blocks = []+# for i in range(3):+# block = await server.block_manager.create_or_update_block_async(+# PydanticBlock(label=f"mixed_block_{i}", value=f"Mixed block content {i}", limit=1000), actor=default_user+# )+# blocks.append(block)+#+# # Mix of operations: add blocks, remove blocks, clear all+# async def mixed_operation(operation_type):+# """Perform different types of block operations."""+# if operation_type == "add_all":+# update_request = UpdateAgent(block_ids=[b.id for b in blocks])+# elif operation_type == "add_subset":+# update_request = UpdateAgent(block_ids=[blocks[0].id])+# elif operation_type == "clear":+# update_request = UpdateAgent(block_ids=[])+# else:+# update_request = UpdateAgent(block_ids=[blocks[1].id, blocks[2].id])+#+# try:+# return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)+# except Exception as e:+# return {"error": str(e)}+#+# # Run mixed concurrent operations+# tasks = [+# mixed_operation("add_all"),+# mixed_operation("add_subset"),+# mixed_operation("clear"),+# mixed_operation("add_two"),+# mixed_operation("add_all"),+# ]+#+# results = await asyncio.gather(*tasks, return_exceptions=True)+#+# # Verify no exceptions occurred+# errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]+# assert len(errors) == 0, f"Mixed concurrent operations failed with errors: {errors}"+#+# # Verify final state is consistent (any valid state is acceptable)+# final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)+# assert final_agent is not None+#+# # Clean up+# for block in blocks:+# await server.block_manager.delete_block_async(block.id, actor=default_user)+#+#+# @pytest.mark.asyncio+# async def test_high_concurrency_stress_test(server: SyncServer, comprehensive_test_agent_fixture, default_user: PydanticUser, event_loop):+# """Stress test with high concurrency to catch race conditions."""+# agent, _ = comprehensive_test_agent_fixture+#+# # Create many blocks for stress testing+# blocks = []+# for i in range(10):+# block = await server.block_manager.create_or_update_block_async(+# PydanticBlock(label=f"stress_block_{i}", value=f"Stress test content {i}", limit=1000), actor=default_user+# )+# blocks.append(block)+#+# # Create many concurrent update tasks+# async def stress_update(task_id):+# """Perform a random block update operation."""+# import random+#+# # Random subset of blocks+# num_blocks = random.randint(0, len(blocks))+# selected_blocks = random.sample(blocks, num_blocks)+#+# update_request = UpdateAgent(block_ids=[b.id for b in selected_blocks])+#+# try:+# return await server.agent_manager.update_agent_async(agent.id, update_request, actor=default_user)+# except Exception as e:+# return {"error": str(e), "task_id": task_id}+#+# # Run 20 concurrent stress updates+# tasks = [stress_update(i) for i in range(20)]+# results = await asyncio.gather(*tasks, return_exceptions=True)+#+# # Verify no exceptions occurred+# errors = [r for r in results if isinstance(r, Exception) or (isinstance(r, dict) and "error" in r)]+# assert len(errors) == 0, f"High concurrency stress test failed with errors: {errors}"+#+# # Verify final state is consistent+# final_agent = await server.agent_manager.get_agent_by_id_async(agent.id, actor=default_user)+# assert final_agent is not None+#+# # Clean up+# for block in blocks:+# await server.block_manager.delete_block_async(block.id, actor=default_user)diff --git a/tests/test_sdk_client.py b/tests/test_sdk_client.pyindex 71a72322b..e9e4fdfbe 100644--- a/tests/test_sdk_client.py+++ b/tests/test_sdk_client.py@@ -969,70 +969,85 @@ def test_create_tool_from_function_with_docstring(e2b_sandbox_mode, client: Lettclient.tools.delete(tool.id)-def test_preview_payload(client: LettaSDKClient, agent):- payload = client.agents.messages.preview_raw_payload(- agent_id=agent.id,- request=LettaRequest(- messages=[- MessageCreate(- role="user",- content=[- TextContent(- text="text",- )- ],- )- ],- ),+def test_preview_payload(client: LettaSDKClient):+ temp_agent = client.agents.create(+ memory_blocks=[+ CreateBlock(+ label="human",+ value="username: sarah",+ ),+ ],+ model="openai/gpt-4o-mini",+ embedding="openai/text-embedding-3-small",)- assert isinstance(payload, dict)- assert "model" in payload- assert "messages" in payload- assert "tools" in payload- assert "frequency_penalty" in payload- assert "max_completion_tokens" in payload- assert "temperature" in payload- assert "user" in payload- assert "parallel_tool_calls" in payload- assert "tool_choice" in payload-- assert payload["model"] == "gpt-4o-mini"-- assert isinstance(payload["messages"], list)- assert len(payload["messages"]) >= 3-- system_message = payload["messages"][0]- assert system_message["role"] == "system"- assert "base_instructions" in system_message["content"]- assert "memory_blocks" in system_message["content"]- assert "tool_usage_rules" in system_message["content"]- assert "Letta" in system_message["content"]-- assert isinstance(payload["tools"], list)- assert len(payload["tools"]) > 0-- tool_names = [tool["function"]["name"] for tool in payload["tools"]]- expected_tools = ["send_message", "conversation_search", "core_memory_replace", "core_memory_append"]- for tool_name in expected_tools:- assert tool_name in tool_names, f"Expected tool {tool_name} not found in tools"-- for tool in payload["tools"]:- assert tool["type"] == "function"- assert "function" in tool- assert "name" in tool["function"]- assert "description" in tool["function"]- assert "parameters" in tool["function"]- assert tool["function"]["strict"] is True-- assert payload["frequency_penalty"] == 1.0- assert payload["max_completion_tokens"] == 4096- assert payload["temperature"] == 0.7- assert payload["parallel_tool_calls"] is False- assert payload["tool_choice"] == "required"- assert payload["user"].startswith("user-")-- print(payload)+ try:+ payload = client.agents.messages.preview_raw_payload(+ agent_id=temp_agent.id,+ request=LettaRequest(+ messages=[+ MessageCreate(+ role="user",+ content=[+ TextContent(+ text="text",+ )+ ],+ )+ ],+ ),+ )++ assert isinstance(payload, dict)+ assert "model" in payload+ assert "messages" in payload+ assert "tools" in payload+ assert "frequency_penalty" in payload+ assert "max_completion_tokens" in payload+ assert "temperature" in payload+ assert "user" in payload+ assert "parallel_tool_calls" in payload+ assert "tool_choice" in payload++ assert payload["model"] == "gpt-4o-mini"++ assert isinstance(payload["messages"], list)+ assert len(payload["messages"]) >= 3++ system_message = payload["messages"][0]+ assert system_message["role"] == "system"+ assert "base_instructions" in system_message["content"]+ assert "memory_blocks" in system_message["content"]+ assert "tool_usage_rules" in system_message["content"]+ assert "Letta" in system_message["content"]++ assert isinstance(payload["tools"], list)+ assert len(payload["tools"]) > 0++ tool_names = [tool["function"]["name"] for tool in payload["tools"]]+ expected_tools = ["send_message", "conversation_search", "core_memory_replace", "core_memory_append"]+ for tool_name in expected_tools:+ assert tool_name in tool_names, f"Expected tool {tool_name} not found in tools"++ for tool in payload["tools"]:+ assert tool["type"] == "function"+ assert "function" in tool+ assert "name" in tool["function"]+ assert "description" in tool["function"]+ assert "parameters" in tool["function"]+ assert tool["function"]["strict"] is True++ assert payload["frequency_penalty"] == 1.0+ assert payload["max_completion_tokens"] == 4096+ assert payload["temperature"] == 0.7+ assert payload["parallel_tool_calls"] is False+ assert payload["tool_choice"] == "required"+ assert payload["user"].startswith("user-")++ print(payload)+ finally:+ # Clean up the agent+ client.agents.delete(agent_id=temp_agent.id)def test_agent_tools_list(client: LettaSDKClient):diff --git a/tests/test_sources.py b/tests/test_sources.pyindex 758fc3689..12effb2fa 100644--- a/tests/test_sources.py+++ b/tests/test_sources.py@@ -468,6 +468,11 @@ def test_agent_uses_open_close_file_correctly(disable_pinecone, client: LettaSDKprint("✓ File successfully opened with different range - content differs as expected")+ not hasattr(__import__("letta.settings"), "settings")+ or not getattr(__import__("letta.settings").settings, "letta_pg_uri_no_default", None),+ reason="Skipping vector-related tests when using SQLite (vector search requires PostgreSQL)",+)def test_agent_uses_search_files_correctly(disable_pinecone, client: LettaSDKClient, agent_state: AgentState):# Create a new sourcesource = client.sources.create(name="test_source", embedding="openai/text-embedding-3-small")@@ -839,6 +844,11 @@ def test_open_files_schema_descriptions(disable_pinecone, client: LettaSDKClient# --- Pinecone Tests ---+ not hasattr(__import__("letta.settings"), "settings")+ or not getattr(__import__("letta.settings").settings, "letta_pg_uri_no_default", None),+ reason="Skipping vector-related tests when using SQLite (vector search requires PostgreSQL)",+)def test_pinecone_search_files_tool(client: LettaSDKClient):"""Test that search_files tool uses Pinecone when enabled"""from letta.helpers.pinecone_utils import should_use_pinecone@@ -890,6 +900,11 @@ def test_pinecone_search_files_tool(client: LettaSDKClient):), f"Search results should contain relevant content: {search_results}"+ not hasattr(__import__("letta.settings"), "settings")+ or not getattr(__import__("letta.settings").settings, "letta_pg_uri_no_default", None),+ reason="Skipping vector-related tests when using SQLite (vector search requires PostgreSQL)",+)def test_pinecone_lifecycle_file_and_source_deletion(client: LettaSDKClient):"""Test that file and source deletion removes records from Pinecone"""import asynciodiff --git a/tests/test_timezone_formatting.py b/tests/test_timezone_formatting.pyindex ca259e89e..878799a16 100644--- a/tests/test_timezone_formatting.py+++ b/tests/test_timezone_formatting.py@@ -68,9 +68,9 @@ class TestTimezoneFormatting:# Check that times are within tolerancetime_diff = abs((parsed_time - current_time_in_tz).total_seconds())- assert time_diff <= tolerance_minutes * 60, (- f"Time difference too large: {time_diff}s. " f"Parsed: {parsed_time}, Expected timezone: {current_time_in_tz}"- )+ assert (+ time_diff <= tolerance_minutes * 60+ ), f"Time difference too large: {time_diff}s. Parsed: {parsed_time}, Expected timezone: {current_time_in_tz}"# Verify timezone info exists and format looks reasonableassert parsed_time.tzinfo is not None, "Parsed time should have timezone info"diff --git a/tests/test_tool_rule_solver.py b/tests/test_tool_rule_solver.pyindex d81b2011d..a228e250c 100644--- a/tests/test_tool_rule_solver.py+++ b/tests/test_tool_rule_solver.py@@ -138,7 +138,9 @@ def test_max_count_per_step_tool_rule():assert solver.get_allowed_tool_names({START_TOOL}) == [START_TOOL], "After first use, should still allow 'start_tool'"solver.register_tool_call(START_TOOL)- assert solver.get_allowed_tool_names({START_TOOL}) == [], "After reaching max count, 'start_tool' should no longer be allowed"+ assert (+ solver.get_allowed_tool_names({START_TOOL}, error_on_empty=False) == []+ ), "After reaching max count, 'start_tool' should no longer be allowed"def test_max_count_per_step_tool_rule_allows_usage_up_to_limit():@@ -155,7 +157,7 @@ def test_max_count_per_step_tool_rule_allows_usage_up_to_limit():assert solver.get_allowed_tool_names({START_TOOL}) == [START_TOOL], "Should still allow 'start_tool' after 2 uses"solver.register_tool_call(START_TOOL)- assert solver.get_allowed_tool_names({START_TOOL}) == [], "Should no longer allow 'start_tool' after 3 uses"+ assert solver.get_allowed_tool_names({START_TOOL}, error_on_empty=False) == [], "Should no longer allow 'start_tool' after 3 uses"def test_max_count_per_step_tool_rule_does_not_affect_other_tools():@@ -180,7 +182,7 @@ def test_max_count_per_step_tool_rule_resets_on_clear():solver.register_tool_call(START_TOOL)solver.register_tool_call(START_TOOL)- assert solver.get_allowed_tool_names({START_TOOL}) == [], "Should not allow 'start_tool' after reaching limit"+ assert solver.get_allowed_tool_names({START_TOOL}, error_on_empty=False) == [], "Should not allow 'start_tool' after reaching limit"solver.clear_tool_history()diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 5da46f61e..23658b843 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -1,3 +1,5 @@+import asyncio+import pytestfrom letta.constants import MAX_FILENAME_LENGTH@@ -357,13 +359,12 @@ def test_basic_sanitization_no_suffix():def test_formatter():-# Example system prompt that has no varsNO_VARS = """THIS IS A SYSTEM PROMPT WITH NO VARS"""- assert NO_VARS == safe_format(NO_VARS, VARS_DICT)+ assert safe_format(NO_VARS, VARS_DICT) == NO_VARS# Example system prompt that has {CORE_MEMORY}CORE_MEMORY_VAR = """@@ -376,7 +377,7 @@ def test_formatter():My core memory is that I like to eat bananas"""- assert CORE_MEMORY_VAR_SOL == safe_format(CORE_MEMORY_VAR, VARS_DICT)+ assert safe_format(CORE_MEMORY_VAR, VARS_DICT) == CORE_MEMORY_VAR_SOL# Example system prompt that has {CORE_MEMORY} and {USER_MEMORY} (latter doesn't exist)UNUSED_VAR = """@@ -391,7 +392,7 @@ def test_formatter():My core memory is that I like to eat bananas"""- assert UNUSED_VAR_SOL == safe_format(UNUSED_VAR, VARS_DICT)+ assert safe_format(UNUSED_VAR, VARS_DICT) == UNUSED_VAR_SOL# Example system prompt that has {CORE_MEMORY} and {USER_MEMORY} (latter doesn't exist), AND an empty {}UNUSED_AND_EMPRY_VAR = """@@ -408,7 +409,7 @@ def test_formatter():My core memory is that I like to eat bananas"""- assert UNUSED_AND_EMPRY_VAR_SOL == safe_format(UNUSED_AND_EMPRY_VAR, VARS_DICT)+ assert safe_format(UNUSED_AND_EMPRY_VAR, VARS_DICT) == UNUSED_AND_EMPRY_VAR_SOL# ---------------------- LineChunker TESTS ---------------------- #@@ -508,3 +509,49 @@ def test_line_chunker_only_start_parameter():# Test invalid start onlywith pytest.raises(ValueError, match="File test.py has only 3 lines, but requested offset 4 is out of range"):chunker.chunk_text(file, start=3, validate_range=True)+++# ---------------------- Alembic Revision TESTS ---------------------- #++[email protected](scope="module")+def event_loop():+ """+ Create an event loop for the entire test session.+ Ensures all async tasks use the same loop, avoiding cross-loop errors.+ """+ loop = asyncio.new_event_loop()+ yield loop+ loop.close()+++async def test_get_latest_alembic_revision(event_loop):+ """Test that get_latest_alembic_revision returns a valid revision ID from the database."""+ from letta.utils import get_latest_alembic_revision++ # Get the revision ID+ revision_id = await get_latest_alembic_revision()++ # Validate that it's not the fallback "unknown" value+ assert revision_id != "unknown"++ # Validate that it looks like a valid revision ID (12 hex characters)+ assert len(revision_id) == 12+ assert all(c in "0123456789abcdef" for c in revision_id)++ # Validate that it's a string+ assert isinstance(revision_id, str)+++async def test_get_latest_alembic_revision_consistency(event_loop):+ """Test that get_latest_alembic_revision returns the same value on multiple calls."""+ from letta.utils import get_latest_alembic_revision++ # Get the revision ID twice+ revision_id1 = await get_latest_alembic_revision()+ revision_id2 = await get_latest_alembic_revision()++ # They should be identical+ assert revision_id1 == revision_id2