Skip to content

feat(sqlserver): add SQLServerChatMessageHistory - #629

Merged
Facundo Santiago (santiagxf) merged 8 commits into
langchain-ai:mainfrom
0xDevNinja:feat/sqlserver-chat-history
Jul 6, 2026
Merged

feat(sqlserver): add SQLServerChatMessageHistory#629
Facundo Santiago (santiagxf) merged 8 commits into
langchain-ai:mainfrom
0xDevNinja:feat/sqlserver-chat-history

Conversation

@0xDevNinja

Copy link
Copy Markdown
Contributor

Summary

Adds SQLServerChatMessageHistory, an implementation of langchain_core.chat_history.BaseChatMessageHistory backed by a SQL Server / Azure SQL table. This is the chat_message_histories integration tracked in #14.

Messages are JSON-serialized via message_to_dict and stored in an NVARCHAR(MAX) column, keyed by session_id, with an auto-incrementing id column that preserves insertion order on read. The class supports the same connection-string conventions as SQLServer_VectorStore — including Entra ID authentication when the connection string carries no credentials — so users can reuse existing config.

Closes #14

Public API

from langchain_sqlserver import SQLServerChatMessageHistory

history = SQLServerChatMessageHistory(
    session_id="user-123",
    connection_string="Driver={ODBC Driver 18 for SQL Server};Server=tcp:host,1433;Database=mydb;Uid=user;Pwd=pwd;TrustServerCertificate=yes;",
)
history.add_user_message("hi")
history.add_ai_message("hello")
print(history.messages)

Works out of the box with RunnableWithMessageHistory.

Files

  • langchain_sqlserver/chat_message_histories.py — new module with SQLServerChatMessageHistory.
  • langchain_sqlserver/__init__.py — export the new class.
  • tests/unit_tests/test_chat_message_histories.py — 6 unit tests covering validation, Entra-ID-vs-uid/pwd routing, serialization and the empty-input fast path. Does not require a live DB.
  • tests/unit_tests/test_imports.py — extend the __all__ snapshot.
  • tests/integration_tests/test_chat_message_histories.py — 6 integration tests (round-trip persistence, helper methods, session isolation, scoped clear, empty-batch noop, empty-session_id rejection). Uses the existing TEST_AZURESQLSERVER_TRUSTED_CONNECTION / TEST_PYODBC_CONNECTION_STRING env vars.

Test plan

  • ruff check langchain_sqlserver tests — clean
  • mypy langchain_sqlserver tests — clean (14 source files)
  • pytest tests/unit_tests/ — 7 passed (6 new + import snapshot), 1 module skipped (pre-existing)
  • pytest tests/integration_tests/test_chat_message_histories.py against a live SQL Server / Azure SQL instance.

Notes

  • The connection-string parsing and Entra-ID token-provider helpers intentionally mirror those on SQLServer_VectorStore so users get identical auth semantics across both classes. Extracting the helpers into a shared internal module is left as a follow-up so this PR stays additive.

DevNinja (0xDevNinja) and others added 3 commits May 26, 2026 15:08
Adds `SQLServerChatMessageHistory`, an implementation of
`langchain_core.chat_history.BaseChatMessageHistory` backed by a SQL
Server / Azure SQL table. Messages are JSON-serialized via
`message_to_dict` and stored in an `NVARCHAR(MAX)` column, keyed by
`session_id`, with an auto-incrementing `id` column that preserves
insertion order on read.

The class supports the same connection-string conventions as
`SQLServer_VectorStore`, including Entra ID authentication when the
connection string carries no credentials.

Closes langchain-ai#14
@santiagxf

Copy link
Copy Markdown
Collaborator

DevNinja (@0xDevNinja) please let us know if you can address the issues with this PR.

@0xDevNinja

Copy link
Copy Markdown
Contributor Author

Facundo Santiago (@santiagxf) sorted the lint/formatting issues and pushed, CI is passing now. Ready for another look.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new SQLServerChatMessageHistory implementation to the langchain_sqlserver package, enabling LangChain chat message history persistence in SQL Server / Azure SQL using a simple table-backed storage model.

Changes:

  • Introduces SQLServerChatMessageHistory with table creation, message insert/retrieve, and session-scoped clear().
  • Exports the new class from langchain_sqlserver.__init__ and updates the __all__ snapshot test.
  • Adds unit tests (no live DB) and integration tests (requires SQL Server/Azure SQL env vars) for persistence and session isolation.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
libs/sqlserver/langchain_sqlserver/chat_message_histories.py New SQL Server-backed BaseChatMessageHistory implementation, including connection/auth helpers.
libs/sqlserver/langchain_sqlserver/init.py Exports SQLServerChatMessageHistory in the public package API.
libs/sqlserver/tests/unit_tests/test_chat_message_histories.py Adds unit tests for validation and behavior without requiring a live DB.
libs/sqlserver/tests/integration_tests/test_chat_message_histories.py Adds integration coverage for round-trip persistence and session isolation.
libs/sqlserver/tests/unit_tests/test_imports.py Updates expected __all__ list to include the new public symbol.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread libs/sqlserver/langchain_sqlserver/chat_message_histories.py
Comment thread libs/sqlserver/langchain_sqlserver/chat_message_histories.py Outdated
Comment thread libs/sqlserver/tests/unit_tests/test_chat_message_histories.py Outdated
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Comment thread libs/sqlserver/tests/unit_tests/test_chat_message_histories.py
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Comment thread libs/sqlserver/tests/unit_tests/test_chat_message_histories.py
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 7 comments.

Comment on lines +95 to +96
assert {m["data"]["content"] for m in decoded} == {"hi", "yo"}
def _make_history_without_db() -> SQLServerChatMessageHistory:
Comment on lines +148 to +150
except ProgrammingError as e:
logging.error(f"Create table {self.table_name} failed.")
raise Exception(e.__cause__) from None
Comment on lines +162 to +164
except DBAPIError as e:
logging.error(f"Fetch messages failed:\n {e.__cause__}\n")
raise Exception(e.__cause__) from None
Comment on lines +190 to +192
except DBAPIError as e:
logging.error(f"Add messages failed:\n {e.__cause__}\n")
raise Exception(e.__cause__) from None
Comment on lines +204 to +206
except DBAPIError as e:
logging.error(f"Clear messages failed:\n {e.__cause__}\n")
raise Exception(e.__cause__) from None
Comment on lines +256 to +259
except KeyError as k:
raise Exception(
f"Server, DB details should be provided in connection string. {k}"
)
Comment on lines +34 to +36
# Best-effort cleanup: clear messages for this session, then drop the
# underlying table if no other session still has rows in it.
history.clear()
Resolve __init__ and test_imports conflicts from the SQLServerVectorStore
rename (langchain-ai#798); keep chat history export alongside the renamed class and
deprecated alias. Apply ruff format.
@santiagxf
Facundo Santiago (santiagxf) merged commit 9be6796 into langchain-ai:main Jul 6, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[langchain-sqlserver] Add support for storing chat history

3 participants