Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(langchain): add LangChain and LangGraph context adapters (#1964)

Hao Zhe81d1b5afd7fb
diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.md
index 92dc5012e..7848e3a86 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -1,6 +1,6 @@
# Agent Integrations Overview
-OpenViking can act as the long-term memory and context backend for many agent runtimes. This section collects the integrations that already exist — pick the one that matches your agent.
+OpenViking can act as the long-term memory and context backend for many agent runtimes. This section collects the supported integration paths — pick the one that matches your agent.
## Which integration should I use?
@@ -8,18 +8,20 @@ OpenViking can act as the long-term memory and context backend for many agent ru
|-------------|----------|
| **Claude Code** | [Claude Code Memory Plugin](./02-claude-code.md) — auto-recall + auto-capture via hooks, no MCP tool calls required from the model |
| **OpenClaw** | [OpenClaw Plugin](./03-openclaw.md) — context-engine + hooks + tools + runtime manager, deep lifecycle integration |
+| **LangChain / LangGraph** | [LangChain and LangGraph](./05-langchain-langgraph.md) — session context backend, chat history, retriever, `viking_*` tools, LangGraph store, and middleware for agent workflows |
| **Codex / OpenCode** | [Other community plugins](./04-other-plugins.md) — MCP-only and tool-mechanism variants |
| **Cursor / Trae / Manus / Claude Desktop / ChatGPT / …** | [MCP Integration Guide](../guides/06-mcp-integration.md) — point any MCP-compatible client at the built-in `/mcp` endpoint |
| **Hermes Agent (Nous Research)** | [Hermes — OpenViking memory provider](https://hermes-agent.nousresearch.com/docs/user-guide/features/memory-providers#openviking) — first-class OpenViking memory provider, no plugin install needed |
-## Two integration depths
+## Integration Depths
-The plugins listed here go beyond what a generic MCP client can do:
+Some integrations go beyond what a generic MCP client can do:
- **Generic MCP clients** call OpenViking on demand through tools the model decides to invoke. Setup is one config snippet.
- **Hooks-based plugins** (Claude Code, OpenClaw) drive recall and capture from runtime lifecycle events — every prompt, every turn, session start/end, compact, subagent spawn. The model doesn't need to "remember to recall."
+- **SDK integrations** (LangChain/LangGraph) wire OpenViking into framework-native abstractions such as retrievers, tools, chat history, stores, and middleware.
-For agents whose runtime exposes hooks or a context-engine slot, the hooks-based path is usually the better default.
+For agents whose runtime exposes hooks, middleware, or a context-engine slot, the native integration path is usually the better default.
## Prerequisite for all integrations
diff --git a/docs/en/agent-integrations/05-langchain-langgraph.md b/docs/en/agent-integrations/05-langchain-langgraph.md
new file mode 100644
index 000000000..37304a2bc
--- /dev/null
+++ b/docs/en/agent-integrations/05-langchain-langgraph.md
@@ -0,0 +1,230 @@
+# LangChain and LangGraph
+
+OpenViking can be configured as the context backend for LangChain and LangGraph agents through optional Python SDK adapters. The recommended deployment is HTTP mode: the agent app connects to a running OpenViking server, and OpenViking handles storage, indexing, embeddings, VLM parsing, session compression, and memory extraction.
+
+- `with_openviking_context()` wraps LangChain runnables with session assembly, recall, capture, and optional commit policy.
+- `OpenVikingContextMiddleware` gives LangGraph agents the same session lifecycle through middleware.
+- `OpenVikingChatMessageHistory` stores LangChain history in OpenViking sessions.
+- `create_openviking_tools()` exposes common `viking_*` tools for agents.
+- `OpenVikingRetriever` returns LangChain `Document` objects from OpenViking `find` or `search`.
+- `OpenVikingStore` implements LangGraph's `BaseStore` for durable user or agent state.
+
+Install the optional dependencies:
+
+```bash
+pip install "openviking[langgraph]"
+```
+
+For retriever-only LangChain usage:
+
+```bash
+pip install "openviking[langchain]"
+```
+
+## Connection Setup
+
+In production, configure OpenViking once, start `openviking-server`, and connect from the LangChain/LangGraph app:
+
+```python
+connection = {
+ "url": "http://localhost:1933",
+ "api_key": "...",
+ "user_id": "user-123",
+ "agent_id": "support-agent",
+}
+```
+
+The application still owns its LLM calls. OpenViking owns context storage and processing. Embedding and VLM providers are configured in OpenViking, not in the LangChain or LangGraph app.
+
+If `client`, `url`, and `path` are all omitted, the adapters create `SyncHTTPClient()` and load connection settings from the OpenViking CLI config.
+
+Embedded local clients can be passed explicitly with `client=...` or `path=...` for tests, notebooks, and single-process scripts. The primary examples below use HTTP mode.
+
+## LangChain Retriever
+
+```python
+from openviking.integrations.langchain import OpenVikingRetriever
+
+retriever = OpenVikingRetriever(
+ url="http://localhost:1933",
+ api_key="...",
+ target_uri=["viking://user/memories", "viking://resources"],
+ search_mode="find",
+ limit=6,
+)
+
+docs = retriever.invoke("What did the user decide about deployment color?")
+```
+
+Use `search_mode="search"` with `session_id=...` when you want OpenViking's session-aware retrieval. Use `content_mode="read"` to force full L2 reads, or keep the default `auto` mode to read L2 hits and use abstracts/overviews for higher-level hits.
+
+The retriever is a LangChain compatibility surface. For OpenViking-managed context lifecycle, prefer `with_openviking_context()` or `OpenVikingContextMiddleware`.
+
+## LangChain Context Backend
+
+Use `with_openviking_context()` when OpenViking should own the agent context lifecycle, not just retrieval:
+
+```python
+from langchain_core.messages import AIMessage, HumanMessage
+from langchain_core.runnables import RunnableLambda
+from openviking.integrations.langchain import (
+ OpenVikingCommitPolicy,
+ with_openviking_context,
+)
+
+
+def answer(messages):
+ return AIMessage(content="Answer using the injected OpenViking context.")
+
+
+chain = with_openviking_context(
+ RunnableLambda(answer),
+ url="http://localhost:1933",
+ api_key="...",
+ target_uri=["viking://user/memories", "viking://resources"],
+ commit_policy=OpenVikingCommitPolicy(
+ mode="pending_tokens",
+ pending_token_threshold=8_000,
+ ),
+)
+
+result = chain.invoke(
+ [HumanMessage(content="What did we decide about deploys?")],
+ config={"configurable": {"session_id": "agent-thread-123"}},
+)
+```
+
+When `session_id` is omitted from `with_openviking_context()`, each invoke must pass the configured session ID. For one-off scripts or single-session apps, pass `session_id="..."` to `with_openviking_context()` and then call `invoke()` without config.
+
+The wrapper calls `get_session_context()`, injects archive/recall context, stores the completed turn through `OpenVikingChatMessageHistory`, and commits when the configured policy is met. Use the same session ID across invocations when the conversation should share OpenViking working memory and archives.
+
+For direct LangChain history usage:
+
+```python
+from langchain_core.runnables.history import RunnableWithMessageHistory
+from openviking.integrations.langchain import OpenVikingChatMessageHistory
+
+with_history = RunnableWithMessageHistory(
+ runnable,
+ lambda session_id: OpenVikingChatMessageHistory(
+ session_id=session_id,
+ url="http://localhost:1933",
+ api_key="...",
+ ),
+)
+```
+
+`OpenVikingChatMessageHistory` stores text, tool calls/results, and context references as OpenViking `TextPart`, `ToolPart`, and `ContextPart` payloads where those details are available.
+
+## Agent Tools
+
+```python
+from openviking.integrations.langchain import create_openviking_tools
+
+tools = create_openviking_tools(
+ url="http://localhost:1933",
+ api_key="...",
+ profile="agent",
+)
+```
+
+The default agent profile includes:
+
+- `viking_find`: quick semantic recall without session context.
+- `viking_search`: session-aware hierarchical retrieval.
+- `viking_browse`: list or glob OpenViking namespaces.
+- `viking_read`: read one or more Viking URIs as L0 `abstract`, L1 `overview`, or full L2 `read` content.
+- `viking_grep`: grep-style content search.
+- `viking_archive_search`: search assembled session/archive context.
+- `viking_archive_expand`: expand a specific committed session archive.
+- `viking_store`: write conversation turns to an OpenViking session.
+- `viking_add_resource`: import files, directories, URLs, or repositories.
+- `viking_add_skill`: register reusable skills.
+- `viking_health`: check OpenViking status.
+
+The default `agent` profile is intended for trusted, app-controlled agents. Use `profile="retrieval"` or explicit `tool_names=[...]` when a model should only retrieve/read context.
+
+`viking_forget` is intentionally not exposed by the default profile. Use `profile="admin"` or `allow_forget=True` only for trusted agents.
+
+`viking_add_resource` exposes OpenViking resource ingestion to agents. OpenViking parses and indexes documents, repositories, URLs, and supported media according to the server's configured parsers, embedding model, and VLM model. Chat message capture focuses on text, tool, and context parts.
+
+## LangGraph Store
+
+```python
+from openviking.integrations.langchain import OpenVikingStore
+
+store = OpenVikingStore(
+ url="http://localhost:1933",
+ api_key="...",
+ root_uri="viking://user/memories/langgraph_store",
+)
+
+store.put(("users", "ada"), "preferences", {"color": "azure"})
+items = store.search(("users",), query="azure", limit=3)
+```
+
+The store writes JSON records under `<root_uri>/data` and a compact markdown index under `<root_uri>/index`. Query-based `search()` uses OpenViking `find()` over that index, then resolves the original JSON values.
+
+Store writes wait for indexing by default so immediate query-based `search()` can see just-written values. Pass `wait=False` when asynchronous indexing is acceptable.
+
+`OpenVikingStore` is for durable LangGraph store data. It is separate from LangGraph checkpointing.
+
+## LangGraph Middleware
+
+```python
+from langchain.agents import create_agent
+from openviking.integrations.langchain import (
+ OpenVikingCommitPolicy,
+ OpenVikingContextMiddleware,
+)
+
+middleware = OpenVikingContextMiddleware(
+ url="http://localhost:1933",
+ api_key="...",
+ target_uri=["viking://user/memories", "viking://resources"],
+ limit=5,
+ capture_on_after_agent=True,
+ commit_policy=OpenVikingCommitPolicy(
+ mode="pending_tokens",
+ pending_token_threshold=8_000,
+ ),
+)
+
+agent = create_agent(
+ model="...",
+ tools=[],
+ middleware=[middleware],
+)
+```
+
+The middleware adds a marked OpenViking context block to the model system message. The block includes session archive overview and recall results; the active request messages are left as normal LangGraph messages to avoid duplication. After the agent finishes, the middleware captures new user, assistant, tool, and context parts into the OpenViking session.
+
+If your graph passes only the latest request and relies on OpenViking for the session window, set `include_active_messages=True` on the middleware.
+
+LangGraph `thread_id` is the natural OpenViking `session_id`. Reuse the same ID for both systems when you also configure a LangGraph checkpointer. OpenViking handles semantic context and memory; the checkpointer handles exact graph execution resume. Provide `session_id_resolver` if your graph uses a custom thread/session identifier.
+
+The middleware requires a session identifier. If no `thread_id`, `session_id`, or custom resolver is available, it raises `ValueError` instead of writing to a shared default session.
+
+## Try The Examples
+
+The repository includes small deterministic examples that exercise real LangChain and LangGraph application flows without requiring model credentials or a running OpenViking server. They use an OpenViking-compatible in-memory test client so you can see how the adapters fit into an agent app before connecting to a real backend.
+
+From the repository root:
+
+```bash
+uv run --extra langgraph python examples/langchain-langgraph/langchain/rag/quick_app.py
+uv run --extra langgraph python examples/langchain-langgraph/langchain/context-backend/quick_app.py
+uv run --extra langgraph python examples/langchain-langgraph/langchain/message-history/quick_app.py
+uv run --extra langgraph python examples/langchain-langgraph/langgraph/agent/quick_app.py
+uv run --extra langgraph python examples/langchain-langgraph/langgraph/middleware/quick_app.py
+```
+
+The examples cover:
+
+- [LangChain RAG quick app](../../../examples/langchain-langgraph/langchain/rag/quick_app.py): LangChain RAG with `OpenVikingRetriever`.
+- [LangChain context backend quick app](../../../examples/langchain-langgraph/langchain/context-backend/quick_app.py): LangChain session context injection with `with_openviking_context()`.
+- [LangChain message history quick app](../../../examples/langchain-langgraph/langchain/message-history/quick_app.py): LangChain chat history backed by `OpenVikingChatMessageHistory`.
+- [LangGraph agent quick app](../../../examples/langchain-langgraph/langgraph/agent/quick_app.py): LangGraph workflow using OpenViking tools and `OpenVikingStore`.
+- [LangGraph middleware quick app](../../../examples/langchain-langgraph/langgraph/middleware/quick_app.py): LangGraph context injection and capture with `OpenVikingContextMiddleware`.
+
+For a real OpenViking server and OpenAI-compatible model flow, see the [live LangGraph app](../../../examples/langchain-langgraph/langgraph/agent/live_app.py).
diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.md
index 0f7d99247..f08b378d3 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -1,6 +1,6 @@
# Agent 集成概览
-OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端。本节汇总了目前已有的集成,按运行时挑选适合的接入方式即可。
+OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端。本节汇总了已支持的接入方式,按运行时挑选适合的方式即可。
## 该用哪个集成?
@@ -8,18 +8,20 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端
|---------|---------|
| **Claude Code** | [Claude Code 记忆插件](./02-claude-code.md) — 通过 hooks 实现自动召回与自动捕获,模型侧无需主动调用 MCP 工具 |
| **OpenClaw** | [OpenClaw 插件](./03-openclaw.md) — context-engine + hooks + tools + 运行时管理一体化集成,覆盖完整生命周期 |
+| **LangChain / LangGraph** | [LangChain 和 LangGraph](./05-langchain-langgraph.md) — session context backend、chat history、retriever、`viking_*` tools、LangGraph store 和 workflow middleware |
| **Codex / OpenCode** | [其他社区插件](./04-other-plugins.md) — 包括 MCP-only 版本和 tool 机制版本 |
| **Cursor / Trae / Manus / Claude Desktop / ChatGPT / …** | [MCP 集成指南](../guides/06-mcp-integration.md) — 任何兼容 MCP 的客户端都可直接对接内置 `/mcp` 端点 |
| **Hermes Agent (Nous Research)** | [Hermes — OpenViking 记忆提供方](https://hermes-agent.nousresearch.com/docs/user-guide/features/memory-providers#openviking) — 一等公民支持,无需额外安装插件 |
-## 两种集成深度
+## 集成深度
-本页列出的插件能力超过通用 MCP 客户端:
+部分集成能力超过通用 MCP 客户端:
- **通用 MCP 客户端**:模型主动调用工具时按需访问 OpenViking。配置只需一份连接片段。
- **基于 hooks 的插件**(Claude Code、OpenClaw):在运行时生命周期事件(每次 prompt、每轮结束、session 起止、compact、subagent 派生等)中驱动召回与捕获。模型不需要"记得调用"。
+- **SDK 集成**(LangChain/LangGraph):把 OpenViking 接入框架原生抽象,例如 retriever、tools、chat history、store 和 middleware。
-如果你的 Agent runtime 暴露 hooks 或 context-engine 槽位,基于 hooks 的方式通常是更好的默认选择。
+如果你的 Agent runtime 暴露 hooks、middleware 或 context-engine 槽位,原生集成通常是更好的默认选择。
## 所有集成的共同前置
diff --git a/docs/zh/agent-integrations/05-langchain-langgraph.md b/docs/zh/agent-integrations/05-langchain-langgraph.md
new file mode 100644
index 000000000..769f2046b
--- /dev/null
+++ b/docs/zh/agent-integrations/05-langchain-langgraph.md
@@ -0,0 +1,50 @@
+# LangChain 和 LangGraph
+
+OpenViking 可以作为 LangChain 与 LangGraph Agent 的上下文后端使用。该集成提供框架原生的 retriever、chat history、runnable wrapper、LangGraph middleware、LangGraph store,以及 `viking_*` tools。
+
+## 安装
+
+```bash
+pip install "openviking[langchain]"
+pip install "openviking[langgraph]"
+```
+
+如果同时使用 LangChain 和 LangGraph,可以一起安装:
+
+```bash
+pip install "openviking[langchain,langgraph]"
+```
+
+## 连接 OpenViking
+
+本集成默认连接 `http://localhost:1933`。远程服务需要传入 `api_key`、`account`、`user_id`、`agent_id` 等连接参数,或使用环境变量和应用自己的配置层传入这些值。
+
+```python
+from openviking.integrations.langchain import create_openviking_tools
+
+tools = create_openviking_tools(
+ url="http://localhost:1933",
+ profile="agent",
+)
+```
+
+## 常见用法
+
+- 使用 `OpenVikingRetriever` 把 OpenViking 检索结果接入 LangChain RAG。
+- 使用 `create_openviking_tools()` 暴露 `viking_find`、`viking_search`、`viking_browse`、`viking_read`、`viking_grep`、`viking_store` 等工具。
+- 使用 `with_openviking_context(...)` 在 LangChain runnable 前自动装配 OpenViking session context,并在模型调用后捕获对话。
+- 使用 `OpenVikingContextMiddleware` 在 LangGraph agent 中注入上下文、捕获消息,并按 commit policy 触发 session commit。该 middleware 需要明确的 `thread_id`、`session_id` 或自定义 `session_id_resolver`,不会回退到共享默认 session。
+- 使用 `OpenVikingStore` 作为 LangGraph `BaseStore`,把跨线程记忆存入 OpenViking。
+
+## 示例
+
+仓库内提供了可直接运行的最小示例:
+
+- `examples/langchain-langgraph/langchain/rag/quick_app.py`
+- `examples/langchain-langgraph/langchain/context-backend/quick_app.py`
+- `examples/langchain-langgraph/langchain/message-history/quick_app.py`
+- `examples/langchain-langgraph/langgraph/agent/quick_app.py`
+- `examples/langchain-langgraph/langgraph/agent/live_app.py`
+- `examples/langchain-langgraph/langgraph/middleware/quick_app.py`
+
+更完整的英文说明见 [LangChain and LangGraph](../../en/agent-integrations/05-langchain-langgraph.md)。
diff --git a/examples/langchain-langgraph/langchain/context-backend/quick_app.py b/examples/langchain-langgraph/langchain/context-backend/quick_app.py
new file mode 100644
index 000000000..1c82ed93b
--- /dev/null
+++ b/examples/langchain-langgraph/langchain/context-backend/quick_app.py
@@ -0,0 +1,52 @@
+"""Deterministic LangChain app using OpenViking as a session context backend."""
+
+from __future__ import annotations
+
+from langchain_core.messages import AIMessage, HumanMessage
+from langchain_core.runnables import RunnableLambda
+
+from openviking.integrations.langchain import (
+ InMemoryOpenVikingClient,
+ OpenVikingCommitPolicy,
+ with_openviking_context,
+)
+
+
+def build_app(client: InMemoryOpenVikingClient | None = None):
+ client = client or InMemoryOpenVikingClient(
+ {
+ "viking://resources/runbooks/context-backend.md": (
+ "OpenViking context backend examples should answer with azure."
+ )
+ }
+ )
+
+ def answer(messages):
+ context = messages[0].content
+ assert "OpenViking context backend examples" in context
+ return AIMessage(content="OpenViking context says azure.")
+
+ return with_openviking_context(
+ RunnableLambda(answer),
+ client=client,
+ session_id="langchain-context-backend-demo",
+ target_uri="viking://resources",
+ commit_policy=OpenVikingCommitPolicy(
+ mode="pending_tokens",
+ pending_token_threshold=1_000,
+ ),
+ )
+
+
+def main() -> str:
+ app = build_app()
+ result = app.invoke(
+ [HumanMessage(content="What color should this context backend example use?")],
+ )
+ answer = result.content
+ print(answer)
+ return answer
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/langchain-langgraph/langchain/message-history/quick_app.py b/examples/langchain-langgraph/langchain/message-history/quick_app.py
new file mode 100644
index 000000000..e516553ed
--- /dev/null
+++ b/examples/langchain-langgraph/langchain/message-history/quick_app.py
@@ -0,0 +1,52 @@
+"""Deterministic LangChain app using OpenViking-backed chat history."""
+
+from __future__ import annotations
+
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
+from langchain_core.runnables import RunnableLambda
+from langchain_core.runnables.history import RunnableWithMessageHistory
+
+from openviking.integrations.langchain import (
+ InMemoryOpenVikingClient,
+ OpenVikingChatMessageHistory,
+)
+from openviking.integrations.langchain.client import extract_message_text
+
+
+def build_app(client: InMemoryOpenVikingClient | None = None):
+ client = client or InMemoryOpenVikingClient()
+
+ def answer(messages: list[BaseMessage]) -> AIMessage:
+ text = "\n".join(extract_message_text(message.content) for message in messages)
+ if "azure" in text.lower():
+ return AIMessage(content="OpenViking history remembers azure.")
+ return AIMessage(content="OpenViking history is waiting for a preference.")
+
+ return RunnableWithMessageHistory(
+ RunnableLambda(answer),
+ lambda session_id: OpenVikingChatMessageHistory(
+ session_id=session_id,
+ client=client,
+ ),
+ )
+
+
+def main() -> str:
+ app = build_app()
+ config = {"configurable": {"session_id": "langchain-history-demo"}}
+
+ app.invoke(
+ [HumanMessage(content="Remember that the deployment color is azure.")],
+ config=config,
+ )
+ result = app.invoke(
+ [HumanMessage(content="Which deployment color did I ask you to remember?")],
+ config=config,
+ )
+ answer = result.content
+ print(answer)
+ return answer
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/langchain-langgraph/langchain/rag/quick_app.py b/examples/langchain-langgraph/langchain/rag/quick_app.py
new file mode 100644
index 000000000..beaf40af3
--- /dev/null
+++ b/examples/langchain-langgraph/langchain/rag/quick_app.py
@@ -0,0 +1,64 @@
+"""Deterministic LangChain RAG smoke app using OpenViking as retriever."""
+
+from __future__ import annotations
+
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+from langchain_core.output_parsers import StrOutputParser
+from langchain_core.prompts import ChatPromptTemplate
+from langchain_core.runnables import RunnableLambda, RunnablePassthrough
+
+from openviking.integrations.langchain import InMemoryOpenVikingClient, OpenVikingRetriever
+
+
+def build_app(client: InMemoryOpenVikingClient | None = None):
+ client = client or InMemoryOpenVikingClient(
+ {
+ "viking://user/memories/preferences/deploy_color.md": (
+ "The user prefers azure as the deployment color for LangChain examples."
+ ),
+ "viking://resources/runbooks/langchain.md": (
+ "LangChain RAG apps should pass OpenViking recall into the prompt context."
+ ),
+ }
+ )
+ retriever = OpenVikingRetriever(
+ client=client,
+ target_uri=["viking://user/memories", "viking://resources"],
+ limit=4,
+ content_mode="auto",
+ )
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "Answer from the supplied OpenViking context.\n\n{context}"),
+ ("human", "{question}"),
+ ]
+ )
+ model = FakeListChatModel(
+ responses=[
+ "OpenViking recall says the deployment color is azure.",
+ ]
+ )
+ return (
+ {
+ "context": retriever | RunnableLambda(_format_docs),
+ "question": RunnablePassthrough(),
+ }
+ | prompt
+ | model
+ | StrOutputParser()
+ )
+
+
+def _format_docs(docs) -> str:
+ return "\n\n".join(f"{doc.metadata.get('openviking_uri')}\n{doc.page_content}" for doc in docs)
+
+
+def main() -> str:
+ app = build_app()
+ answer = app.invoke("Which deployment color should the LangChain example use?")
+ print(answer)
+ return answer
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/langchain-langgraph/langgraph/agent/live_app.py b/examples/langchain-langgraph/langgraph/agent/live_app.py
new file mode 100644
index 000000000..d95ffba60
--- /dev/null
+++ b/examples/langchain-langgraph/langgraph/agent/live_app.py
@@ -0,0 +1,212 @@
+"""Live LangGraph app using OpenViking middleware and an OpenAI-compatible LLM.
+
+Required:
+ ARK_API_KEY
+
+Optional:
+ ARK_BASE_URL, ARK_MODEL
+ OPENVIKING_URL, OPENVIKING_API_KEY, OPENVIKING_LIVE_COMMIT_TIMEOUT
+"""
+
+from __future__ import annotations
+
+import os
+import time
+import uuid
+from typing import Any
+
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
+from langgraph.graph import END, START, StateGraph
+from langgraph.graph.message import add_messages
+from openai import OpenAI
+from typing_extensions import Annotated, TypedDict
+
+from openviking.integrations.langchain import OpenVikingContextMiddleware
+from openviking.integrations.langchain.client import extract_message_text
+
+
+class LiveState(TypedDict, total=False):
+ messages: Annotated[list, add_messages]
+
+
+def build_context_client():
+ from openviking.client import SyncHTTPClient
+
+ client = SyncHTTPClient(
+ url=os.environ.get("OPENVIKING_URL") or None,
+ api_key=os.environ.get("OPENVIKING_API_KEY"),
+ user_id=os.environ.get("OPENVIKING_USER_ID"),
+ agent_id=os.environ.get("OPENVIKING_AGENT_ID"),
+ )
+ client.initialize()
+ return client
+
+
+def seed_context(client, session_id: str, code: str) -> None:
+ client.create_session(session_id=session_id)
+ client.add_message(
+ session_id=session_id,
+ role="user",
+ parts=[
+ {
+ "type": "text",
+ "text": (
+ f"Remember this OpenViking LangGraph live e2e exact code: {code}. "
+ "This is durable session context for the next agent turn."
+ ),
+ }
+ ],
+ )
+ client.add_message(
+ session_id=session_id,
+ role="assistant",
+ parts=[
+ {
+ "type": "text",
+ "text": f"Stored the OpenViking LangGraph live e2e exact code: {code}.",
+ }
+ ],
+ )
+
+
+def build_app(*, client: Any, session_id: str):
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ token_budget=8_000,
+ commit_on_after_agent=False,
+ include_active_messages=True,
+ )
+
+ class Runtime:
+ config = {"configurable": {"thread_id": session_id}}
+
+ def model_node(state: LiveState) -> LiveState:
+ current_messages = list(state["messages"])
+
+ class Request:
+ state = {}
+ runtime = Runtime()
+ messages = current_messages
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get(
+ "system_message",
+ self.system_message,
+ )
+ return new_request
+
+ def handler(request):
+ messages: list[BaseMessage] = []
+ if request.system_message is not None:
+ messages.append(request.system_message)
+ messages.extend(request.messages)
+ answer = call_llm(messages)
+ return AIMessage(content=answer)
+
+ response = middleware.wrap_model_call(Request(), handler)
+ middleware.after_agent(
+ {
+ "messages": current_messages + [response],
+ },
+ Runtime(),
+ )
+ return {"messages": [response]}
+
+ graph = StateGraph(LiveState)
+ graph.add_node("model", model_node)
+ graph.add_edge(START, "model")
+ graph.add_edge("model", END)
+ return graph.compile()
+
+
+def call_llm(messages: list[BaseMessage]) -> str:
+ openai_messages = [
+ {
+ "role": "system",
+ "content": (
+ "You are validating OpenViking as LangGraph middleware. "
+ "Return only the exact lg_live_* code if one appears in the context "
+ "or conversation."
+ ),
+ }
+ ]
+ for message in messages:
+ content = extract_message_text(message.content)
+ if isinstance(message, SystemMessage):
+ openai_messages.append({"role": "system", "content": content})
+ elif isinstance(message, HumanMessage):
+ openai_messages.append({"role": "user", "content": content})
+ elif isinstance(message, AIMessage):
+ openai_messages.append({"role": "assistant", "content": content})
+
+ llm = OpenAI(
+ api_key=os.environ["ARK_API_KEY"],
+ base_url=os.environ.get("ARK_BASE_URL", "https://ark-cn-beijing.bytedance.net/api/v3"),
+ )
+ completion = llm.chat.completions.create(
+ model=os.environ.get("ARK_MODEL", "doubao-seed-2-0-code-preview-260215"),
+ messages=openai_messages,
+ )
+ return completion.choices[0].message.content or ""
+
+
+def main() -> str:
+ if not os.environ.get("ARK_API_KEY"):
+ raise RuntimeError("ARK_API_KEY is required for the live app.")
+
+ client = build_context_client()
+ session_id = f"langgraph-live-demo-{uuid.uuid4().hex}"
+ code = f"lg_live_{uuid.uuid4().hex[:10]}"
+ seed_context(client, session_id, code)
+ try:
+ app = build_app(client=client, session_id=session_id)
+ result = app.invoke(
+ {
+ "messages": [
+ HumanMessage(
+ content=(
+ "What is the OpenViking LangGraph live e2e exact code? "
+ "Answer only the exact code."
+ )
+ )
+ ]
+ }
+ )
+ answer = result["messages"][-1].content
+ print(answer)
+ if code not in answer.lower():
+ raise RuntimeError(f"Expected {code!r} in live answer: {answer!r}")
+ commit = client.commit_session(session_id)
+ wait_for_commit_task(client, commit)
+ return answer
+ finally:
+ try:
+ client.delete_session(session_id)
+ except Exception:
+ pass
+
+
+def wait_for_commit_task(client, commit: dict[str, object]) -> None:
+ if commit.get("archived") is not True or not commit.get("task_id"):
+ raise RuntimeError(f"OpenViking commit did not start extraction: {commit}")
+ timeout = float(os.environ.get("OPENVIKING_LIVE_COMMIT_TIMEOUT", "180"))
+ deadline = time.monotonic() + timeout
+ last_task = None
+ while time.monotonic() < deadline:
+ task = client.get_task(str(commit["task_id"]))
+ last_task = task
+ if task and task.get("status") == "completed":
+ return
+ if task and task.get("status") == "failed":
+ raise RuntimeError(f"OpenViking commit task failed: {task}")
+ time.sleep(0.5)
+ raise RuntimeError(
+ f"OpenViking commit task did not complete: {commit['task_id']}; last_task={last_task}"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/langchain-langgraph/langgraph/agent/quick_app.py b/examples/langchain-langgraph/langgraph/agent/quick_app.py
new file mode 100644
index 000000000..3384c34ae
--- /dev/null
+++ b/examples/langchain-langgraph/langgraph/agent/quick_app.py
@@ -0,0 +1,91 @@
+"""Deterministic LangGraph smoke app using OpenViking tools and store."""
+
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+from langchain_core.messages import AIMessage, HumanMessage
+from langgraph.graph import END, START, StateGraph
+from langgraph.graph.message import add_messages
+from typing_extensions import Annotated, TypedDict
+
+from openviking.integrations.langchain import (
+ InMemoryOpenVikingClient,
+ OpenVikingStore,
+ create_openviking_tools,
+)
+
+
+class AgentState(TypedDict, total=False):
+ messages: Annotated[list, add_messages]
+ openviking_context: str
+
+
+def build_app(client: InMemoryOpenVikingClient | None = None):
+ client = client or InMemoryOpenVikingClient(
+ {
+ "viking://user/memories/profile.md": (
+ "The user wants LangGraph agents to use OpenViking for durable context."
+ ),
+ "viking://resources/runbooks/langgraph.md": (
+ "LangGraph workflows can call OpenViking tools before model nodes."
+ ),
+ }
+ )
+ store = OpenVikingStore(client=client)
+ store.put(
+ ("demo", "user"),
+ "deployment",
+ {"color": "azure", "framework": "langgraph"},
+ )
+ find_tool = next(
+ tool
+ for tool in create_openviking_tools(client=client, profile="retrieval")
+ if tool.name == "viking_find"
+ )
+ model = FakeListChatModel(
+ responses=[
+ "The LangGraph workflow should use OpenViking context and azure deployment color.",
+ ]
+ )
+
+ def recall(state: AgentState) -> AgentState:
+ latest = state["messages"][-1].content
+ context = find_tool.invoke({"query": latest, "limit": 4})
+ stored = store.search(("demo",), query="azure", limit=1)
+ if stored:
+ context += f"\n\nStore: {stored[0].value}"
+ return {"openviking_context": context}
+
+ def answer(state: AgentState) -> AgentState:
+ latest = state["messages"][-1].content
+ response = model.invoke(
+ [
+ HumanMessage(
+ content=(
+ "OpenViking context:\n"
+ f"{state.get('openviking_context', '')}\n\nQuestion: {latest}"
+ )
+ )
+ ]
+ )
+ return {"messages": [AIMessage(content=response.content)]}
+
+ graph = StateGraph(AgentState)
+ graph.add_node("recall", recall)
+ graph.add_node("answer", answer)
+ graph.add_edge(START, "recall")
+ graph.add_edge("recall", "answer")
+ graph.add_edge("answer", END)
+ return graph.compile()
+
+
+def main() -> str:
+ app = build_app()
+ result = app.invoke(
+ {"messages": [HumanMessage(content="How should LangGraph use OpenViking?")]}
+ )
+ answer = result["messages"][-1].content
+ print(answer)
+ return answer
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/langchain-langgraph/langgraph/middleware/quick_app.py b/examples/langchain-langgraph/langgraph/middleware/quick_app.py
new file mode 100644
index 000000000..d12b3f134
--- /dev/null
+++ b/examples/langchain-langgraph/langgraph/middleware/quick_app.py
@@ -0,0 +1,93 @@
+"""Deterministic LangGraph app using OpenViking context middleware."""
+
+from typing import Any
+
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
+from langgraph.graph import END, START, StateGraph
+from langgraph.graph.message import add_messages
+from typing_extensions import Annotated, TypedDict
+
+from openviking.integrations.langchain import (
+ InMemoryOpenVikingClient,
+ OpenVikingContextMiddleware,
+)
+from openviking.integrations.langchain.client import extract_message_text
+
+
+class AgentState(TypedDict, total=False):
+ messages: Annotated[list, add_messages]
+
+
+def build_app(client: InMemoryOpenVikingClient | None = None):
+ client = client or InMemoryOpenVikingClient(
+ {
+ "viking://user/memories/profile.md": (
+ "OpenViking middleware examples should answer with azure."
+ )
+ }
+ )
+ session_id = "langgraph-middleware-demo"
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ target_uri="viking://user/memories",
+ session_id_resolver=lambda _state, _runtime: session_id,
+ include_active_messages=True,
+ )
+
+ class Runtime:
+ config = {"configurable": {"thread_id": session_id}}
+
+ def model_node(state: AgentState) -> AgentState:
+ current_messages = list(state["messages"])
+
+ class Request:
+ state: dict[str, Any] = {}
+ runtime = Runtime()
+ messages: list[BaseMessage] = current_messages
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get(
+ "system_message",
+ self.system_message,
+ )
+ return new_request
+
+ def handler(request):
+ context = (
+ extract_message_text(request.system_message.content)
+ if request.system_message
+ else ""
+ )
+ if "azure" in context.lower():
+ return AIMessage(content="OpenViking middleware context says azure.")
+ return AIMessage(content="OpenViking middleware context was missing.")
+
+ response = middleware.wrap_model_call(Request(), handler)
+ middleware.after_agent(
+ {"messages": current_messages + [response]},
+ Runtime(),
+ )
+ return {"messages": [response]}
+
+ graph = StateGraph(AgentState)
+ graph.add_node("model", model_node)
+ graph.add_edge(START, "model")
+ graph.add_edge("model", END)
+ return graph.compile()
+
+
+def main() -> str:
+ app = build_app()
+ result = app.invoke(
+ {"messages": [HumanMessage(content="What should this middleware example use?")]}
+ )
+ answer = result["messages"][-1].content
+ print(answer)
+ return answer
+
+
+if __name__ == "__main__":
+ main()
diff --git a/openviking/integrations/__init__.py b/openviking/integrations/__init__.py
new file mode 100644
index 000000000..857da4c89
--- /dev/null
+++ b/openviking/integrations/__init__.py
@@ -0,0 +1,3 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Optional framework integrations for OpenViking."""
diff --git a/openviking/integrations/langchain/__init__.py b/openviking/integrations/langchain/__init__.py
new file mode 100644
index 000000000..d33e6ce67
--- /dev/null
+++ b/openviking/integrations/langchain/__init__.py
@@ -0,0 +1,63 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LangChain and LangGraph integrations for OpenViking.
+
+The objects in this package depend on optional framework packages. Importing
+``openviking`` itself does not install or import LangChain/LangGraph.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+__all__ = [
+ "InMemoryOpenVikingClient",
+ "OpenVikingChatMessageHistory",
+ "OpenVikingCommitPolicy",
+ "OpenVikingContextMiddleware",
+ "OpenVikingRetriever",
+ "OpenVikingSessionContextAssembler",
+ "OpenVikingStore",
+ "create_openviking_tools",
+ "with_openviking_context",
+]
+
+
+def __getattr__(name: str) -> Any:
+ if name == "OpenVikingRetriever":
+ from openviking.integrations.langchain.retrievers import OpenVikingRetriever
+
+ return OpenVikingRetriever
+ if name == "create_openviking_tools":
+ from openviking.integrations.langchain.tools import create_openviking_tools
+
+ return create_openviking_tools
+ if name == "OpenVikingStore":
+ from openviking.integrations.langchain.store import OpenVikingStore
+
+ return OpenVikingStore
+ if name == "OpenVikingChatMessageHistory":
+ from openviking.integrations.langchain.history import OpenVikingChatMessageHistory
+
+ return OpenVikingChatMessageHistory
+ if name == "OpenVikingSessionContextAssembler":
+ from openviking.integrations.langchain.context import OpenVikingSessionContextAssembler
+
+ return OpenVikingSessionContextAssembler
+ if name == "OpenVikingCommitPolicy":
+ from openviking.integrations.langchain.client import OpenVikingCommitPolicy
+
+ return OpenVikingCommitPolicy
+ if name == "with_openviking_context":
+ from openviking.integrations.langchain.context import with_openviking_context
+
+ return with_openviking_context
+ if name == "OpenVikingContextMiddleware":
+ from openviking.integrations.langchain.middleware import OpenVikingContextMiddleware
+
+ return OpenVikingContextMiddleware
+ if name == "InMemoryOpenVikingClient":
+ from openviking.integrations.langchain.testing import InMemoryOpenVikingClient
+
+ return InMemoryOpenVikingClient
+ raise AttributeError(name)
diff --git a/openviking/integrations/langchain/client.py b/openviking/integrations/langchain/client.py
new file mode 100644
index 000000000..b4676ca17
--- /dev/null
+++ b/openviking/integrations/langchain/client.py
@@ -0,0 +1,227 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Shared helpers for LangChain/LangGraph integration adapters."""
+
+from __future__ import annotations
+
+import inspect
+import json
+import logging
+from dataclasses import dataclass
+from typing import Any, Iterable, Literal
+
+logger = logging.getLogger(__name__)
+
+
+class OptionalDependencyError(ImportError):
+ """Raised when an optional framework dependency is not installed."""
+
+
+def missing_dependency(extra: str, package: str | None = None) -> OptionalDependencyError:
+ package = package or extra
+ return OptionalDependencyError(
+ f"{package} is required for this OpenViking integration. "
+ f'Install it with `pip install "openviking[{extra}]"`.'
+ )
+
+
+@dataclass(slots=True)
+class OpenVikingConnection:
+ """Connection settings for lazily creating an OpenViking client."""
+
+ client: Any = None
+ url: str | None = None
+ api_key: str | None = None
+ account: str | None = None
+ user: str | None = None
+ user_id: str | None = None
+ agent_id: str | None = None
+ path: str | None = None
+ timeout: float = 60.0
+ extra_headers: dict[str, str] | None = None
+ auto_initialize: bool = True
+
+
+@dataclass(slots=True)
+class OpenVikingCommitPolicy:
+ """Commit behavior for OpenViking-backed agent sessions."""
+
+ mode: Literal["never", "always", "pending_tokens"] = "never"
+ pending_token_threshold: int = 8_000
+
+
+def ensure_client(connection: OpenVikingConnection) -> Any:
+ """Return an initialized OpenViking client from explicit or connection settings."""
+
+ client = connection.client
+ if client is None:
+ if connection.url or connection.path is None:
+ from openviking.client import SyncHTTPClient
+
+ client = SyncHTTPClient(
+ url=connection.url,
+ api_key=connection.api_key,
+ account=connection.account,
+ user=connection.user,
+ user_id=connection.user_id,
+ agent_id=connection.agent_id,
+ timeout=connection.timeout,
+ extra_headers=connection.extra_headers,
+ )
+ else:
+ from openviking.sync_client import SyncOpenViking
+
+ client = SyncOpenViking(path=connection.path)
+
+ if connection.auto_initialize and hasattr(client, "initialize"):
+ if not getattr(client, "_initialized", False):
+ client.initialize()
+ return client
+
+
+def maybe_commit_session(
+ client: Any,
+ session_id: str,
+ policy: OpenVikingCommitPolicy | None,
+) -> dict[str, Any] | None:
+ """Commit a session if the configured policy says the live tail is ready."""
+
+ if policy is None or policy.mode == "never":
+ return None
+ if policy.mode == "always":
+ return call_openviking(
+ client,
+ "commit_session",
+ session_id=session_id,
+ )
+ if policy.mode != "pending_tokens":
+ raise ValueError(f"Unsupported OpenViking commit policy: {policy.mode}")
+
+ try:
+ session = call_openviking(client, "get_session", session_id=session_id, auto_create=False)
+ except Exception:
+ logger.debug(
+ "Skipping OpenViking pending-token commit because session lookup failed",
+ exc_info=True,
+ )
+ return None
+ pending_tokens = int(item_value(session, "pending_tokens", 0) or 0)
+ if pending_tokens < policy.pending_token_threshold:
+ return None
+ return call_openviking(
+ client,
+ "commit_session",
+ session_id=session_id,
+ )
+
+
+def call_openviking(client: Any, method_name: str, /, **kwargs: Any) -> Any:
+ """Call a client method, filtering kwargs unsupported by local/HTTP variants."""
+
+ method = getattr(client, method_name)
+ try:
+ signature = inspect.signature(method)
+ except (TypeError, ValueError):
+ return method(**{key: value for key, value in kwargs.items() if value is not None})
+
+ accepts_kwargs = any(
+ parameter.kind == inspect.Parameter.VAR_KEYWORD
+ for parameter in signature.parameters.values()
+ )
+ if accepts_kwargs:
+ filtered = {key: value for key, value in kwargs.items() if value is not None}
+ else:
+ filtered = {
+ key: value
+ for key, value in kwargs.items()
+ if value is not None and key in signature.parameters
+ }
+ return method(**filtered)
+
+
+def result_groups(result: Any) -> list[tuple[str, list[Any]]]:
+ """Normalize OpenViking retrieval results into named context groups."""
+
+ if result is None:
+ return []
+ if isinstance(result, dict):
+ return [
+ ("memory", list(result.get("memories") or [])),
+ ("resource", list(result.get("resources") or [])),
+ ("skill", list(result.get("skills") or [])),
+ ]
+ return [
+ ("memory", list(getattr(result, "memories", []) or [])),
+ ("resource", list(getattr(result, "resources", []) or [])),
+ ("skill", list(getattr(result, "skills", []) or [])),
+ ]
+
+
+def item_value(item: Any, key: str, default: Any = None) -> Any:
+ if isinstance(item, dict):
+ return item.get(key, default)
+ return getattr(item, key, default)
+
+
+def iter_result_items(
+ result: Any,
+ context_types: Iterable[str] = ("memory", "resource", "skill"),
+) -> Iterable[tuple[str, Any]]:
+ allowed = set(context_types)
+ for context_type, items in result_groups(result):
+ if context_type not in allowed:
+ continue
+ for item in items:
+ yield context_type, item
+
+
+def compact_json(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, default=str, separators=(",", ":"))
+
+
+def stringify(value: Any, *, max_chars: int = 12_000) -> str:
+ if value is None:
+ text = ""
+ elif isinstance(value, str):
+ text = value
+ else:
+ text = json.dumps(value, ensure_ascii=False, default=str, indent=2)
+ if max_chars > 0 and len(text) > max_chars:
+ return text[:max_chars] + "\n...[truncated]"
+ return text
+
+
+def extract_message_text(content: Any) -> str:
+ """Extract text from LangChain/OpenAI-style message content."""
+
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ chunks: list[str] = []
+ for block in content:
+ if isinstance(block, str):
+ chunks.append(block)
+ elif isinstance(block, dict):
+ if block.get("type") == "text" and isinstance(block.get("text"), str):
+ chunks.append(block["text"])
+ elif isinstance(block.get("content"), str):
+ chunks.append(block["content"])
+ return "\n".join(chunk for chunk in chunks if chunk)
+ if content is None:
+ return ""
+ return str(content)
+
+
+def get_latest_user_text(messages: Iterable[Any]) -> str:
+ for message in reversed(list(messages)):
+ role = getattr(message, "type", None) or getattr(message, "role", None)
+ if isinstance(message, dict):
+ role = message.get("type") or message.get("role")
+ content = message.get("content")
+ else:
+ content = getattr(message, "content", "")
+ if role in {"human", "user"}:
+ text = extract_message_text(content).strip()
+ if text:
+ return text
+ return ""
diff --git a/openviking/integrations/langchain/context.py b/openviking/integrations/langchain/context.py
new file mode 100644
index 000000000..645b17f57
--- /dev/null
+++ b/openviking/integrations/langchain/context.py
@@ -0,0 +1,426 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""High-level OpenViking context lifecycle helpers for LangChain."""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from typing import Any, Sequence
+
+try:
+ from langchain_core.messages import SystemMessage
+ from langchain_core.runnables import ConfigurableFieldSpec, RunnableLambda
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+except ImportError as exc: # pragma: no cover - exercised by optional import path
+ from openviking.integrations.langchain.client import missing_dependency
+
+ raise missing_dependency("langchain", "langchain-core") from exc
+
+from openviking.integrations.langchain.client import (
+ OpenVikingCommitPolicy,
+ OpenVikingConnection,
+ call_openviking,
+ ensure_client,
+ extract_message_text,
+ get_latest_user_text,
+)
+from openviking.integrations.langchain.history import (
+ OpenVikingChatMessageHistory,
+ context_parts_from_documents,
+)
+from openviking.integrations.langchain.retrievers import OpenVikingRetriever
+
+OPENVIKING_CONTEXT_MARKER = "<openviking_context>"
+logger = logging.getLogger(__name__)
+
+
+@dataclass(slots=True)
+class OpenVikingAssembledContext:
+ """Context block plus structured references assembled before an agent turn."""
+
+ block: str = ""
+ context_parts: list[dict[str, Any]] = field(default_factory=list)
+ session_context: dict[str, Any] = field(default_factory=dict)
+ recall_documents: list[Any] = field(default_factory=list)
+
+
+class OpenVikingSessionContextAssembler:
+ """Assemble session working memory, archive context, and recall results."""
+
+ def __init__(
+ self,
+ *,
+ client: Any = None,
+ retriever: OpenVikingRetriever | None = None,
+ url: str | None = None,
+ api_key: str | None = None,
+ account: str | None = None,
+ user: str | None = None,
+ user_id: str | None = None,
+ agent_id: str | None = None,
+ path: str | None = None,
+ timeout: float = 60.0,
+ extra_headers: dict[str, str] | None = None,
+ auto_initialize: bool = True,
+ target_uri: str | list[str] = "",
+ limit: int = 5,
+ score_threshold: float | None = None,
+ token_budget: int = 128_000,
+ include_session_context: bool = True,
+ include_active_messages: bool = True,
+ include_recall: bool = True,
+ recall_header: str = "Relevant OpenViking context:",
+ ):
+ self._connection = OpenVikingConnection(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ auto_initialize=auto_initialize,
+ )
+ self.retriever = retriever or OpenVikingRetriever(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ auto_initialize=auto_initialize,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=score_threshold,
+ search_mode="search",
+ )
+ self.token_budget = token_budget
+ self.include_session_context = include_session_context
+ self.include_active_messages = include_active_messages
+ self.include_recall = include_recall
+ self.recall_header = recall_header
+ self._client_cache: Any = None
+
+ def assemble(self, *, session_id: str, query: str = "") -> OpenVikingAssembledContext:
+ client = self._get_client()
+ self._ensure_session(client, session_id)
+ session_context = self._get_session_context(client, session_id)
+ recall_documents = self._get_recall_documents(session_id, query)
+ block = self._format_context_block(session_context, recall_documents)
+ return OpenVikingAssembledContext(
+ block=block,
+ context_parts=context_parts_from_documents(recall_documents),
+ session_context=session_context,
+ recall_documents=recall_documents,
+ )
+
+ def _get_client(self) -> Any:
+ if self._client_cache is None:
+ self._client_cache = ensure_client(self._connection)
+ return self._client_cache
+
+ def _ensure_session(self, client: Any, session_id: str) -> None:
+ try:
+ call_openviking(client, "create_session", session_id=session_id)
+ except Exception:
+ logger.debug("OpenViking session ensure failed", exc_info=True)
+ pass
+
+ def _get_session_context(self, client: Any, session_id: str) -> dict[str, Any]:
+ if not self.include_session_context:
+ return {}
+ try:
+ return call_openviking(
+ client,
+ "get_session_context",
+ session_id=session_id,
+ token_budget=self.token_budget,
+ )
+ except Exception:
+ logger.debug("OpenViking session context assembly failed", exc_info=True)
+ return {}
+
+ def _get_recall_documents(self, session_id: str, query: str) -> list[Any]:
+ if not self.include_recall or not query:
+ return []
+ try:
+ return list(_retriever_for_session(self.retriever, session_id).invoke(query))
+ except Exception:
+ logger.debug("OpenViking recall retrieval failed", exc_info=True)
+ return []
+
+ def _format_context_block(
+ self,
+ session_context: dict[str, Any],
+ recall_documents: Sequence[Any],
+ ) -> str:
+ sections: list[str] = []
+ latest_archive = str(session_context.get("latest_archive_overview") or "").strip()
+ if latest_archive:
+ sections.append("Session archive overview:\n" + latest_archive)
+
+ abstracts = []
+ for archive in session_context.get("pre_archive_abstracts") or []:
+ archive_id = archive.get("archive_id") or "archive"
+ abstract = str(archive.get("abstract") or "").strip()
+ if abstract:
+ abstracts.append(f"[{archive_id}] {abstract}")
+ if abstracts:
+ sections.append("Older archive abstracts:\n" + "\n".join(abstracts))
+
+ if self.include_active_messages:
+ active_messages = [
+ _format_session_message(message)
+ for message in session_context.get("messages") or []
+ ]
+ active_messages = [message for message in active_messages if message]
+ if active_messages:
+ sections.append("Active session messages:\n" + "\n".join(active_messages))
+
+ if recall_documents:
+ recall_lines = []
+ for index, doc in enumerate(recall_documents, start=1):
+ metadata = getattr(doc, "metadata", {}) or {}
+ uri = metadata.get("openviking_uri") or metadata.get("source") or ""
+ recall_lines.append(f"[{index}] {uri}\n{doc.page_content}".strip())
+ sections.append(self.recall_header + "\n\n" + "\n\n".join(recall_lines))
+
+ if not sections:
+ return ""
+ return f"{OPENVIKING_CONTEXT_MARKER}\n" + "\n\n".join(sections) + "\n</openviking_context>"
+
+
+def with_openviking_context(
+ runnable: Any,
+ *,
+ client: Any = None,
+ url: str | None = None,
+ api_key: str | None = None,
+ account: str | None = None,
+ user: str | None = None,
+ user_id: str | None = None,
+ agent_id: str | None = None,
+ path: str | None = None,
+ timeout: float = 60.0,
+ extra_headers: dict[str, str] | None = None,
+ auto_initialize: bool = True,
+ session_id: str | None = None,
+ target_uri: str | list[str] = "",
+ limit: int = 5,
+ score_threshold: float | None = None,
+ token_budget: int = 128_000,
+ input_messages_key: str | None = None,
+ output_messages_key: str | None = None,
+ history_messages_key: str | None = None,
+ commit_policy: OpenVikingCommitPolicy | None = None,
+ session_id_config_key: str = "session_id",
+ inject_context: bool = True,
+) -> RunnableWithMessageHistory:
+ """Wrap a LangChain runnable with OpenViking context and message history."""
+
+ assembler = OpenVikingSessionContextAssembler(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ auto_initialize=auto_initialize,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=score_threshold,
+ token_budget=token_budget,
+ include_active_messages=False,
+ include_recall=inject_context,
+ )
+ pending_context_parts: dict[str, list[dict[str, Any]]] = {}
+
+ def make_history(active_session_id: str) -> OpenVikingChatMessageHistory:
+ return OpenVikingChatMessageHistory(
+ session_id=active_session_id,
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ auto_initialize=auto_initialize,
+ token_budget=token_budget,
+ commit_policy=commit_policy,
+ context_parts_provider=lambda current_session_id: pending_context_parts.pop(
+ current_session_id,
+ [],
+ ),
+ )
+
+ if session_id is None:
+
+ def session_history_factory(resolved_session_id: str) -> OpenVikingChatMessageHistory:
+ return make_history(
+ _validate_session_id(resolved_session_id, key=session_id_config_key)
+ )
+
+ history_factory_config = [
+ ConfigurableFieldSpec(
+ id=session_id_config_key,
+ annotation=str,
+ name="Session ID",
+ description=("Required OpenViking session ID for dynamic chat history and recall."),
+ default="",
+ is_shared=True,
+ )
+ ]
+ else:
+
+ def session_history_factory() -> OpenVikingChatMessageHistory:
+ return make_history(session_id)
+
+ history_factory_config = None
+
+ def inject(input_value: Any, config: dict[str, Any] | None = None) -> Any:
+ if not inject_context:
+ return input_value
+ resolved_session_id = session_id or _session_id_from_config(
+ config,
+ key=session_id_config_key,
+ )
+ pending_context_parts.pop(resolved_session_id, None)
+ query = _latest_user_text_from_input(input_value, input_messages_key)
+ assembled = assembler.assemble(session_id=resolved_session_id, query=query)
+ if not assembled.block:
+ return input_value
+ if assembled.context_parts:
+ pending_context_parts[resolved_session_id] = assembled.context_parts
+ return _inject_system_context(input_value, assembled.block, input_messages_key)
+
+ def clear_pending_on_error(_run: Any, config: dict[str, Any] | None = None) -> None:
+ del config
+ if session_id is not None:
+ pending_context_parts.pop(session_id, None)
+ else:
+ pending_context_parts.clear()
+
+ bound = (RunnableLambda(inject) | runnable).with_listeners(on_error=clear_pending_on_error)
+ return RunnableWithMessageHistory(
+ bound,
+ session_history_factory,
+ input_messages_key=input_messages_key,
+ output_messages_key=output_messages_key,
+ history_messages_key=history_messages_key,
+ history_factory_config=history_factory_config,
+ )
+
+
+def _session_id_from_config(config: dict[str, Any] | None, *, key: str) -> str:
+ configurable = (config or {}).get("configurable") or {}
+ return _validate_session_id(configurable.get(key), key=key)
+
+
+def _validate_session_id(value: Any, *, key: str) -> str:
+ session_id = str(value or "").strip()
+ if not session_id:
+ raise ValueError(
+ "OpenViking dynamic sessions require "
+ f"config={{'configurable': {{'{key}': '<session-id>'}}}}. "
+ "Pass session_id='...' to with_openviking_context for no-config usage."
+ )
+ return session_id
+
+
+def _retriever_for_session(retriever: Any, session_id: str) -> Any:
+ if hasattr(retriever, "model_copy"):
+ return retriever.model_copy(
+ update={
+ "session_id": session_id,
+ "search_mode": "search",
+ }
+ )
+ return retriever
+
+
+def _latest_user_text_from_input(input_value: Any, input_messages_key: str | None) -> str:
+ messages = _input_messages(input_value, input_messages_key)
+ if messages:
+ return get_latest_user_text(messages)
+ if isinstance(input_value, str):
+ return input_value
+ if isinstance(input_value, dict):
+ for value in input_value.values():
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+
+def _input_messages(input_value: Any, input_messages_key: str | None) -> list[Any]:
+ if isinstance(input_value, list):
+ return list(input_value)
+ if isinstance(input_value, dict):
+ key = input_messages_key or "messages"
+ value = input_value.get(key)
+ if isinstance(value, list):
+ return list(value)
+ return []
+
+
+def _inject_system_context(
+ input_value: Any,
+ context_block: str,
+ input_messages_key: str | None,
+) -> Any:
+ if isinstance(input_value, list):
+ return _merge_system_message(input_value, context_block)
+ if isinstance(input_value, dict):
+ key = input_messages_key or "messages"
+ if isinstance(input_value.get(key), list):
+ updated = dict(input_value)
+ updated[key] = _merge_system_message(input_value[key], context_block)
+ return updated
+ updated = dict(input_value)
+ updated["openviking_context"] = context_block
+ return updated
+ return input_value
+
+
+def _merge_system_message(messages: Sequence[Any], context_block: str) -> list[Any]:
+ updated = list(messages)
+ for index, message in enumerate(updated):
+ if isinstance(message, SystemMessage):
+ content = extract_message_text(message.content)
+ updated[index] = SystemMessage(content=f"{content}\n\n{context_block}".strip())
+ return updated
+ return [SystemMessage(content=context_block), *updated]
+
+
+def _format_session_message(message: dict[str, Any]) -> str:
+ role = str(message.get("role") or "assistant")
+ parts = message.get("parts") or []
+ chunks: list[str] = []
+ for part in parts:
+ part_type = part.get("type")
+ if part_type == "text" and part.get("text"):
+ chunks.append(str(part["text"]))
+ elif part_type == "context" and part.get("abstract"):
+ chunks.append(f"[context] {part['abstract']}")
+ elif part_type == "tool":
+ tool_name = part.get("tool_name") or "tool"
+ status = part.get("tool_status") or "completed"
+ output = part.get("tool_output") or ""
+ chunks.append(f"[tool:{tool_name} ({status})] {output}".strip())
+ text = "\n".join(chunk for chunk in chunks if chunk).strip()
+ return f"[{role}] {text}" if text else ""
diff --git a/openviking/integrations/langchain/history.py b/openviking/integrations/langchain/history.py
new file mode 100644
index 000000000..d9339515a
--- /dev/null
+++ b/openviking/integrations/langchain/history.py
@@ -0,0 +1,311 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LangChain chat history backed by OpenViking sessions."""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from typing import Any, Callable
+
+try:
+ from langchain_core.chat_history import BaseChatMessageHistory
+ from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+ )
+except ImportError as exc: # pragma: no cover - exercised by optional import path
+ from openviking.integrations.langchain.client import missing_dependency
+
+ raise missing_dependency("langchain", "langchain-core") from exc
+
+from openviking.integrations.langchain.client import (
+ OpenVikingCommitPolicy,
+ OpenVikingConnection,
+ call_openviking,
+ ensure_client,
+ extract_message_text,
+ maybe_commit_session,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class OpenVikingChatMessageHistory(BaseChatMessageHistory):
+ """LangChain chat history implementation stored in an OpenViking session."""
+
+ def __init__(
+ self,
+ session_id: str,
+ *,
+ client: Any = None,
+ url: str | None = None,
+ api_key: str | None = None,
+ account: str | None = None,
+ user: str | None = None,
+ user_id: str | None = None,
+ agent_id: str | None = None,
+ path: str | None = None,
+ timeout: float = 60.0,
+ extra_headers: dict[str, str] | None = None,
+ auto_initialize: bool = True,
+ token_budget: int = 128_000,
+ persist_system_messages: bool = False,
+ commit_policy: OpenVikingCommitPolicy | None = None,
+ context_parts_provider: Callable[[str], list[dict[str, Any]]] | None = None,
+ ):
+ self.session_id = session_id
+ self.token_budget = token_budget
+ # Retained for constructor compatibility. System messages are runtime
+ # policy, not conversation memory, so they are never persisted.
+ self.persist_system_messages = False
+ self.commit_policy = commit_policy
+ self.context_parts_provider = context_parts_provider
+ self._connection = OpenVikingConnection(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ auto_initialize=auto_initialize,
+ )
+ self._client_cache: Any = None
+
+ @property
+ def messages(self) -> list[BaseMessage]:
+ client = self._get_client()
+ try:
+ context = call_openviking(
+ client,
+ "get_session_context",
+ session_id=self.session_id,
+ token_budget=self.token_budget,
+ )
+ except Exception:
+ logger.debug("OpenViking chat history context fetch failed", exc_info=True)
+ self._ensure_session(client)
+ return []
+
+ return _restore_openviking_messages(context.get("messages") or [])
+
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
+ client = self._get_client()
+ added = 0
+ pending_context_parts = (
+ list(self.context_parts_provider(self.session_id))
+ if self.context_parts_provider
+ else []
+ )
+ for message in messages:
+ for payload in langchain_message_to_openviking(
+ message,
+ persist_system_messages=self.persist_system_messages,
+ ):
+ if pending_context_parts and payload["role"] == "assistant":
+ payload["parts"].extend(pending_context_parts)
+ pending_context_parts = []
+ call_openviking(
+ client,
+ "add_message",
+ session_id=self.session_id,
+ role=payload["role"],
+ parts=payload["parts"],
+ )
+ added += 1
+ if added:
+ maybe_commit_session(client, self.session_id, self.commit_policy)
+
+ def clear(self) -> None:
+ client = self._get_client()
+ call_openviking(client, "delete_session", session_id=self.session_id)
+ self._ensure_session(client)
+
+ def _get_client(self) -> Any:
+ if self._client_cache is None:
+ self._client_cache = ensure_client(self._connection)
+ return self._client_cache
+
+ def _ensure_session(self, client: Any) -> None:
+ try:
+ call_openviking(client, "create_session", session_id=self.session_id)
+ except Exception:
+ logger.debug("OpenViking chat history session ensure failed", exc_info=True)
+ pass
+
+
+def langchain_message_to_openviking(
+ message: BaseMessage,
+ *,
+ persist_system_messages: bool = False,
+) -> list[dict[str, Any]]:
+ """Convert a LangChain message into one or more OpenViking add_message payloads."""
+
+ if isinstance(message, HumanMessage):
+ parts = _text_parts(message.content)
+ return [{"role": "user", "parts": parts or [{"type": "text", "text": ""}]}]
+
+ if isinstance(message, AIMessage):
+ parts = _text_parts(message.content)
+ for tool_call in message.tool_calls or []:
+ parts.append(
+ {
+ "type": "tool",
+ "tool_id": str(tool_call.get("id") or ""),
+ "tool_name": str(tool_call.get("name") or ""),
+ "tool_input": _tool_args(tool_call.get("args")),
+ "tool_status": "pending",
+ }
+ )
+ return [{"role": "assistant", "parts": parts or [{"type": "text", "text": ""}]}]
+
+ if isinstance(message, ToolMessage):
+ return [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "tool",
+ "tool_id": str(message.tool_call_id or ""),
+ "tool_name": str(message.name or ""),
+ "tool_output": extract_message_text(message.content),
+ "tool_status": _tool_status(message),
+ }
+ ],
+ }
+ ]
+
+ if isinstance(message, SystemMessage):
+ return []
+
+ text = extract_message_text(getattr(message, "content", ""))
+ if not text:
+ return []
+ role = "user" if getattr(message, "type", "") == "human" else "assistant"
+ return [{"role": role, "parts": [{"type": "text", "text": text}]}]
+
+
+def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage]:
+ """Convert one OpenViking session message into LangChain messages."""
+
+ role = str(message.get("role") or "")
+ parts = list(message.get("parts") or [])
+ text = _parts_text(parts)
+ if role == "user":
+ return [HumanMessage(content=text)]
+
+ tool_calls = []
+ tool_messages = []
+ for part in parts:
+ if part.get("type") != "tool":
+ continue
+ tool_id = str(part.get("tool_id") or "")
+ tool_name = str(part.get("tool_name") or "")
+ status = str(part.get("tool_status") or "")
+ has_output = part.get("tool_output") is not None
+ is_completed_result = has_output or status in {"completed", "error"}
+ if is_completed_result:
+ tool_messages.append(
+ ToolMessage(
+ content=str(part.get("tool_output") or ""),
+ tool_call_id=tool_id or "openviking-tool",
+ name=tool_name or None,
+ status="error" if status == "error" else "success",
+ )
+ )
+ else:
+ tool_calls.append(
+ {
+ "id": tool_id,
+ "name": tool_name,
+ "args": _tool_args(part.get("tool_input")),
+ }
+ )
+
+ messages: list[BaseMessage] = []
+ if text or tool_calls or not tool_messages:
+ messages.append(
+ AIMessage(content=text, tool_calls=tool_calls or [])
+ if tool_calls
+ else AIMessage(content=text)
+ )
+ messages.extend(tool_messages)
+ return messages
+
+
+def _restore_openviking_messages(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:
+ restored: list[BaseMessage] = []
+ active_tool_call_ids: set[str] = set()
+ for message in messages:
+ for langchain_message in openviking_message_to_langchain(message):
+ if isinstance(langchain_message, AIMessage):
+ restored.append(langchain_message)
+ for tool_call in langchain_message.tool_calls or []:
+ tool_call_id = str(tool_call.get("id") or "")
+ if tool_call_id:
+ active_tool_call_ids.add(tool_call_id)
+ elif isinstance(langchain_message, ToolMessage):
+ tool_call_id = str(langchain_message.tool_call_id or "")
+ if tool_call_id and tool_call_id in active_tool_call_ids:
+ restored.append(langchain_message)
+ active_tool_call_ids.discard(tool_call_id)
+ else:
+ restored.append(langchain_message)
+ return restored
+
+
+def context_parts_from_documents(documents: Sequence[Any]) -> list[dict[str, Any]]:
+ """Build OpenViking ContextPart dictionaries from LangChain Documents."""
+
+ parts: list[dict[str, Any]] = []
+ for doc in documents:
+ metadata = getattr(doc, "metadata", {}) or {}
+ uri = metadata.get("openviking_uri") or metadata.get("source") or ""
+ if not uri:
+ continue
+ parts.append(
+ {
+ "type": "context",
+ "uri": uri,
+ "context_type": metadata.get("openviking_context_type") or "resource",
+ "abstract": metadata.get("openviking_abstract")
+ or getattr(doc, "page_content", "")[:500],
+ }
+ )
+ return parts
+
+
+def _text_parts(content: Any) -> list[dict[str, str]]:
+ text = extract_message_text(content)
+ return [{"type": "text", "text": text}] if text else []
+
+
+def _parts_text(parts: Sequence[dict[str, Any]]) -> str:
+ chunks: list[str] = []
+ for part in parts:
+ part_type = part.get("type")
+ if part_type == "text" and part.get("text"):
+ chunks.append(str(part["text"]))
+ elif part_type == "context" and part.get("abstract"):
+ uri = part.get("uri") or "context"
+ chunks.append(f"[context:{uri}] {part['abstract']}")
+ return "\n".join(chunks)
+
+
+def _tool_args(value: Any) -> dict[str, Any]:
+ if value is None:
+ return {}
+ if isinstance(value, dict):
+ return value
+ return {"value": value}
+
+
+def _tool_status(message: ToolMessage) -> str:
+ return "error" if getattr(message, "status", "") == "error" else "completed"
diff --git a/openviking/integrations/langchain/middleware.py b/openviking/integrations/langchain/middleware.py
new file mode 100644
index 000000000..6b4fb59ca
--- /dev/null
+++ b/openviking/integrations/langchain/middleware.py
@@ -0,0 +1,331 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LangGraph agent middleware for OpenViking recall and capture."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Callable
+
+try:
+ from langchain.agents.middleware import AgentMiddleware
+ from langchain.agents.middleware.types import ModelRequest
+ from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+ )
+except ImportError as exc: # pragma: no cover - exercised by optional import path
+ from openviking.integrations.langchain.client import missing_dependency
+
+ raise missing_dependency("langgraph", "langchain/langgraph") from exc
+
+from openviking.integrations.langchain.client import (
+ OpenVikingCommitPolicy,
+ OpenVikingConnection,
+ call_openviking,
+ ensure_client,
+ extract_message_text,
+ get_latest_user_text,
+ maybe_commit_session,
+)
+from openviking.integrations.langchain.context import (
+ OPENVIKING_CONTEXT_MARKER,
+ OpenVikingSessionContextAssembler,
+)
+from openviking.integrations.langchain.history import langchain_message_to_openviking
+from openviking.integrations.langchain.retrievers import OpenVikingRetriever
+
+logger = logging.getLogger(__name__)
+
+_SESSION_ID_ERROR = (
+ "OpenVikingContextMiddleware requires a LangGraph session id. Pass "
+ 'config={"configurable": {"thread_id": "..."}}, set state["session_id"], '
+ "or provide session_id_resolver."
+)
+
+
+class OpenVikingContextMiddleware(AgentMiddleware):
+ """Inject OpenViking recall into LangGraph agent model calls.
+
+ The middleware mirrors the OpenClaw-style lifecycle at LangGraph's extension
+ points: recall before model calls and optional session capture after agent
+ execution.
+ """
+
+ def __init__(
+ self,
+ *,
+ client: Any = None,
+ retriever: OpenVikingRetriever | None = None,
+ url: str | None = None,
+ api_key: str | None = None,
+ account: str | None = None,
+ user: str | None = None,
+ user_id: str | None = None,
+ agent_id: str | None = None,
+ path: str | None = None,
+ target_uri: str | list[str] = "",
+ limit: int = 5,
+ score_threshold: float | None = None,
+ token_budget: int = 128_000,
+ session_id_resolver: Callable[[dict[str, Any], Any], str] | None = None,
+ capture_on_after_agent: bool = True,
+ commit_on_after_agent: bool = False,
+ commit_policy: OpenVikingCommitPolicy | None = None,
+ recall_header: str = "Relevant OpenViking context:",
+ include_active_messages: bool = False,
+ ):
+ super().__init__()
+ self._client = client
+ self._connection = OpenVikingConnection(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ )
+ self.retriever = retriever or OpenVikingRetriever(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=score_threshold,
+ search_mode="search",
+ )
+ self.assembler = OpenVikingSessionContextAssembler(
+ client=client,
+ retriever=self.retriever,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=score_threshold,
+ token_budget=token_budget,
+ include_session_context=True,
+ include_active_messages=include_active_messages,
+ include_recall=True,
+ recall_header=recall_header,
+ )
+ self.session_id_resolver = session_id_resolver
+ self.capture_on_after_agent = capture_on_after_agent
+ self.commit_policy = commit_policy
+ if commit_on_after_agent and self.commit_policy is None:
+ self.commit_policy = OpenVikingCommitPolicy(mode="always")
+ self.recall_header = recall_header
+ self._captured_signatures: dict[str, tuple[str, ...]] = {}
+ self._pending_context_parts: dict[str, list[dict[str, Any]]] = {}
+
+ def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], Any]) -> Any:
+ query = get_latest_user_text(request.messages)
+ if not query:
+ return handler(request)
+ session_id = self._resolve_session_id(
+ getattr(request, "state", {}) or {},
+ getattr(request, "runtime", None),
+ )
+ self._pending_context_parts.pop(session_id, None)
+ assembled = self.assembler.assemble(session_id=session_id, query=query)
+ context_block = assembled.block
+ if not context_block:
+ return handler(request)
+ if assembled.context_parts:
+ self._pending_context_parts[session_id] = assembled.context_parts
+
+ system_message = request.system_message
+ if system_message is None:
+ updated_system = SystemMessage(content=context_block)
+ else:
+ content = extract_message_text(system_message.content)
+ updated_system = SystemMessage(content=f"{content}\n\n{context_block}".strip())
+ try:
+ return handler(request.override(system_message=updated_system))
+ except Exception:
+ self._pending_context_parts.pop(session_id, None)
+ raise
+
+ def after_agent(self, state: dict[str, Any], runtime: Any) -> dict[str, Any] | None:
+ if not self.capture_on_after_agent:
+ return None
+ messages = list(state.get("messages") or [])
+ if not messages:
+ return None
+ session_id = self._resolve_session_id(state, runtime)
+ previous_signatures = self._captured_signatures.get(session_id, ())
+ current_signatures = tuple(_message_signature(message) for message in messages)
+
+ if current_signatures == previous_signatures:
+ self._pending_context_parts.pop(session_id, None)
+ return None
+ start = 0
+ if (
+ previous_signatures
+ and len(current_signatures) > len(previous_signatures)
+ and current_signatures[: len(previous_signatures)] == previous_signatures
+ ):
+ start = len(previous_signatures)
+
+ client = ensure_client(self._connection)
+ added = 0
+ pending_context_parts = list(self._pending_context_parts.pop(session_id, []))
+ for message in messages[start:]:
+ if OPENVIKING_CONTEXT_MARKER in _message_content(message):
+ continue
+ payloads = langchain_message_to_openviking(message)
+ for payload in payloads:
+ if pending_context_parts and payload["role"] == "assistant":
+ payload["parts"].extend(pending_context_parts)
+ pending_context_parts = []
+ call_openviking(
+ client,
+ "add_message",
+ session_id=session_id,
+ role=payload["role"],
+ parts=payload["parts"],
+ )
+ added += 1
+ self._captured_signatures[session_id] = current_signatures
+ if added:
+ maybe_commit_session(client, session_id, self.commit_policy)
+ return None
+
+ def _resolve_session_id(self, state: dict[str, Any], runtime: Any) -> str:
+ if self.session_id_resolver:
+ resolved = _normalize_session_id(self.session_id_resolver(state, runtime))
+ if resolved:
+ return resolved
+ raise ValueError(_SESSION_ID_ERROR)
+ candidates = [
+ state.get("thread_id"),
+ state.get("session_id"),
+ _nested_get(getattr(runtime, "context", None), "thread_id"),
+ _nested_get(getattr(runtime, "config", None), "configurable", "thread_id"),
+ _nested_get(getattr(runtime, "config", None), "configurable", "session_id"),
+ ]
+ for candidate in candidates:
+ resolved = _normalize_session_id(candidate)
+ if resolved:
+ return resolved
+ raise ValueError(_SESSION_ID_ERROR)
+
+ def _ensure_session(self, client: Any, session_id: str) -> None:
+ try:
+ call_openviking(client, "create_session", session_id=session_id)
+ except Exception:
+ logger.debug("OpenViking LangGraph middleware session ensure failed", exc_info=True)
+ pass
+
+
+def _nested_get(value: Any, *keys: str) -> Any:
+ current = value
+ for key in keys:
+ if current is None:
+ return None
+ if isinstance(current, dict):
+ current = current.get(key)
+ else:
+ current = getattr(current, key, None)
+ return current
+
+
+def _normalize_session_id(value: Any) -> str | None:
+ if value is None:
+ return None
+ text = str(value).strip()
+ return text or None
+
+
+def _message_role(message: Any) -> str:
+ if isinstance(message, HumanMessage):
+ return "user"
+ if isinstance(message, AIMessage):
+ return "assistant"
+ if isinstance(message, BaseMessage):
+ if message.type == "human":
+ return "user"
+ if message.type == "ai":
+ return "assistant"
+ return message.type
+ if isinstance(message, dict):
+ role = str(message.get("role") or message.get("type") or "")
+ return {"human": "user", "ai": "assistant"}.get(role, role)
+ return str(getattr(message, "role", "") or getattr(message, "type", ""))
+
+
+def _message_content(message: Any) -> str:
+ if isinstance(message, dict):
+ return extract_message_text(message.get("content"))
+ return extract_message_text(getattr(message, "content", ""))
+
+
+def _message_stable_id(message: Any) -> str | None:
+ if isinstance(message, dict):
+ value = message.get("id")
+ else:
+ value = getattr(message, "id", None)
+ return str(value) if value else None
+
+
+def _message_signature(message: Any) -> str:
+ return _stable_json(
+ {
+ "id": _message_stable_id(message),
+ "role": _message_role(message),
+ "content": _message_content(message),
+ "tool_calls": _message_tool_calls(message),
+ "tool_result": _message_tool_result(message),
+ }
+ )
+
+
+def _message_tool_calls(message: Any) -> Any:
+ if isinstance(message, AIMessage):
+ calls = getattr(message, "tool_calls", None) or []
+ if not calls:
+ calls = (getattr(message, "additional_kwargs", {}) or {}).get("tool_calls") or []
+ return calls
+ if isinstance(message, dict):
+ return message.get("tool_calls") or []
+ return getattr(message, "tool_calls", None) or []
+
+
+def _message_tool_result(message: Any) -> dict[str, Any]:
+ if isinstance(message, ToolMessage):
+ return {
+ "tool_call_id": getattr(message, "tool_call_id", None),
+ "name": getattr(message, "name", None),
+ "status": getattr(message, "status", None),
+ }
+ if isinstance(message, dict):
+ return {
+ "tool_call_id": message.get("tool_call_id") or message.get("tool_id"),
+ "name": message.get("name") or message.get("tool_name"),
+ "output": message.get("tool_output") or message.get("output"),
+ "status": message.get("status") or message.get("tool_status"),
+ }
+ return {
+ "tool_call_id": getattr(message, "tool_call_id", None),
+ "name": getattr(message, "name", None),
+ "status": getattr(message, "status", None),
+ }
+
+
+def _stable_json(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
diff --git a/openviking/integrations/langchain/retrievers.py b/openviking/integrations/langchain/retrievers.py
new file mode 100644
index 000000000..21aeb16d1
--- /dev/null
+++ b/openviking/integrations/langchain/retrievers.py
@@ -0,0 +1,139 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LangChain retriever backed by OpenViking retrieval."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Literal
+
+from pydantic import ConfigDict, Field, PrivateAttr
+
+try:
+ from langchain_core.documents import Document
+ from langchain_core.retrievers import BaseRetriever
+except ImportError as exc: # pragma: no cover - exercised by optional import path
+ from openviking.integrations.langchain.client import missing_dependency
+
+ raise missing_dependency("langchain", "langchain-core") from exc
+
+from openviking.integrations.langchain.client import (
+ OpenVikingConnection,
+ call_openviking,
+ ensure_client,
+ item_value,
+ iter_result_items,
+ stringify,
+)
+
+
+class OpenVikingRetriever(BaseRetriever):
+ """Retrieve LangChain ``Document`` objects from OpenViking contexts."""
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ client: Any = None
+ url: str | None = None
+ api_key: str | None = None
+ account: str | None = None
+ user: str | None = None
+ user_id: str | None = None
+ agent_id: str | None = None
+ path: str | None = None
+ timeout: float = 60.0
+ extra_headers: dict[str, str] | None = None
+ auto_initialize: bool = True
+
+ target_uri: str | list[str] = ""
+ search_mode: Literal["find", "search"] = "find"
+ session_id: str | None = None
+ limit: int = 10
+ score_threshold: float | None = None
+ filter: dict[str, Any] | None = None
+ context_types: tuple[str, ...] = ("memory", "resource", "skill")
+ content_mode: Literal["auto", "abstract", "overview", "read"] = "auto"
+ max_content_chars: int = 12_000
+ metadata_prefix: str = "openviking"
+ tags: list[str] | None = Field(default=None, exclude=True)
+
+ _client_cache: Any = PrivateAttr(default=None)
+
+ def _get_client(self) -> Any:
+ if self._client_cache is None:
+ self._client_cache = ensure_client(
+ OpenVikingConnection(
+ client=self.client,
+ url=self.url,
+ api_key=self.api_key,
+ account=self.account,
+ user=self.user,
+ user_id=self.user_id,
+ agent_id=self.agent_id,
+ path=self.path,
+ timeout=self.timeout,
+ extra_headers=self.extra_headers,
+ auto_initialize=self.auto_initialize,
+ )
+ )
+ return self._client_cache
+
+ def _get_relevant_documents(self, query: str, *, run_manager: Any) -> list[Document]:
+ client = self._get_client()
+ method = "search" if self.search_mode == "search" else "find"
+ result = call_openviking(
+ client,
+ method,
+ query=query,
+ target_uri=self.target_uri,
+ session_id=self.session_id,
+ limit=self.limit,
+ score_threshold=self.score_threshold,
+ filter=self.filter,
+ )
+ documents: list[Document] = []
+ for context_type, item in iter_result_items(result, self.context_types):
+ uri = item_value(item, "uri", "")
+ content = self._content_for_item(client, item)
+ metadata = {
+ "source": uri,
+ f"{self.metadata_prefix}_uri": uri,
+ f"{self.metadata_prefix}_context_type": context_type,
+ f"{self.metadata_prefix}_level": item_value(item, "level"),
+ f"{self.metadata_prefix}_category": item_value(item, "category"),
+ f"{self.metadata_prefix}_score": item_value(item, "score"),
+ f"{self.metadata_prefix}_match_reason": item_value(item, "match_reason"),
+ f"{self.metadata_prefix}_abstract": item_value(item, "abstract"),
+ f"{self.metadata_prefix}_overview": item_value(item, "overview"),
+ }
+ documents.append(Document(page_content=content, metadata=metadata))
+ return documents
+
+ async def _aget_relevant_documents(self, query: str, *, run_manager: Any) -> list[Document]:
+ return await asyncio.to_thread(
+ lambda: self._get_relevant_documents(query, run_manager=run_manager)
+ )
+
+ def _content_for_item(self, client: Any, item: Any) -> str:
+ uri = item_value(item, "uri", "")
+ abstract = item_value(item, "abstract", "")
+ overview = item_value(item, "overview", "")
+ level = item_value(item, "level")
+
+ if self.content_mode == "abstract":
+ return stringify(abstract or overview, max_chars=self.max_content_chars)
+ if self.content_mode == "overview":
+ return stringify(overview or abstract, max_chars=self.max_content_chars)
+ if self.content_mode == "read":
+ return self._read_or_fallback(client, uri, overview or abstract)
+ if level == 2 and uri:
+ return self._read_or_fallback(client, uri, overview or abstract)
+ return stringify(overview or abstract, max_chars=self.max_content_chars)
+
+ def _read_or_fallback(self, client: Any, uri: str, fallback: Any) -> str:
+ if uri:
+ try:
+ content = call_openviking(client, "read", uri=uri)
+ return stringify(content, max_chars=self.max_content_chars)
+ except Exception:
+ pass
+ return stringify(fallback, max_chars=self.max_content_chars)
diff --git a/openviking/integrations/langchain/store.py b/openviking/integrations/langchain/store.py
new file mode 100644
index 000000000..6fbe3ab3a
--- /dev/null
+++ b/openviking/integrations/langchain/store.py
@@ -0,0 +1,589 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LangGraph Store implementation backed by OpenViking."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any, Iterable
+from urllib.parse import quote, unquote
+
+from openviking.core.namespace import UriClassification, classify_uri
+from openviking.integrations.langchain.client import (
+ OpenVikingConnection,
+ call_openviking,
+ ensure_client,
+ item_value,
+ iter_result_items,
+)
+
+try:
+ from langgraph.store.base import (
+ BaseStore,
+ GetOp,
+ Item,
+ ListNamespacesOp,
+ PutOp,
+ SearchItem,
+ SearchOp,
+ )
+except ImportError: # pragma: no cover - exercised by optional import path
+ from openviking.integrations.langchain.client import missing_dependency
+
+ _LANGGRAPH_IMPORT_ERROR = missing_dependency("langgraph", "langgraph")
+ BaseStore = object # type: ignore[assignment,misc]
+ GetOp = PutOp = SearchOp = ListNamespacesOp = object # type: ignore[misc,assignment]
+ Item = SearchItem = object # type: ignore[misc,assignment]
+else:
+ _LANGGRAPH_IMPORT_ERROR = None
+
+logger = logging.getLogger(__name__)
+
+
+class OpenVikingStore(BaseStore):
+ """LangGraph ``BaseStore`` persisted and indexed through OpenViking.
+
+ Values are stored as JSON records under ``<root_uri>/data``. A separate
+ markdown projection under ``<root_uri>/index`` gives OpenViking semantic
+ retrieval a compact document to index for query-based ``search`` calls.
+ """
+
+ def __init__(
+ self,
+ *,
+ client: Any = None,
+ url: str | None = None,
+ api_key: str | None = None,
+ account: str | None = None,
+ user: str | None = None,
+ user_id: str | None = None,
+ agent_id: str | None = None,
+ path: str | None = None,
+ root_uri: str = "viking://user/memories/langgraph_store",
+ index: bool | list[str] | None = None,
+ wait: bool = True,
+ timeout: float | None = None,
+ search_fetch_limit: int = 50,
+ auto_initialize: bool = True,
+ ):
+ if _LANGGRAPH_IMPORT_ERROR is not None:
+ raise _LANGGRAPH_IMPORT_ERROR
+ super().__init__()
+ self._connection = OpenVikingConnection(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ auto_initialize=auto_initialize,
+ )
+ self.root_uri = root_uri.rstrip("/")
+ self.index = index
+ self.wait = wait
+ self.timeout = timeout
+ self.search_fetch_limit = search_fetch_limit
+ self._client_cache: Any = None
+
+ def batch(self, ops: Iterable[Any]) -> list[Any]:
+ results: list[Any] = []
+ for op in ops:
+ if isinstance(op, GetOp):
+ results.append(self.get(op.namespace, op.key))
+ elif isinstance(op, PutOp):
+ if op.value is None:
+ self.delete(op.namespace, op.key)
+ else:
+ self.put(op.namespace, op.key, op.value, index=op.index, ttl=op.ttl)
+ results.append(None)
+ elif isinstance(op, SearchOp):
+ results.append(
+ self.search(
+ op.namespace_prefix,
+ query=op.query,
+ filter=op.filter,
+ limit=op.limit,
+ offset=op.offset,
+ )
+ )
+ elif isinstance(op, ListNamespacesOp):
+ prefix, suffix = self._match_conditions_to_prefix_suffix(op.match_conditions)
+ results.append(
+ self.list_namespaces(
+ prefix=prefix,
+ suffix=suffix,
+ max_depth=op.max_depth,
+ limit=op.limit,
+ offset=op.offset,
+ )
+ )
+ else:
+ raise TypeError(f"Unsupported LangGraph store operation: {type(op)!r}")
+ return results
+
+ async def abatch(self, ops: Iterable[Any]) -> list[Any]:
+ return await asyncio.to_thread(lambda: self.batch(list(ops)))
+
+ def get(self, namespace: tuple[str, ...], key: str, *, refresh_ttl: Any = None) -> Any:
+ try:
+ record = self._read_record(self._data_uri(namespace, key))
+ except Exception:
+ return None
+ return Item(
+ namespace=tuple(record["namespace"]),
+ key=record["key"],
+ value=record["value"],
+ created_at=_parse_dt(record["created_at"]),
+ updated_at=_parse_dt(record["updated_at"]),
+ )
+
+ def put(
+ self,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ index: bool | list[str] | None = None,
+ *,
+ ttl: Any = None,
+ ) -> None:
+ if ttl is not None:
+ raise NotImplementedError(
+ "TTL is not supported by OpenVikingStore. "
+ "OpenViking stores LangGraph values as durable content records."
+ )
+ namespace = tuple(namespace)
+ now = datetime.now(timezone.utc)
+ data_uri = self._data_uri(namespace, key)
+ record = self._write_record(data_uri, namespace, key, value, now)
+
+ effective_index = self.index if index is None else index
+ index_uri = self._index_uri(namespace, key)
+ if effective_index is False:
+ self._remove(index_uri)
+ return
+ self._write(index_uri, self._index_document(record, effective_index))
+
+ def delete(self, namespace: tuple[str, ...], key: str) -> None:
+ self._remove(self._data_uri(namespace, key))
+ self._remove(self._index_uri(namespace, key))
+
+ def search(
+ self,
+ namespace_prefix: tuple[str, ...],
+ *,
+ query: str | None = None,
+ filter: dict[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ refresh_ttl: Any = None,
+ ) -> list[Any]:
+ namespace_prefix = tuple(namespace_prefix)
+ if query:
+ return self._semantic_search(namespace_prefix, query, filter, limit, offset)
+ items = [
+ self._item_to_search_item(item, score=None)
+ for item in self._list_items(namespace_prefix)
+ if _matches_filter(item.value, filter)
+ ]
+ items.sort(key=lambda item: (item.updated_at, item.namespace, item.key), reverse=True)
+ return items[offset : offset + limit]
+
+ def list_namespaces(
+ self,
+ *,
+ prefix: tuple[str, ...] | None = None,
+ suffix: tuple[str, ...] | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ ) -> list[tuple[str, ...]]:
+ namespaces = set()
+ for uri in self._all_data_uris(prefix or ()):
+ parsed = self._parse_data_uri(uri)
+ if parsed is None:
+ continue
+ namespace, _key = parsed
+ if prefix and not _tuple_matches_prefix(namespace, prefix):
+ continue
+ if suffix and not _tuple_matches_suffix(namespace, suffix):
+ continue
+ if max_depth is not None and len(namespace) > max_depth:
+ namespace = namespace[:max_depth]
+ namespaces.add(namespace)
+ ordered = sorted(namespaces)
+ return ordered[offset : offset + limit]
+
+ def _semantic_search(
+ self,
+ namespace_prefix: tuple[str, ...],
+ query: str,
+ filter: dict[str, Any] | None,
+ limit: int,
+ offset: int,
+ ) -> list[Any]:
+ result = call_openviking(
+ self._client(),
+ "find",
+ query=query,
+ target_uri=self._index_prefix_uri(namespace_prefix),
+ limit=max(limit + offset, self.search_fetch_limit),
+ )
+ items: list[Any] = []
+ for _context_type, result_item in iter_result_items(
+ result, ("memory", "resource", "skill")
+ ):
+ uri = item_value(result_item, "uri", "")
+ parsed = self._parse_index_uri(uri)
+ if parsed is None:
+ continue
+ namespace, key = parsed
+ item = self.get(namespace, key)
+ if item is None or not _matches_filter(item.value, filter):
+ continue
+ items.append(self._item_to_search_item(item, score=item_value(result_item, "score")))
+ return items[offset : offset + limit]
+
+ def _list_items(self, namespace_prefix: tuple[str, ...]) -> list[Any]:
+ items = []
+ for uri in self._all_data_uris(namespace_prefix):
+ parsed = self._parse_data_uri(uri)
+ if parsed is None:
+ continue
+ namespace, key = parsed
+ item = self.get(namespace, key)
+ if item is not None:
+ items.append(item)
+ return items
+
+ def _all_data_uris(self, namespace_prefix: tuple[str, ...]) -> list[str]:
+ base_uri = self._data_prefix_uri(namespace_prefix)
+ uris: list[str] = []
+ seen: set[str] = set()
+ for pattern in ("*.json", "**/*.json"):
+ try:
+ result = call_openviking(self._client(), "glob", pattern=pattern, uri=base_uri)
+ except Exception:
+ continue
+ for uri in _extract_uris(result):
+ if uri not in seen:
+ seen.add(uri)
+ uris.append(uri)
+ return uris
+
+ def _client(self) -> Any:
+ if self._client_cache is None:
+ self._client_cache = ensure_client(self._connection)
+ return self._client_cache
+
+ def _read_record(self, uri: str) -> dict[str, Any]:
+ content = call_openviking(self._client(), "read", uri=uri)
+ if isinstance(content, bytes):
+ content = content.decode("utf-8")
+ return json.loads(str(content))
+
+ def _write_record(
+ self,
+ uri: str,
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ now: datetime,
+ ) -> dict[str, Any]:
+ record = _store_record(namespace, key, value, created_at=now, updated_at=now)
+ content = json.dumps(record, ensure_ascii=False, indent=2)
+ try:
+ self._write_create(uri, content)
+ return record
+ except Exception as create_exc:
+ try:
+ existing = self._read_record(uri)
+ except Exception:
+ raise create_exc
+
+ created_at = _parse_dt(existing["created_at"])
+ record = _store_record(namespace, key, value, created_at=created_at, updated_at=now)
+ self._write_replace(uri, json.dumps(record, ensure_ascii=False, indent=2))
+ return record
+
+ def _write(self, uri: str, content: str) -> None:
+ try:
+ self._write_create(uri, content)
+ return
+ except Exception as create_exc:
+ try:
+ self._write_replace(uri, content)
+ return
+ except Exception:
+ raise create_exc
+
+ def _write_create(self, uri: str, content: str) -> None:
+ call_openviking(
+ self._client(),
+ "write",
+ uri=uri,
+ content=content,
+ mode="create",
+ wait=self.wait,
+ timeout=self.timeout,
+ )
+
+ def _write_replace(self, uri: str, content: str) -> None:
+ call_openviking(
+ self._client(),
+ "write",
+ uri=uri,
+ content=content,
+ mode="replace",
+ wait=self.wait,
+ timeout=self.timeout,
+ )
+
+ def _remove(self, uri: str) -> None:
+ try:
+ call_openviking(self._client(), "rm", uri=uri, recursive=False)
+ except Exception:
+ logger.debug("OpenVikingStore remove ignored missing/unavailable URI", exc_info=True)
+ pass
+
+ def _data_uri(self, namespace: tuple[str, ...], key: str) -> str:
+ return f"{self._data_prefix_uri(namespace)}/{_segment(key)}.json"
+
+ def _index_uri(self, namespace: tuple[str, ...], key: str) -> str:
+ return f"{self._index_prefix_uri(namespace)}/{_segment(key)}.md"
+
+ def _data_prefix_uri(self, namespace: tuple[str, ...]) -> str:
+ return _join_uri(self.root_uri, "data", *namespace)
+
+ def _index_prefix_uri(self, namespace: tuple[str, ...]) -> str:
+ return _join_uri(self.root_uri, "index", *namespace)
+
+ def _parse_data_uri(self, uri: str) -> tuple[tuple[str, ...], str] | None:
+ return self._parse_record_uri(uri, "data", ".json")
+
+ def _parse_index_uri(self, uri: str) -> tuple[tuple[str, ...], str] | None:
+ return self._parse_record_uri(uri, "index", ".md")
+
+ def _parse_record_uri(
+ self, uri: str, collection: str, suffix: str
+ ) -> tuple[tuple[str, ...], str] | None:
+ prefix = _join_uri(self.root_uri, collection) + "/"
+ if not uri.startswith(prefix) or not uri.endswith(suffix):
+ return _parse_canonicalized_record_uri(
+ root_uri=self.root_uri,
+ uri=uri,
+ collection=collection,
+ suffix=suffix,
+ )
+ return _parse_record_parts(uri[len(prefix) : -len(suffix)].split("/"))
+
+ def _index_document(self, record: dict[str, Any], index: bool | list[str] | None) -> str:
+ value = record["value"]
+ projected = _project_value(value, index)
+ return "\n".join(
+ [
+ f"# {record['key']}",
+ "",
+ f"Namespace: {'/'.join(record['namespace'])}",
+ f"Key: {record['key']}",
+ "",
+ json.dumps(projected, ensure_ascii=False, indent=2),
+ ]
+ )
+
+ def _item_to_search_item(self, item: Any, score: float | None) -> Any:
+ return SearchItem(
+ namespace=item.namespace,
+ key=item.key,
+ value=item.value,
+ created_at=item.created_at,
+ updated_at=item.updated_at,
+ score=score,
+ )
+
+ def _match_conditions_to_prefix_suffix(
+ self, conditions: Iterable[Any] | None
+ ) -> tuple[tuple[str, ...] | None, tuple[str, ...] | None]:
+ prefix = None
+ suffix = None
+ for condition in conditions or []:
+ match_type = getattr(condition, "match_type", None)
+ path = tuple(getattr(condition, "path", ()) or ())
+ if match_type == "prefix":
+ prefix = path
+ elif match_type == "suffix":
+ suffix = path
+ return prefix, suffix
+
+
+def _segment(value: str) -> str:
+ return quote(str(value), safe="")
+
+
+def _join_uri(root: str, *segments: str) -> str:
+ suffix = "/".join(_segment(segment) for segment in segments if segment)
+ return root.rstrip("/") if not suffix else f"{root.rstrip('/')}/{suffix}"
+
+
+def _parse_canonicalized_record_uri(
+ *,
+ root_uri: str,
+ uri: str,
+ collection: str,
+ suffix: str,
+) -> tuple[tuple[str, ...], str] | None:
+ root = classify_uri(root_uri)
+ root_tail = _identity_relative_root_tail(root)
+ if root_tail is None:
+ return None
+
+ candidate = classify_uri(uri)
+ if candidate.scope != root.scope or candidate.content_index is None:
+ return None
+
+ candidate_tail = candidate.parts[candidate.content_index :]
+ if len(candidate_tail) < len(root_tail) + 2:
+ return None
+ if candidate_tail[: len(root_tail)] != root_tail:
+ return None
+
+ collection_index = len(root_tail)
+ if candidate_tail[collection_index] != collection:
+ return None
+
+ rel_parts = list(candidate_tail[collection_index + 1 :])
+ if not rel_parts or not rel_parts[-1].endswith(suffix):
+ return None
+ rel_parts = [*rel_parts[:-1], rel_parts[-1][: -len(suffix)]]
+ return _parse_record_parts(rel_parts)
+
+
+def _identity_relative_root_tail(classification: UriClassification) -> tuple[str, ...] | None:
+ if classification.scope not in {"user", "agent"}:
+ return None
+ if classification.content_index != 1:
+ return None
+ return classification.parts[classification.content_index :]
+
+
+def _parse_record_parts(parts: list[str]) -> tuple[tuple[str, ...], str] | None:
+ if not parts or not parts[-1]:
+ return None
+ namespace = tuple(unquote(part) for part in parts[:-1])
+ key = unquote(parts[-1])
+ return namespace, key
+
+
+def _parse_dt(value: str) -> datetime:
+ parsed = datetime.fromisoformat(value)
+ if parsed.tzinfo is None:
+ return parsed.replace(tzinfo=timezone.utc)
+ return parsed
+
+
+def _store_record(
+ namespace: tuple[str, ...],
+ key: str,
+ value: dict[str, Any],
+ *,
+ created_at: datetime,
+ updated_at: datetime,
+) -> dict[str, Any]:
+ return {
+ "namespace": list(namespace),
+ "key": key,
+ "value": value,
+ "created_at": created_at.isoformat(),
+ "updated_at": updated_at.isoformat(),
+ }
+
+
+def _extract_uris(value: Any) -> list[str]:
+ if value is None:
+ return []
+ if isinstance(value, str):
+ return [value] if value.startswith("viking://") else []
+ if isinstance(value, dict):
+ if isinstance(value.get("uri"), str):
+ return [value["uri"]]
+ uris: list[str] = []
+ for key in ("matches", "result", "files", "items"):
+ uris.extend(_extract_uris(value.get(key)))
+ return uris
+ if isinstance(value, list):
+ uris: list[str] = []
+ for item in value:
+ uris.extend(_extract_uris(item))
+ return uris
+ return []
+
+
+def _project_value(value: dict[str, Any], index: bool | list[str] | None) -> dict[str, Any]:
+ if isinstance(index, list):
+ return {field: _nested_value(value, field) for field in index}
+ return value
+
+
+def _nested_value(value: dict[str, Any], path: str) -> Any:
+ current: Any = value
+ for part in path.split("."):
+ if not isinstance(current, dict):
+ return None
+ current = current.get(part)
+ return current
+
+
+def _matches_filter(value: dict[str, Any], filter: dict[str, Any] | None) -> bool:
+ if not filter:
+ return True
+ for path, expected in filter.items():
+ actual = _nested_value(value, path)
+ if isinstance(expected, dict):
+ for op, target in expected.items():
+ if not _compare(actual, op, target):
+ return False
+ elif actual != expected:
+ return False
+ return True
+
+
+def _compare(actual: Any, op: str, target: Any) -> bool:
+ if op in {"$eq", "eq"}:
+ return actual == target
+ if op in {"$ne", "ne"}:
+ return actual != target
+ if op in {"$gt", "gt"}:
+ return _safe_ordered_compare(actual, target, lambda left, right: left > right)
+ if op in {"$gte", "gte"}:
+ return _safe_ordered_compare(actual, target, lambda left, right: left >= right)
+ if op in {"$lt", "lt"}:
+ return _safe_ordered_compare(actual, target, lambda left, right: left < right)
+ if op in {"$lte", "lte"}:
+ return _safe_ordered_compare(actual, target, lambda left, right: left <= right)
+ if op in {"$in", "in"}:
+ try:
+ return actual in target
+ except TypeError:
+ return False
+ return actual == target
+
+
+def _safe_ordered_compare(actual: Any, target: Any, compare) -> bool:
+ if actual is None:
+ return False
+ try:
+ return bool(compare(actual, target))
+ except TypeError:
+ return False
+
+
+def _tuple_matches_prefix(value: tuple[str, ...], prefix: tuple[str, ...]) -> bool:
+ return len(value) >= len(prefix) and value[: len(prefix)] == prefix
+
+
+def _tuple_matches_suffix(value: tuple[str, ...], suffix: tuple[str, ...]) -> bool:
+ return len(value) >= len(suffix) and value[-len(suffix) :] == suffix
diff --git a/openviking/integrations/langchain/testing.py b/openviking/integrations/langchain/testing.py
new file mode 100644
index 000000000..3c4489bea
--- /dev/null
+++ b/openviking/integrations/langchain/testing.py
@@ -0,0 +1,360 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Deterministic test utilities for framework smoke tests."""
+
+from __future__ import annotations
+
+import fnmatch
+import re
+import uuid
+from collections import defaultdict
+from datetime import datetime, timezone
+from typing import Any
+
+
+class InMemoryOpenVikingClient:
+ """Small OpenViking-compatible client for examples and CI smoke tests.
+
+ This class intentionally implements the OpenViking methods used by the
+ LangChain/LangGraph adapters. It is not a replacement for OpenViking.
+ """
+
+ def __init__(self, records: dict[str, str] | None = None):
+ self.records: dict[str, str] = dict(records or {})
+ self.sessions: dict[str, list[dict[str, Any]]] = defaultdict(list)
+ self.archives: dict[str, list[dict[str, Any]]] = defaultdict(list)
+ self.pending_tokens: dict[str, int] = defaultdict(int)
+ self.find_calls: list[dict[str, Any]] = []
+ self.search_calls: list[dict[str, Any]] = []
+ self._initialized = False
+
+ def initialize(self) -> None:
+ self._initialized = True
+
+ def close(self) -> None:
+ self._initialized = False
+
+ def find(
+ self,
+ query: str,
+ target_uri: str | list[str] = "",
+ limit: int = 10,
+ score_threshold: float | None = None,
+ filter: dict[str, Any] | None = None,
+ **_: Any,
+ ) -> dict[str, Any]:
+ self.find_calls.append(
+ {
+ "query": query,
+ "target_uri": target_uri,
+ "limit": limit,
+ "score_threshold": score_threshold,
+ }
+ )
+ return self._search(query, target_uri, limit, score_threshold)
+
+ def search(
+ self,
+ query: str,
+ target_uri: str | list[str] = "",
+ session_id: str | None = None,
+ limit: int = 10,
+ score_threshold: float | None = None,
+ filter: dict[str, Any] | None = None,
+ **_: Any,
+ ) -> dict[str, Any]:
+ self.search_calls.append(
+ {
+ "query": query,
+ "target_uri": target_uri,
+ "session_id": session_id,
+ "limit": limit,
+ "score_threshold": score_threshold,
+ }
+ )
+ session_text = " ".join(
+ _message_text(message) for message in self.sessions.get(session_id or "", [])
+ )
+ return self._search(f"{query} {session_text}", target_uri, limit, score_threshold)
+
+ def _search(
+ self,
+ query: str,
+ target_uri: str | list[str],
+ limit: int,
+ score_threshold: float | None,
+ ) -> dict[str, Any]:
+ targets = [target_uri] if isinstance(target_uri, str) else list(target_uri)
+ targets = [target.rstrip("/") for target in targets if target]
+ tokens = {token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1}
+ scored: list[tuple[float, str, str]] = []
+ for uri, content in self.records.items():
+ if targets and not any(uri.startswith(target) for target in targets):
+ continue
+ haystack = f"{uri}\n{content}".lower()
+ score = sum(1 for token in tokens if token in haystack)
+ if score == 0 and tokens:
+ continue
+ normalized = float(score or 1)
+ if score_threshold is not None and normalized < score_threshold:
+ continue
+ scored.append((normalized, uri, content))
+ scored.sort(key=lambda row: (-row[0], row[1]))
+ result = {"memories": [], "resources": [], "skills": [], "total": 0}
+ for score, uri, content in scored[:limit]:
+ item = {
+ "uri": uri,
+ "level": 2,
+ "abstract": content[:240],
+ "overview": content,
+ "score": score,
+ "match_reason": "deterministic token match",
+ }
+ if "/skills/" in uri:
+ result["skills"].append(item)
+ elif "/memories/" in uri:
+ result["memories"].append(item)
+ else:
+ result["resources"].append(item)
+ result["total"] = sum(len(result[key]) for key in ("memories", "resources", "skills"))
+ return result
+
+ def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:
+ if uri not in self.records:
+ raise FileNotFoundError(uri)
+ lines = self.records[uri].splitlines()
+ if offset or limit >= 0:
+ end = None if limit < 0 else offset + limit
+ return "\n".join(lines[offset:end])
+ return self.records[uri]
+
+ def abstract(self, uri: str) -> str:
+ return self.read(uri)[:240]
+
+ def overview(self, uri: str) -> str:
+ return self.read(uri)
+
+ def write(
+ self,
+ uri: str,
+ content: str,
+ mode: str = "replace",
+ wait: bool = False,
+ timeout: float | None = None,
+ **_: Any,
+ ) -> dict[str, Any]:
+ if mode == "create" and uri in self.records:
+ raise FileExistsError(uri)
+ if mode == "replace" and uri not in self.records:
+ raise FileNotFoundError(uri)
+ if mode == "append":
+ self.records[uri] = self.records.get(uri, "") + content
+ else:
+ self.records[uri] = content
+ return {"uri": uri, "mode": mode, "content_updated": True}
+
+ def mkdir(self, uri: str, description: str | None = None) -> None:
+ return None
+
+ def rm(self, uri: str, recursive: bool = False) -> None:
+ if recursive:
+ prefix = uri.rstrip("/") + "/"
+ for key in list(self.records):
+ if key == uri or key.startswith(prefix):
+ del self.records[key]
+ return
+ self.records.pop(uri, None)
+
+ def ls(self, uri: str, simple: bool = False, recursive: bool = False, **_: Any) -> list[Any]:
+ prefix = uri.rstrip("/") + "/"
+ seen: set[str] = set()
+ values: list[Any] = []
+ for key in sorted(self.records):
+ if not key.startswith(prefix):
+ continue
+ rel = key[len(prefix) :]
+ if not recursive and "/" in rel:
+ rel = rel.split("/", 1)[0]
+ child_uri = prefix + rel
+ if child_uri in seen:
+ continue
+ seen.add(child_uri)
+ values.append(child_uri if simple else {"uri": child_uri, "rel_path": rel})
+ return values
+
+ def glob(self, pattern: str, uri: str = "viking://") -> dict[str, Any]:
+ prefix = uri.rstrip("/") + "/"
+ matches = []
+ for key in sorted(self.records):
+ if not key.startswith(prefix):
+ continue
+ rel = key[len(prefix) :]
+ if fnmatch.fnmatch(rel, pattern):
+ matches.append(key)
+ return {"matches": matches, "count": len(matches)}
+
+ def grep(
+ self,
+ uri: str,
+ pattern: str,
+ case_insensitive: bool = False,
+ node_limit: int | None = None,
+ **_: Any,
+ ) -> dict[str, Any]:
+ flags = re.IGNORECASE if case_insensitive else 0
+ regex = re.compile(pattern, flags)
+ prefix = uri.rstrip("/") + "/"
+ matches: list[dict[str, Any]] = []
+ for key, content in sorted(self.records.items()):
+ if key != uri and not key.startswith(prefix):
+ continue
+ for line_number, line in enumerate(content.splitlines(), start=1):
+ if regex.search(line):
+ matches.append({"uri": key, "line_number": line_number, "line": line})
+ if node_limit and len(matches) >= node_limit:
+ return {"matches": matches, "count": len(matches)}
+ return {"matches": matches, "count": len(matches)}
+
+ def create_session(self, session_id: str | None = None) -> dict[str, Any]:
+ session_id = session_id or f"session-{uuid.uuid4().hex[:12]}"
+ self.sessions.setdefault(session_id, [])
+ return {"session_id": session_id}
+
+ def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str | None = None,
+ parts: list[dict] | None = None,
+ **_: Any,
+ ) -> dict[str, Any]:
+ message_parts = list(parts or [{"type": "text", "text": content or ""}])
+ message = {
+ "id": f"msg_{uuid.uuid4().hex}",
+ "role": role,
+ "parts": message_parts,
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ }
+ self.sessions.setdefault(session_id, []).append(message)
+ self.pending_tokens[session_id] += max(1, len(_message_text(message)) // 4)
+ return {
+ "session_id": session_id,
+ "role": role,
+ "message_count": len(self.sessions[session_id]),
+ }
+
+ def get_session(self, session_id: str, auto_create: bool = False) -> dict[str, Any]:
+ if auto_create:
+ self.create_session(session_id=session_id)
+ return {
+ "session_id": session_id,
+ "message_count": len(self.sessions.get(session_id, [])),
+ "pending_tokens": self.pending_tokens.get(session_id, 0),
+ }
+
+ def get_session_context(
+ self,
+ session_id: str,
+ token_budget: int = 128_000,
+ **_: Any,
+ ) -> dict[str, Any]:
+ del token_budget
+ latest_archive = self.archives.get(session_id, [])[-1:] or []
+ latest = latest_archive[0] if latest_archive else {}
+ messages = list(self.sessions.get(session_id, []))
+ active_tokens = sum(max(1, len(_message_text(message)) // 4) for message in messages)
+ archive_tokens = max(0, len(str(latest.get("overview", ""))) // 4)
+ return {
+ "latest_archive_overview": latest.get("overview", ""),
+ "pre_archive_abstracts": [
+ {"archive_id": archive["archive_id"], "abstract": archive["abstract"]}
+ for archive in self.archives.get(session_id, [])[:-1]
+ ],
+ "messages": messages,
+ "estimatedTokens": active_tokens + archive_tokens,
+ "stats": {
+ "totalArchives": len(self.archives.get(session_id, [])),
+ "includedArchives": 1 if latest else 0,
+ "droppedArchives": 0,
+ "failedArchives": 0,
+ "activeTokens": active_tokens,
+ "archiveTokens": archive_tokens,
+ },
+ }
+
+ def get_session_archive(self, session_id: str, archive_id: str, **_: Any) -> dict[str, Any]:
+ for archive in self.archives.get(session_id, []):
+ if archive["archive_id"] == archive_id:
+ return dict(archive)
+ raise FileNotFoundError(archive_id)
+
+ def commit_session(
+ self,
+ session_id: str,
+ **_: Any,
+ ) -> dict[str, Any]:
+ messages = list(self.sessions.get(session_id, []))
+ archive_id = f"archive_{len(self.archives[session_id]) + 1:03d}"
+ overview = "\n".join(_message_text(message) for message in messages)
+ if messages:
+ archive_uri = f"viking://session/{session_id}/history/{archive_id}"
+ self.archives[session_id].append(
+ {
+ "archive_id": archive_id,
+ "abstract": overview[:240],
+ "overview": overview,
+ "messages": messages,
+ }
+ )
+ self.records[f"{archive_uri}/messages.jsonl"] = (
+ "\n".join(_message_text(message) for message in messages) + "\n"
+ )
+ self.records[f"{archive_uri}/.abstract.md"] = overview[:240]
+ self.records[f"{archive_uri}/.overview.md"] = overview
+ self.records[f"{archive_uri}/.done"] = "{}"
+ self.sessions[session_id] = []
+ self.pending_tokens[session_id] = 0
+ return {
+ "session_id": session_id,
+ "status": "completed",
+ "archive_id": archive_id if messages else None,
+ "archived": bool(messages),
+ }
+
+ def delete_session(self, session_id: str) -> None:
+ self.sessions.pop(session_id, None)
+ self.archives.pop(session_id, None)
+ self.pending_tokens.pop(session_id, None)
+ session_uri = f"viking://session/{session_id}"
+ for uri in list(self.records):
+ if uri == session_uri or uri.startswith(f"{session_uri}/"):
+ del self.records[uri]
+
+ def add_resource(self, path: str, to: str | None = None, **_: Any) -> dict[str, Any]:
+ uri = to or f"viking://resources/{path.rstrip('/').split('/')[-1]}"
+ self.records.setdefault(uri, f"Resource imported from {path}")
+ return {"status": "completed", "root_uri": uri}
+
+ def add_skill(self, data: Any, **_: Any) -> dict[str, Any]:
+ name = data.get("name", "skill") if isinstance(data, dict) else "skill"
+ uri = f"viking://agent/skills/{name}.md"
+ self.records[uri] = str(data)
+ return {"status": "completed", "uri": uri, "name": name}
+
+ def get_status(self) -> dict[str, Any]:
+ return {"healthy": True, "backend": "in-memory"}
+
+ def is_healthy(self) -> bool:
+ return True
+
+
+def _message_text(message: dict[str, Any]) -> str:
+ chunks: list[str] = []
+ for part in message.get("parts") or []:
+ if part.get("type") == "text" and part.get("text"):
+ chunks.append(str(part["text"]))
+ elif part.get("type") == "context" and part.get("abstract"):
+ chunks.append(str(part["abstract"]))
+ elif part.get("type") == "tool" and part.get("tool_output"):
+ chunks.append(str(part["tool_output"]))
+ return "\n".join(chunks)
diff --git a/openviking/integrations/langchain/tools.py b/openviking/integrations/langchain/tools.py
new file mode 100644
index 000000000..4c39cc803
--- /dev/null
+++ b/openviking/integrations/langchain/tools.py
@@ -0,0 +1,561 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LangChain tool factory for OpenViking primitives."""
+
+from __future__ import annotations
+
+import logging
+import re
+from typing import Any, Iterable
+
+try:
+ from langchain_core.tools import StructuredTool
+except ImportError as exc: # pragma: no cover - exercised by optional import path
+ from openviking.integrations.langchain.client import missing_dependency
+
+ raise missing_dependency("langchain", "langchain-core") from exc
+
+from openviking.integrations.langchain.client import (
+ OpenVikingConnection,
+ call_openviking,
+ compact_json,
+ ensure_client,
+ item_value,
+ iter_result_items,
+ stringify,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def create_openviking_tools(
+ *,
+ client: Any = None,
+ url: str | None = None,
+ api_key: str | None = None,
+ account: str | None = None,
+ user: str | None = None,
+ user_id: str | None = None,
+ agent_id: str | None = None,
+ path: str | None = None,
+ timeout: float = 60.0,
+ extra_headers: dict[str, str] | None = None,
+ auto_initialize: bool = True,
+ profile: str = "agent",
+ tool_names: Iterable[str] | None = None,
+ allow_forget: bool = False,
+) -> list[StructuredTool]:
+ """Create LangChain tools exposing OpenViking's common agent primitives.
+
+ Tool names intentionally use the ``viking_*`` prefix so models see the same
+ conceptual operations that OpenViking users know from plugins and MCP:
+ find/search, browse/read, grep, store, add_resource, add_skill, and health.
+ """
+
+ cached_client: Any = None
+
+ def get_client() -> Any:
+ nonlocal cached_client
+ if cached_client is None:
+ cached_client = ensure_client(
+ OpenVikingConnection(
+ client=client,
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=user,
+ user_id=user_id,
+ agent_id=agent_id,
+ path=path,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ auto_initialize=auto_initialize,
+ )
+ )
+ return cached_client
+
+ def viking_find(
+ query: str,
+ target_uri: str = "",
+ limit: int = 8,
+ min_score: float | None = None,
+ ) -> str:
+ """Quick semantic recall from OpenViking without session context."""
+
+ result = call_openviking(
+ get_client(),
+ "find",
+ query=query,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=min_score,
+ )
+ return _format_retrieval_result(result)
+
+ def viking_search(
+ query: str,
+ target_uri: str = "",
+ session_id: str | None = None,
+ limit: int = 8,
+ min_score: float | None = None,
+ ) -> str:
+ """Session-aware OpenViking retrieval for memories, resources, and skills."""
+
+ result = call_openviking(
+ get_client(),
+ "search",
+ query=query,
+ target_uri=target_uri,
+ session_id=session_id,
+ limit=limit,
+ score_threshold=min_score,
+ )
+ return _format_retrieval_result(result)
+
+ def viking_browse(
+ uri: str = "viking://",
+ recursive: bool = False,
+ pattern: str | None = None,
+ ) -> str:
+ """Browse OpenViking namespaces with ls, or glob when pattern is set."""
+
+ active_client = get_client()
+ if pattern:
+ result = call_openviking(active_client, "glob", pattern=pattern, uri=uri)
+ else:
+ result = call_openviking(active_client, "ls", uri=uri, recursive=recursive)
+ return stringify(result, max_chars=12_000)
+
+ def viking_read(
+ uris: str | list[str],
+ max_chars: int = 12_000,
+ content_mode: str = "read",
+ ) -> str:
+ """Read one or more OpenViking URIs as L0 abstract, L1 overview, or L2 content."""
+
+ active_client = get_client()
+ uri_list = [uris] if isinstance(uris, str) else uris
+ mode = str(content_mode or "read").lower().strip()
+ if mode not in {"abstract", "overview", "read"}:
+ raise ValueError("content_mode must be one of: abstract, overview, read")
+ payload = []
+ for uri in uri_list:
+ content = call_openviking(active_client, mode, uri=uri)
+ payload.append(
+ {
+ "uri": uri,
+ "content_mode": mode,
+ "content": stringify(content, max_chars=max_chars),
+ }
+ )
+ return stringify(payload, max_chars=max_chars * max(1, len(uri_list)))
+
+ def viking_grep(
+ uri: str,
+ pattern: str,
+ case_insensitive: bool = False,
+ node_limit: int = 20,
+ ) -> str:
+ """Search OpenViking file content with a grep-style pattern."""
+
+ result = call_openviking(
+ get_client(),
+ "grep",
+ uri=uri,
+ pattern=pattern,
+ case_insensitive=case_insensitive,
+ node_limit=node_limit,
+ )
+ return stringify(result, max_chars=12_000)
+
+ def viking_store(
+ messages: str | list[dict[str, Any]],
+ session_id: str | None = None,
+ commit: bool = True,
+ ) -> str:
+ """Store a conversation turn in an OpenViking session and optionally commit it."""
+
+ active_client = get_client()
+ if not session_id:
+ created = call_openviking(active_client, "create_session")
+ session_id = created.get("session_id") if isinstance(created, dict) else str(created)
+ normalized_messages = _normalize_messages(messages)
+ for message in normalized_messages:
+ call_openviking(
+ active_client,
+ "add_message",
+ session_id=session_id,
+ role=message["role"],
+ content=message.get("content"),
+ parts=message.get("parts"),
+ )
+ result: dict[str, Any] = {
+ "session_id": session_id,
+ "messages_added": len(normalized_messages),
+ }
+ if commit:
+ result["commit"] = call_openviking(
+ active_client,
+ "commit_session",
+ session_id=session_id,
+ )
+ return compact_json(result)
+
+ def viking_archive_search(
+ session_id: str,
+ query: str,
+ archive_id: str | None = None,
+ token_budget: int = 128_000,
+ max_matches: int = 8,
+ ) -> str:
+ """Search committed OpenViking session archive context."""
+
+ active_client = get_client()
+ if archive_id:
+ archive = call_openviking(
+ active_client,
+ "get_session_archive",
+ session_id=session_id,
+ archive_id=archive_id,
+ )
+ matches = _search_archive_payload(archive, query, max_matches=max_matches)
+ else:
+ matches = _grep_session_history(
+ active_client,
+ session_id=session_id,
+ query=query,
+ max_matches=max_matches,
+ )
+ if _match_count(matches) > 0:
+ return stringify(matches, max_chars=12_000)
+ context = call_openviking(
+ active_client,
+ "get_session_context",
+ session_id=session_id,
+ token_budget=token_budget,
+ )
+ matches = _search_archive_payload(context, query, max_matches=max_matches)
+ return stringify(matches or {"matches": [], "count": 0}, max_chars=12_000)
+
+ def viking_archive_expand(
+ session_id: str,
+ archive_id: str,
+ max_chars: int = 20_000,
+ ) -> str:
+ """Expand one OpenViking session archive by archive ID."""
+
+ archive = call_openviking(
+ get_client(),
+ "get_session_archive",
+ session_id=session_id,
+ archive_id=archive_id,
+ )
+ return stringify(archive, max_chars=max_chars)
+
+ def viking_add_resource(
+ path: str,
+ to: str | None = None,
+ parent: str | None = None,
+ reason: str = "",
+ instruction: str = "",
+ wait: bool = False,
+ timeout: float | None = None,
+ ) -> str:
+ """Import a file, directory, URL, or repository into OpenViking resources."""
+
+ result = call_openviking(
+ get_client(),
+ "add_resource",
+ path=path,
+ to=to,
+ parent=parent,
+ reason=reason,
+ instruction=instruction,
+ wait=wait,
+ timeout=timeout,
+ )
+ return stringify(result, max_chars=8_000)
+
+ def viking_add_skill(
+ data: dict[str, Any] | str,
+ wait: bool = False,
+ timeout: float | None = None,
+ ) -> str:
+ """Register a reusable skill in OpenViking."""
+
+ result = call_openviking(
+ get_client(),
+ "add_skill",
+ data=data,
+ wait=wait,
+ timeout=timeout,
+ )
+ return stringify(result, max_chars=8_000)
+
+ def viking_health() -> str:
+ """Check OpenViking health/status."""
+
+ active_client = get_client()
+ if hasattr(active_client, "get_status"):
+ return stringify(call_openviking(active_client, "get_status"), max_chars=8_000)
+ if hasattr(active_client, "is_healthy"):
+ return compact_json({"healthy": call_openviking(active_client, "is_healthy")})
+ return compact_json({"healthy": True})
+
+ def viking_forget(uri: str, recursive: bool = False) -> str:
+ """Remove a URI from OpenViking. Only expose this to trusted agents."""
+
+ call_openviking(get_client(), "rm", uri=uri, recursive=recursive)
+ return compact_json({"removed": uri, "recursive": recursive})
+
+ all_tools: dict[str, StructuredTool] = {
+ "viking_find": StructuredTool.from_function(viking_find),
+ "viking_search": StructuredTool.from_function(viking_search),
+ "viking_browse": StructuredTool.from_function(viking_browse),
+ "viking_read": StructuredTool.from_function(viking_read),
+ "viking_grep": StructuredTool.from_function(viking_grep),
+ "viking_archive_search": StructuredTool.from_function(viking_archive_search),
+ "viking_archive_expand": StructuredTool.from_function(viking_archive_expand),
+ "viking_store": StructuredTool.from_function(viking_store),
+ "viking_add_resource": StructuredTool.from_function(viking_add_resource),
+ "viking_add_skill": StructuredTool.from_function(viking_add_skill),
+ "viking_health": StructuredTool.from_function(viking_health),
+ "viking_forget": StructuredTool.from_function(viking_forget),
+ }
+
+ if tool_names is None:
+ selected = _profile_tool_names(profile, allow_forget=allow_forget)
+ else:
+ selected = list(tool_names)
+ return [all_tools[name] for name in selected if name in all_tools]
+
+
+def _profile_tool_names(profile: str, *, allow_forget: bool) -> list[str]:
+ retrieval = [
+ "viking_find",
+ "viking_search",
+ "viking_browse",
+ "viking_read",
+ "viking_grep",
+ "viking_archive_search",
+ "viking_archive_expand",
+ ]
+ if profile == "retrieval":
+ names = retrieval + ["viking_health"]
+ elif profile == "admin":
+ names = retrieval + [
+ "viking_store",
+ "viking_add_resource",
+ "viking_add_skill",
+ "viking_health",
+ "viking_forget",
+ ]
+ else:
+ names = retrieval + [
+ "viking_store",
+ "viking_add_resource",
+ "viking_add_skill",
+ "viking_health",
+ ]
+ if allow_forget and "viking_forget" not in names:
+ names.append("viking_forget")
+ return names
+
+
+def _normalize_messages(messages: str | list[dict[str, Any]]) -> list[dict[str, Any]]:
+ if isinstance(messages, str):
+ return [{"role": "user", "parts": [{"type": "text", "text": messages}]}]
+ normalized = []
+ for message in messages:
+ role = str(message.get("role") or "user")
+ if role not in {"user", "assistant", "system", "tool"}:
+ role = "user"
+ if message.get("parts") is not None:
+ normalized.append(
+ {
+ "role": "assistant" if role in {"system", "tool"} else role,
+ "parts": list(message.get("parts") or []),
+ }
+ )
+ continue
+ content = str(message.get("content", ""))
+ if role == "tool":
+ normalized.append(
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "tool",
+ "tool_id": str(message.get("tool_call_id") or message.get("id") or ""),
+ "tool_name": str(message.get("name") or ""),
+ "tool_output": content,
+ "tool_status": "completed",
+ }
+ ],
+ }
+ )
+ elif role == "system":
+ normalized.append({"role": "assistant", "parts": [{"type": "text", "text": content}]})
+ else:
+ normalized.append({"role": role, "parts": [{"type": "text", "text": content}]})
+ return normalized
+
+
+def _format_retrieval_result(result: Any) -> str:
+ lines: list[str] = []
+ for index, (context_type, item) in enumerate(iter_result_items(result), start=1):
+ uri = item_value(item, "uri", "")
+ score = item_value(item, "score")
+ abstract = item_value(item, "abstract") or item_value(item, "overview") or ""
+ score_text = "" if score is None else f" score={score}"
+ lines.append(f"[{index}] {context_type}{score_text} {uri}\n{abstract}".strip())
+ if not lines:
+ return "No OpenViking contexts matched."
+ return "\n\n".join(lines)
+
+
+def _search_archive_payload(
+ payload: dict[str, Any],
+ query: str,
+ *,
+ max_matches: int,
+) -> dict[str, Any]:
+ tokens = [token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1]
+ sections = _archive_sections(payload)
+ matches: list[dict[str, str]] = []
+ for label, text in sections:
+ haystack = text.lower()
+ if tokens and not all(token in haystack for token in tokens):
+ continue
+ matches.append({"section": label, "snippet": _snippet(text, tokens)})
+ if len(matches) >= max_matches:
+ break
+ return {"matches": matches, "count": len(matches)}
+
+
+def _grep_session_history(
+ client: Any,
+ *,
+ session_id: str,
+ query: str,
+ max_matches: int,
+) -> dict[str, Any]:
+ history_uri = f"viking://session/{session_id}/history"
+ tokens = _archive_query_tokens(query)
+ try:
+ result = call_openviking(
+ client,
+ "grep",
+ uri=history_uri,
+ pattern=_archive_grep_pattern(query),
+ case_insensitive=True,
+ node_limit=None,
+ )
+ except Exception:
+ logger.debug("OpenViking archive history grep failed", exc_info=True)
+ return {"matches": [], "count": 0, "source": history_uri}
+ return _filter_grep_result(result, tokens=tokens, max_matches=max_matches, source=history_uri)
+
+
+def _match_count(result: dict[str, Any] | None) -> int:
+ if not result:
+ return 0
+ for key in ("count", "match_count"):
+ value = result.get(key)
+ if value is not None:
+ return int(value or 0)
+ matches = result.get("matches")
+ return len(matches) if isinstance(matches, list) else 0
+
+
+def _archive_grep_pattern(query: str) -> str:
+ tokens = _archive_query_tokens(query)
+ if not tokens:
+ return re.escape(query) or ".*"
+ return re.escape(tokens[0])
+
+
+def _archive_query_tokens(query: str) -> list[str]:
+ return [token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1]
+
+
+def _filter_grep_result(
+ result: Any,
+ *,
+ tokens: list[str],
+ max_matches: int,
+ source: str,
+) -> dict[str, Any]:
+ raw_matches = result.get("matches", []) if isinstance(result, dict) else result
+ matches: list[Any] = []
+ for match in raw_matches if isinstance(raw_matches, list) else []:
+ text = _grep_match_text(match).lower()
+ if tokens and not all(token in text for token in tokens):
+ continue
+ matches.append(match)
+ if len(matches) >= max_matches:
+ break
+
+ filtered = {"source": source}
+ if isinstance(result, dict):
+ filtered.update({key: value for key, value in result.items() if key != "matches"})
+ filtered["matches"] = matches
+ filtered["count"] = len(matches)
+ filtered["match_count"] = len(matches)
+ return filtered
+
+
+def _grep_match_text(match: Any) -> str:
+ if isinstance(match, dict):
+ return str(
+ match.get("content")
+ or match.get("line")
+ or match.get("text")
+ or match.get("snippet")
+ or ""
+ )
+ return str(match)
+
+
+def _archive_sections(payload: dict[str, Any]) -> list[tuple[str, str]]:
+ sections: list[tuple[str, str]] = []
+ if payload.get("overview"):
+ sections.append(
+ (f"archive:{payload.get('archive_id', 'archive')}:overview", payload["overview"])
+ )
+ if payload.get("abstract"):
+ sections.append(
+ (f"archive:{payload.get('archive_id', 'archive')}:abstract", payload["abstract"])
+ )
+ if payload.get("latest_archive_overview"):
+ sections.append(("latest_archive_overview", payload["latest_archive_overview"]))
+ for archive in payload.get("pre_archive_abstracts") or []:
+ sections.append(
+ (
+ f"archive:{archive.get('archive_id', 'archive')}:abstract",
+ str(archive.get("abstract") or ""),
+ )
+ )
+ for index, message in enumerate(payload.get("messages") or [], start=1):
+ text_parts = []
+ for part in message.get("parts") or []:
+ text_parts.extend(
+ str(part.get(key) or "")
+ for key in ("text", "abstract", "tool_output")
+ if part.get(key)
+ )
+ if text_parts:
+ sections.append((f"message:{index}:{message.get('role', '')}", "\n".join(text_parts)))
+ return sections
+
+
+def _snippet(text: str, tokens: list[str], *, radius: int = 240) -> str:
+ if not text:
+ return ""
+ lower = text.lower()
+ positions = [lower.find(token) for token in tokens if token and lower.find(token) >= 0]
+ start = max(0, min(positions) - radius) if positions else 0
+ end = min(len(text), start + radius * 2)
+ prefix = "..." if start else ""
+ suffix = "..." if end < len(text) else ""
+ return prefix + text[start:end] + suffix
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index 7634084d3..0a9446e50 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -159,12 +159,13 @@ class AsyncHTTPClient(BaseClient):
timeout: HTTP request timeout in seconds. Default 60.0.
extra_headers: Additional HTTP headers to send with requests. If not provided, reads from ovcli.conf.
"""
+ effective_user = user if user is not None else user_id
should_load_cli_config = (
url is None
or api_key is None
or agent_id is None
or account is None
- or user is None
+ or effective_user is None
or timeout == 60.0
or extra_headers is None
)
@@ -175,7 +176,7 @@ class AsyncHTTPClient(BaseClient):
api_key = api_key or cli_config.api_key
agent_id = agent_id or cli_config.agent_id
account = account or cli_config.account
- user = user or cli_config.user
+ effective_user = effective_user or cli_config.user
if timeout == 60.0: # only override default with config value
timeout = cli_config.timeout
if extra_headers is None:
@@ -189,7 +190,7 @@ class AsyncHTTPClient(BaseClient):
self._api_key = api_key
self._agent_id = agent_id
self._account = account
- self._user_id = user
+ self._user_id = effective_user
self._user = UserIdentifier.the_default_user()
self._timeout = timeout
self._extra_headers = extra_headers
diff --git a/pyproject.toml b/pyproject.toml
index d77dc483d..fe83ce06d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -178,6 +178,14 @@ benchmark = [
"datasets>=2.0.0",
"pandas>=2.0.0",
]
+langchain = [
+ "langchain-core>=1.0.0,<2.0.0",
+]
+langgraph = [
+ "langchain>=1.0.0,<2.0.0",
+ "langchain-core>=1.0.0,<2.0.0",
+ "langgraph>=1.0.0,<2.0.0",
+]
local-embed = [
"llama-cpp-python>=0.3.0",
]
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index 7374260f6..a4abda6b3 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -62,6 +62,36 @@ def test_async_http_client_explicit_values_override_ovcli_config(tmp_path, monke
assert client._timeout == 33.0
+async def test_async_http_client_user_id_sets_openviking_user_header(monkeypatch):
+ captured: dict[str, object] = {}
+
+ class FakeAsyncClient:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ monkeypatch.setattr("openviking_cli.client.http.httpx.AsyncClient", FakeAsyncClient)
+
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="explicit-key",
+ account="explicit-account",
+ user_id="explicit-user",
+ agent_id="explicit-agent",
+ timeout=33.0,
+ extra_headers={},
+ )
+ await client.initialize()
+
+ assert client._user_id == "explicit-user"
+ assert captured["headers"] == {
+ "X-API-Key": "explicit-key",
+ "X-OpenViking-Agent": "explicit-agent",
+ "X-OpenViking-Account": "explicit-account",
+ "X-OpenViking-User": "explicit-user",
+ }
+
+
def test_async_http_client_rejects_unknown_ovcli_field(tmp_path, monkeypatch):
config_path = tmp_path / "ovcli.conf"
config_path.write_text(json.dumps({"ur": "http://localhost:1933"}))
diff --git a/tests/integration/langchain_langgraph/conftest.py b/tests/integration/langchain_langgraph/conftest.py
new file mode 100644
index 000000000..ddc16e34e
--- /dev/null
+++ b/tests/integration/langchain_langgraph/conftest.py
@@ -0,0 +1,16 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+
+def pytest_configure() -> None:
+ env_path = Path(__file__).with_name(".env")
+ if not env_path.exists():
+ return
+ for raw_line in env_path.read_text(encoding="utf-8").splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, value = line.split("=", 1)
+ os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
diff --git a/tests/integration/langchain_langgraph/live_e2e.py b/tests/integration/langchain_langgraph/live_e2e.py
new file mode 100644
index 000000000..cab0667f8
--- /dev/null
+++ b/tests/integration/langchain_langgraph/live_e2e.py
@@ -0,0 +1,616 @@
+from __future__ import annotations
+
+import os
+import time
+import uuid
+from typing import Any
+
+import pytest
+
+pytest.importorskip("langchain")
+pytest.importorskip("langchain_core")
+pytest.importorskip("langgraph")
+pytest.importorskip("openai")
+
+from langchain.agents import create_agent
+from langchain_core.language_models.chat_models import SimpleChatModel
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
+from langchain_core.runnables import RunnableLambda
+from langchain_core.runnables.history import RunnableWithMessageHistory
+from langgraph.graph import END, START, StateGraph
+from langgraph.graph.message import add_messages
+from openai import OpenAI
+from typing_extensions import Annotated, TypedDict
+
+from openviking.integrations.langchain import (
+ OpenVikingChatMessageHistory,
+ OpenVikingContextMiddleware,
+ OpenVikingRetriever,
+ OpenVikingStore,
+ create_openviking_tools,
+ with_openviking_context,
+)
+from openviking.integrations.langchain.client import extract_message_text
+
+
+def test_true_live_langchain_context_backend_e2e():
+ _require_live_env()
+ client = _build_real_client()
+ session_id = f"langchain-live-e2e-{uuid.uuid4().hex}"
+ code = f"lc_live_{uuid.uuid4().hex[:10]}"
+
+ try:
+ _seed_session_context(
+ client,
+ session_id,
+ code,
+ framework="LangChain",
+ )
+ app = with_openviking_context(
+ RunnableLambda(_langchain_live_model),
+ client=client,
+ session_id=session_id,
+ token_budget=8_000,
+ )
+
+ first = app.invoke(
+ [
+ HumanMessage(
+ content=(
+ "What is the OpenViking LangChain live e2e exact code? "
+ "Answer only the exact code."
+ )
+ )
+ ]
+ )
+ assert code in first.content.lower()
+
+ second = app.invoke(
+ [
+ HumanMessage(
+ content=(
+ "Repeat the exact code from the previous answer. "
+ "Answer only the exact code."
+ )
+ )
+ ]
+ )
+ assert code in second.content.lower()
+
+ context = client.get_session_context(session_id, token_budget=8_000)
+ assert len(context["messages"]) >= 4
+ assert code in str(context).lower()
+
+ commit = client.commit_session(session_id)
+ _wait_for_commit_task(client, commit)
+ archive_id = _archive_id_from_commit(commit)
+ assert archive_id
+
+ tools = {tool.name: tool for tool in create_openviking_tools(client=client)}
+ archive_search = _invoke_until_contains(
+ lambda: tools["viking_archive_search"].invoke(
+ {"session_id": session_id, "query": code}
+ ),
+ code,
+ label="archive search",
+ )
+ archive_expand = _invoke_until_contains(
+ lambda: tools["viking_archive_expand"].invoke(
+ {"session_id": session_id, "archive_id": archive_id}
+ ),
+ code,
+ label="archive expand",
+ )
+
+ recovered = _call_llm(
+ [
+ {
+ "role": "system",
+ "content": "Return only the exact code present in the archive text.",
+ },
+ {
+ "role": "user",
+ "content": f"Archive search:\n{archive_search}\n\nArchive:\n{archive_expand}",
+ },
+ ]
+ )
+ assert code in recovered.lower()
+ finally:
+ _cleanup(client, session_id)
+
+
+def test_true_live_langchain_message_history_e2e():
+ _require_openviking_live_env()
+ client = _build_real_client()
+ session_id = f"langchain-history-live-e2e-{uuid.uuid4().hex}"
+ code = f"history_live_{uuid.uuid4().hex[:10]}"
+
+ def answer(messages: list[BaseMessage]) -> AIMessage:
+ text = "\n".join(extract_message_text(message.content) for message in messages)
+ if code in text.lower():
+ return AIMessage(content=code)
+ return AIMessage(content="missing")
+
+ app = RunnableWithMessageHistory(
+ RunnableLambda(answer),
+ lambda resolved_session_id: OpenVikingChatMessageHistory(
+ session_id=resolved_session_id,
+ client=client,
+ ),
+ )
+
+ try:
+ first = app.invoke(
+ [
+ HumanMessage(
+ content=(
+ f"Remember this OpenViking LangChain history exact code: {code}. "
+ "Answer only the exact code."
+ )
+ )
+ ],
+ config={"configurable": {"session_id": session_id}},
+ )
+ assert code in first.content.lower()
+
+ second = app.invoke(
+ [
+ HumanMessage(
+ content=(
+ "Repeat the OpenViking LangChain history exact code from the "
+ "conversation. Answer only the exact code."
+ )
+ )
+ ],
+ config={"configurable": {"session_id": session_id}},
+ )
+ assert code in second.content.lower()
+
+ context = client.get_session_context(session_id, token_budget=8_000)
+ assert [message["role"] for message in context["messages"]] == [
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ ]
+ assert code in str(context).lower()
+ finally:
+ _cleanup(client, session_id)
+
+
+def test_true_live_langgraph_middleware_e2e():
+ _require_live_env()
+ client = _build_real_client()
+ session_id = f"langgraph-live-e2e-{uuid.uuid4().hex}"
+ code = f"lg_live_{uuid.uuid4().hex[:10]}"
+
+ try:
+ _seed_session_context(
+ client,
+ session_id,
+ code,
+ framework="LangGraph",
+ )
+ app = _build_langgraph_live_app(
+ client=client,
+ session_id=session_id,
+ )
+
+ result = app.invoke(
+ {
+ "messages": [
+ HumanMessage(
+ content=(
+ "What is the OpenViking LangGraph live e2e exact code? "
+ "Answer only the exact code."
+ )
+ )
+ ]
+ }
+ )
+ answer = result["messages"][-1].content
+ assert code in answer.lower()
+
+ context = client.get_session_context(session_id, token_budget=8_000)
+ assert [message["role"] for message in context["messages"]] == [
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ ]
+ assert code in str(context).lower()
+
+ commit = client.commit_session(session_id)
+ _wait_for_commit_task(client, commit)
+ archive_id = _archive_id_from_commit(commit)
+ assert archive_id
+
+ tools = {tool.name: tool for tool in create_openviking_tools(client=client)}
+ archive_expand = _invoke_until_contains(
+ lambda: tools["viking_archive_expand"].invoke(
+ {"session_id": session_id, "archive_id": archive_id}
+ ),
+ code,
+ label="archive expand",
+ )
+ recovered = _call_llm(
+ [
+ {
+ "role": "system",
+ "content": "Return only the exact code present in the archive text.",
+ },
+ {"role": "user", "content": archive_expand},
+ ]
+ )
+ assert code in recovered.lower()
+ finally:
+ _cleanup(client, session_id)
+
+
+def test_true_live_langgraph_create_agent_middleware_e2e():
+ _require_live_env()
+ client = _build_real_client()
+ session_id = f"langgraph-agent-live-e2e-{uuid.uuid4().hex}"
+ code = f"lg_agent_live_{uuid.uuid4().hex[:10]}"
+
+ try:
+ _seed_session_context(
+ client,
+ session_id,
+ code,
+ framework="LangGraph create_agent",
+ )
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ session_id_resolver=lambda _state, _runtime: session_id,
+ token_budget=8_000,
+ commit_on_after_agent=False,
+ include_active_messages=True,
+ )
+ agent = create_agent(
+ model=_LiveOpenAIChatModel(
+ instruction=(
+ "You are validating OpenViking with LangGraph create_agent "
+ "middleware. Return only the exact lg_agent_live_* code if one "
+ "appears in the context or conversation."
+ )
+ ),
+ tools=[],
+ middleware=[middleware],
+ )
+
+ result = agent.invoke(
+ {
+ "messages": [
+ HumanMessage(
+ content=(
+ "What is the OpenViking LangGraph create_agent live e2e "
+ "exact code? Answer only the exact code."
+ )
+ )
+ ]
+ },
+ config={"configurable": {"thread_id": session_id}},
+ )
+ answer = extract_message_text(result["messages"][-1].content)
+ assert code in answer.lower()
+
+ context = client.get_session_context(session_id, token_budget=8_000)
+ assert [message["role"] for message in context["messages"]] == [
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ ]
+ assert code in str(context).lower()
+ finally:
+ _cleanup(client, session_id)
+
+
+def test_true_live_retriever_and_langgraph_store_e2e():
+ _require_openviking_live_env()
+ client = _build_real_client()
+ root_uri = f"viking://user/memories/langgraph_store_live_{uuid.uuid4().hex}"
+ code = f"store_live_{uuid.uuid4().hex[:10]}"
+
+ try:
+ store = OpenVikingStore(
+ client=client,
+ root_uri=root_uri,
+ wait=True,
+ timeout=float(os.environ.get("OPENVIKING_LIVE_INDEX_TIMEOUT", "180")),
+ )
+ store.put(
+ ("users", "ada"),
+ "preferences",
+ {
+ "framework": "langgraph",
+ "deployment_color": "azure",
+ "exact_code": code,
+ "note": f"OpenViking live store and retriever validation code {code}.",
+ },
+ )
+
+ item = store.get(("users", "ada"), "preferences")
+ assert item is not None
+ assert item.value["exact_code"] == code
+
+ store_search = _invoke_until_contains(
+ lambda: "\n".join(
+ str(result.value) for result in store.search(("users",), query=code, limit=5)
+ ),
+ code,
+ label="LangGraph store semantic search",
+ )
+ assert code in store_search.lower()
+
+ retriever = OpenVikingRetriever(
+ client=client,
+ target_uri=f"{root_uri}/index",
+ limit=5,
+ content_mode="read",
+ )
+ retrieved = _invoke_until_contains(
+ lambda: "\n".join(
+ f"{doc.page_content}\n{doc.metadata}" for doc in retriever.invoke(code)
+ ),
+ code,
+ label="LangChain retriever live HTTP search",
+ )
+ assert code in retrieved.lower()
+ finally:
+ _cleanup_uri(client, root_uri)
+
+
+def _langchain_live_model(messages: list[BaseMessage]) -> AIMessage:
+ answer = _call_llm(
+ _langchain_messages_to_openai(
+ messages,
+ instruction=(
+ "You are validating OpenViking as a LangChain context backend. "
+ "Return only the exact lc_live_* code if one appears in the context "
+ "or conversation."
+ ),
+ )
+ )
+ return AIMessage(content=answer)
+
+
+class _LiveOpenAIChatModel(SimpleChatModel):
+ instruction: str
+
+ @property
+ def _llm_type(self) -> str:
+ return "openviking-live-openai-compatible"
+
+ def _call(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: Any = None,
+ **kwargs: Any,
+ ) -> str:
+ return _call_llm(_langchain_messages_to_openai(messages, instruction=self.instruction))
+
+
+class _LiveGraphState(TypedDict, total=False):
+ messages: Annotated[list, add_messages]
+
+
+def _build_langgraph_live_app(*, client: Any, session_id: str):
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ token_budget=8_000,
+ commit_on_after_agent=False,
+ include_active_messages=True,
+ )
+
+ class Runtime:
+ config = {"configurable": {"thread_id": session_id}}
+
+ def model_node(state: _LiveGraphState) -> _LiveGraphState:
+ current_messages = list(state["messages"])
+
+ class Request:
+ state = {}
+ runtime = Runtime()
+ messages = current_messages
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get(
+ "system_message",
+ self.system_message,
+ )
+ return new_request
+
+ def handler(request):
+ messages: list[BaseMessage] = []
+ if request.system_message is not None:
+ messages.append(request.system_message)
+ messages.extend(request.messages)
+ answer = _call_llm(
+ _langchain_messages_to_openai(
+ messages,
+ instruction=(
+ "You are validating OpenViking as LangGraph middleware. "
+ "Return only the exact lg_live_* code if one appears in the "
+ "context or conversation."
+ ),
+ )
+ )
+ return AIMessage(content=answer)
+
+ response = middleware.wrap_model_call(Request(), handler)
+ all_messages = current_messages + [response]
+ middleware.after_agent(
+ {
+ "messages": all_messages,
+ },
+ Runtime(),
+ )
+ return {"messages": [response]}
+
+ graph = StateGraph(_LiveGraphState)
+ graph.add_node("model", model_node)
+ graph.add_edge(START, "model")
+ graph.add_edge("model", END)
+ return graph.compile()
+
+
+def _langchain_messages_to_openai(
+ messages: list[BaseMessage],
+ *,
+ instruction: str,
+) -> list[dict[str, str]]:
+ converted = [{"role": "system", "content": instruction}]
+ for message in messages:
+ content = extract_message_text(message.content)
+ if isinstance(message, SystemMessage):
+ converted.append({"role": "system", "content": content})
+ elif isinstance(message, HumanMessage):
+ converted.append({"role": "user", "content": content})
+ elif isinstance(message, AIMessage):
+ converted.append({"role": "assistant", "content": content})
+ return converted
+
+
+def _call_llm(messages: list[dict[str, str]]) -> str:
+ client = OpenAI(
+ api_key=os.environ["ARK_API_KEY"],
+ base_url=os.environ.get("ARK_BASE_URL", "https://ark-cn-beijing.bytedance.net/api/v3"),
+ )
+ completion = client.chat.completions.create(
+ model=os.environ.get("ARK_MODEL", "doubao-seed-2-0-code-preview-260215"),
+ messages=messages,
+ )
+ return completion.choices[0].message.content or ""
+
+
+def _require_live_env() -> None:
+ _require_openviking_live_env()
+ if not os.environ.get("ARK_API_KEY"):
+ pytest.skip("ARK_API_KEY is required for live e2e")
+
+
+def _require_openviking_live_env() -> None:
+ if os.environ.get("OPENVIKING_URL"):
+ return
+ try:
+ from openviking_cli.utils.config.ovcli_config import load_ovcli_config
+
+ cli_config = load_ovcli_config()
+ except Exception as exc:
+ pytest.skip(f"OpenViking live connection config is unavailable: {exc}")
+ if cli_config is None or not cli_config.url:
+ pytest.skip("OPENVIKING_URL or ovcli.conf url is required for live e2e")
+
+
+def _build_real_client():
+ from openviking.client import SyncHTTPClient
+
+ client = SyncHTTPClient(
+ url=os.environ.get("OPENVIKING_URL") or None,
+ api_key=os.environ.get("OPENVIKING_API_KEY"),
+ user_id=os.environ.get("OPENVIKING_USER_ID"),
+ agent_id=os.environ.get("OPENVIKING_AGENT_ID"),
+ )
+ client.initialize()
+ return client
+
+
+def _seed_session_context(client, session_id: str, code: str, *, framework: str) -> None:
+ client.create_session(session_id=session_id)
+ client.add_message(
+ session_id=session_id,
+ role="user",
+ parts=[
+ {
+ "type": "text",
+ "text": (
+ f"Remember this OpenViking {framework} live e2e exact code: {code}. "
+ "This is durable session context for the next agent turn."
+ ),
+ }
+ ],
+ )
+ client.add_message(
+ session_id=session_id,
+ role="assistant",
+ parts=[
+ {
+ "type": "text",
+ "text": f"Stored the OpenViking {framework} live e2e exact code: {code}.",
+ }
+ ],
+ )
+
+
+def _cleanup(client, session_id: str) -> None:
+ try:
+ client.delete_session(session_id)
+ except Exception:
+ pass
+
+
+def _cleanup_uri(client, uri: str) -> None:
+ try:
+ client.rm(uri, recursive=True)
+ except Exception:
+ pass
+
+
+def _archive_id_from_commit(commit: dict[str, object]) -> str | None:
+ archive_id = commit.get("archive_id")
+ if archive_id:
+ return str(archive_id)
+ archive_uri = str(commit.get("archive_uri") or "").rstrip("/")
+ if not archive_uri:
+ return None
+ return archive_uri.rsplit("/", 1)[-1]
+
+
+def _invoke_until_contains(
+ invoke,
+ expected: str,
+ *,
+ label: str,
+) -> str:
+ timeout = float(os.environ.get("OPENVIKING_LIVE_ARCHIVE_TIMEOUT", "60"))
+ deadline = time.monotonic() + timeout
+ last_error: Exception | None = None
+ last_value = ""
+ while time.monotonic() < deadline:
+ try:
+ value = str(invoke())
+ except Exception as exc:
+ last_error = exc
+ else:
+ last_value = value
+ if expected in value.lower():
+ return value
+ time.sleep(0.5)
+ pytest.fail(
+ f"OpenViking {label} did not contain {expected!r}; "
+ f"last_error={last_error!r}; last_value={last_value[:1000]!r}"
+ )
+
+
+def _wait_for_commit_task(client, commit: dict[str, object]) -> None:
+ assert commit.get("archived") is True
+ task_id = commit.get("task_id")
+ assert task_id, f"OpenViking commit did not start extraction: {commit}"
+ timeout = float(os.environ.get("OPENVIKING_LIVE_COMMIT_TIMEOUT", "180"))
+ deadline = time.monotonic() + timeout
+ last_task = None
+ while time.monotonic() < deadline:
+ task = client.get_task(str(task_id))
+ last_task = task
+ if task and task.get("status") == "completed":
+ return
+ if task and task.get("status") == "failed":
+ pytest.fail(f"OpenViking commit task failed: {task}")
+ time.sleep(0.5)
+ pytest.fail(f"OpenViking commit task did not complete: {task_id}; last_task={last_task}")
diff --git a/tests/integration/langchain_langgraph/test_smoke.py b/tests/integration/langchain_langgraph/test_smoke.py
new file mode 100644
index 000000000..b955dcf2d
--- /dev/null
+++ b/tests/integration/langchain_langgraph/test_smoke.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import runpy
+from pathlib import Path
+
+import pytest
+
+pytest.importorskip("langchain_core")
+pytest.importorskip("langgraph")
+
+PROJECT_ROOT = Path(__file__).resolve().parents[3]
+
+
+def test_langchain_quick_app_runs():
+ namespace = runpy.run_path(
+ str(PROJECT_ROOT / "examples/langchain-langgraph/langchain/rag/quick_app.py"),
+ run_name="openviking_langchain_quick",
+ )
+
+ answer = namespace["main"]()
+ assert "azure" in answer.lower()
+
+
+def test_langchain_context_backend_quick_app_runs():
+ namespace = runpy.run_path(
+ str(PROJECT_ROOT / "examples/langchain-langgraph/langchain/context-backend/quick_app.py"),
+ run_name="openviking_langchain_context_backend_quick",
+ )
+
+ answer = namespace["main"]()
+ assert "openviking" in answer.lower()
+ assert "azure" in answer.lower()
+
+
+def test_langchain_message_history_quick_app_runs():
+ namespace = runpy.run_path(
+ str(PROJECT_ROOT / "examples/langchain-langgraph/langchain/message-history/quick_app.py"),
+ run_name="openviking_langchain_message_history_quick",
+ )
+
+ answer = namespace["main"]()
+ assert "history" in answer.lower()
+ assert "azure" in answer.lower()
+
+
+def test_langgraph_quick_app_runs():
+ namespace = runpy.run_path(
+ str(PROJECT_ROOT / "examples/langchain-langgraph/langgraph/agent/quick_app.py"),
+ run_name="openviking_langgraph_quick",
+ )
+
+ answer = namespace["main"]()
+ assert "openviking" in answer.lower()
+ assert "azure" in answer.lower()
+
+
+def test_langgraph_middleware_quick_app_runs():
+ namespace = runpy.run_path(
+ str(PROJECT_ROOT / "examples/langchain-langgraph/langgraph/middleware/quick_app.py"),
+ run_name="openviking_langgraph_middleware_quick",
+ )
+
+ answer = namespace["main"]()
+ assert "middleware" in answer.lower()
+ assert "azure" in answer.lower()
diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.py
new file mode 100644
index 000000000..3590aa9d6
--- /dev/null
+++ b/tests/unit/test_langchain_integration.py
@@ -0,0 +1,1143 @@
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("langchain_core")
+pytest.importorskip("langgraph")
+
+from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
+from langchain_core.runnables import RunnableLambda
+from langgraph.store.base import PutOp
+
+from openviking.integrations.langchain import (
+ InMemoryOpenVikingClient,
+ OpenVikingChatMessageHistory,
+ OpenVikingCommitPolicy,
+ OpenVikingContextMiddleware,
+ OpenVikingRetriever,
+ OpenVikingSessionContextAssembler,
+ OpenVikingStore,
+ create_openviking_tools,
+ with_openviking_context,
+)
+from openviking.integrations.langchain.client import (
+ OpenVikingConnection,
+ ensure_client,
+ maybe_commit_session,
+)
+from openviking.integrations.langchain.history import (
+ langchain_message_to_openviking,
+ openviking_message_to_langchain,
+)
+from openviking.integrations.langchain.middleware import _message_signature
+from openviking.integrations.langchain.tools import _archive_grep_pattern
+
+
+def test_retriever_returns_langchain_documents():
+ client = InMemoryOpenVikingClient(
+ {
+ "viking://user/memories/preferences.md": "The user prefers azure deploys.",
+ "viking://resources/runbooks/release.md": "Release notes mention LangChain.",
+ }
+ )
+ retriever = OpenVikingRetriever(
+ client=client,
+ target_uri=["viking://user/memories", "viking://resources"],
+ limit=3,
+ )
+
+ docs = retriever.invoke("azure LangChain")
+
+ assert {doc.metadata["openviking_uri"] for doc in docs} == {
+ "viking://resources/runbooks/release.md",
+ "viking://user/memories/preferences.md",
+ }
+ assert all(doc.page_content for doc in docs)
+
+
+def test_create_openviking_tools_exposes_common_viking_primitives():
+ client = InMemoryOpenVikingClient(
+ {"viking://user/memories/profile.md": "The user likes LangGraph agents."}
+ )
+ tools = create_openviking_tools(client=client, profile="agent")
+ names = {tool.name for tool in tools}
+
+ assert {
+ "viking_find",
+ "viking_search",
+ "viking_browse",
+ "viking_read",
+ "viking_grep",
+ "viking_archive_search",
+ "viking_archive_expand",
+ "viking_store",
+ "viking_add_resource",
+ "viking_add_skill",
+ "viking_health",
+ }.issubset(names)
+ assert "viking_forget" not in names
+
+ find_tool = next(tool for tool in tools if tool.name == "viking_find")
+ assert "viking://user/memories/profile.md" in find_tool.invoke(
+ {"query": "LangGraph", "limit": 2}
+ )
+
+ store_tool = next(tool for tool in tools if tool.name == "viking_store")
+ stored = store_tool.invoke(
+ {
+ "messages": [
+ {"role": "user", "content": "Remember that azure is preferred."},
+ {"role": "assistant", "content": "Noted."},
+ ],
+ "session_id": "test-session",
+ "commit": False,
+ }
+ )
+ assert '"messages_added":2' in stored
+ assert len(client.sessions["test-session"]) == 2
+ assert client.sessions["test-session"][0]["parts"][0]["text"] == (
+ "Remember that azure is preferred."
+ )
+
+
+def test_create_openviking_tools_profiles_control_destructive_tools():
+ client = InMemoryOpenVikingClient()
+
+ retrieval_names = {
+ tool.name for tool in create_openviking_tools(client=client, profile="retrieval")
+ }
+ assert "viking_store" not in retrieval_names
+ assert "viking_add_resource" not in retrieval_names
+ assert "viking_add_skill" not in retrieval_names
+ assert "viking_forget" not in retrieval_names
+
+ admin_names = {tool.name for tool in create_openviking_tools(client=client, profile="admin")}
+ assert "viking_store" in admin_names
+ assert "viking_add_resource" in admin_names
+ assert "viking_add_skill" in admin_names
+ assert "viking_forget" in admin_names
+
+ explicit_names = {
+ tool.name
+ for tool in create_openviking_tools(
+ client=client,
+ tool_names=["viking_find", "viking_store"],
+ )
+ }
+ assert explicit_names == {"viking_find", "viking_store"}
+
+
+def test_openviking_tools_read_l0_l1_l2_content_modes():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/release.md": "Release runbook full details."}
+ )
+ tools = {tool.name: tool for tool in create_openviking_tools(client=client)}
+ read_tool = tools["viking_read"]
+
+ abstract = read_tool.invoke(
+ {
+ "uris": "viking://resources/runbooks/release.md",
+ "content_mode": "abstract",
+ }
+ )
+ overview = read_tool.invoke(
+ {
+ "uris": "viking://resources/runbooks/release.md",
+ "content_mode": "overview",
+ }
+ )
+ full = read_tool.invoke(
+ {
+ "uris": "viking://resources/runbooks/release.md",
+ "content_mode": "read",
+ }
+ )
+
+ assert '"content_mode": "abstract"' in abstract
+ assert '"content_mode": "overview"' in overview
+ assert '"content_mode": "read"' in full
+ assert "Release runbook full details." in full
+
+
+def test_ensure_client_defaults_to_http_client(monkeypatch):
+ created = {}
+
+ class FakeHTTPClient:
+ def __init__(self, **kwargs):
+ created.update(kwargs)
+ self._initialized = False
+
+ def initialize(self):
+ self._initialized = True
+
+ import openviking.client as client_module
+
+ monkeypatch.setattr(client_module, "SyncHTTPClient", FakeHTTPClient)
+
+ client = ensure_client(
+ OpenVikingConnection(
+ api_key="test-key",
+ user_id="test-user",
+ agent_id="test-agent",
+ )
+ )
+
+ assert isinstance(client, FakeHTTPClient)
+ assert client._initialized is True
+ assert created["api_key"] == "test-key"
+ assert created["user_id"] == "test-user"
+ assert created["agent_id"] == "test-agent"
+ assert created["url"] is None
+
+
+def test_chat_message_history_preserves_tool_parts():
+ client = InMemoryOpenVikingClient()
+ history = OpenVikingChatMessageHistory(session_id="history-session", client=client)
+
+ history.add_messages(
+ [
+ HumanMessage(content="Find deployment notes."),
+ AIMessage(
+ content="Searching.",
+ tool_calls=[
+ {
+ "id": "call-1",
+ "name": "viking_find",
+ "args": {"query": "deployment"},
+ }
+ ],
+ ),
+ ToolMessage(
+ content="Azure deployment notes found.",
+ tool_call_id="call-1",
+ name="viking_find",
+ ),
+ ]
+ )
+
+ stored = client.sessions["history-session"]
+ assert stored[1]["parts"][1]["type"] == "tool"
+ assert stored[2]["parts"][0]["tool_output"] == "Azure deployment notes found."
+
+ restored = history.messages
+ restored_ai_messages = [message for message in restored if isinstance(message, AIMessage)]
+ restored_tool_messages = [message for message in restored if isinstance(message, ToolMessage)]
+ assert len(restored_ai_messages) == 1
+ assert len(restored_ai_messages[0].tool_calls) == 1
+ assert len(restored_tool_messages) == 1
+
+
+def test_openviking_tool_result_restores_without_duplicate_ai_tool_call():
+ restored = openviking_message_to_langchain(
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "tool",
+ "tool_id": "call-1",
+ "tool_name": "viking_find",
+ "tool_output": "Azure deployment notes found.",
+ "tool_status": "completed",
+ }
+ ],
+ }
+ )
+
+ assert len(restored) == 1
+ assert isinstance(restored[0], ToolMessage)
+ assert restored[0].tool_call_id == "call-1"
+
+
+def test_empty_human_message_uses_empty_text_part():
+ payloads = langchain_message_to_openviking(HumanMessage(content=""))
+
+ assert payloads == [{"role": "user", "parts": [{"type": "text", "text": ""}]}]
+
+
+def test_system_messages_are_never_persisted_to_openviking_history():
+ payloads = langchain_message_to_openviking(
+ SystemMessage(content="Never persist runtime policy."),
+ persist_system_messages=True,
+ )
+
+ assert payloads == []
+
+
+def test_session_context_assembler_uses_archive_active_messages_and_recall():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/deploy.md": "Azure deployments use OpenViking context."}
+ )
+ client.add_message("assembler-session", "user", content="Earlier user turn")
+ client.add_message("assembler-session", "assistant", content="Earlier assistant turn")
+ client.commit_session("assembler-session")
+ client.add_message("assembler-session", "user", content="Active turn")
+
+ assembler = OpenVikingSessionContextAssembler(
+ client=client,
+ target_uri="viking://resources",
+ )
+ assembled = assembler.assemble(session_id="assembler-session", query="azure context")
+
+ assert client.search_calls[-1]["session_id"] == "assembler-session"
+ assert "Session archive overview" in assembled.block
+ assert "Earlier user turn" in assembled.block
+ assert "Active session messages" in assembled.block
+ assert "Active turn" in assembled.block
+ assert "Azure deployments" in assembled.block
+ assert assembled.context_parts[0]["type"] == "context"
+
+
+def test_with_openviking_context_wraps_runnable_with_history():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/deploy.md": "Azure is the deployment color."}
+ )
+
+ def answer(messages):
+ assert "Azure is the deployment color" in messages[0].content
+ return AIMessage(content="OpenViking says azure.")
+
+ runnable = with_openviking_context(
+ RunnableLambda(answer),
+ client=client,
+ session_id="wrapped-session",
+ target_uri="viking://resources",
+ )
+
+ result = runnable.invoke(
+ [HumanMessage(content="What deployment color?")],
+ )
+
+ assert result.content == "OpenViking says azure."
+ assert len(client.sessions["wrapped-session"]) == 2
+ assert any(part["type"] == "context" for part in client.sessions["wrapped-session"][1]["parts"])
+
+
+def test_with_openviking_context_dynamic_session_requires_config():
+ client = InMemoryOpenVikingClient()
+ runnable = with_openviking_context(
+ RunnableLambda(lambda _messages: AIMessage(content="ok")),
+ client=client,
+ )
+
+ with pytest.raises(ValueError, match="Missing keys .*session_id"):
+ runnable.invoke([HumanMessage(content="hi")])
+
+
+def test_with_openviking_context_dynamic_session_uses_configured_session():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/deploy.md": "Azure dynamic context."}
+ )
+
+ def answer(messages):
+ assert "Azure dynamic context" in messages[0].content
+ return AIMessage(content="dynamic ok")
+
+ runnable = with_openviking_context(
+ RunnableLambda(answer),
+ client=client,
+ target_uri="viking://resources",
+ )
+
+ result = runnable.invoke(
+ [HumanMessage(content="What dynamic context?")],
+ config={"configurable": {"session_id": "dynamic-session"}},
+ )
+
+ assert result.content == "dynamic ok"
+ assert client.search_calls[-1]["session_id"] == "dynamic-session"
+ assert len(client.sessions["dynamic-session"]) == 2
+
+
+def test_with_openviking_context_dynamic_session_can_use_thread_id_key():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/deploy.md": "Thread dynamic context."}
+ )
+ runnable = with_openviking_context(
+ RunnableLambda(lambda _messages: AIMessage(content="thread ok")),
+ client=client,
+ target_uri="viking://resources",
+ session_id_config_key="thread_id",
+ )
+
+ result = runnable.invoke(
+ [HumanMessage(content="What thread context?")],
+ config={"configurable": {"thread_id": "thread-session"}},
+ )
+
+ assert result.content == "thread ok"
+ assert client.search_calls[-1]["session_id"] == "thread-session"
+ assert len(client.sessions["thread-session"]) == 2
+
+
+def test_with_openviking_context_clears_pending_context_after_failure():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/deploy.md": "Azure failure context."}
+ )
+ calls = {"count": 0}
+
+ def answer(_messages):
+ calls["count"] += 1
+ if calls["count"] == 1:
+ raise RuntimeError("synthetic model failure")
+ return AIMessage(content="Recovered.")
+
+ runnable = with_openviking_context(
+ RunnableLambda(answer),
+ client=client,
+ session_id="failure-session",
+ target_uri="viking://resources",
+ )
+
+ with pytest.raises(RuntimeError, match="synthetic model failure"):
+ runnable.invoke([HumanMessage(content="What deployment color?")])
+
+ client.records.clear()
+ result = runnable.invoke([HumanMessage(content="No context this time.")])
+
+ assert result.content == "Recovered."
+ assistant_parts = client.sessions["failure-session"][-1]["parts"]
+ assert not any(part["type"] == "context" for part in assistant_parts)
+
+
+def test_with_openviking_context_dynamic_error_clears_pending_context():
+ client = InMemoryOpenVikingClient(
+ {"viking://resources/runbooks/deploy.md": "Azure dynamic failure context."}
+ )
+ calls = {"count": 0}
+
+ def answer(_messages):
+ calls["count"] += 1
+ if calls["count"] == 1:
+ raise RuntimeError("synthetic dynamic failure")
+ return AIMessage(content="recovered")
+
+ runnable = with_openviking_context(
+ RunnableLambda(answer),
+ client=client,
+ target_uri="viking://resources",
+ )
+
+ with pytest.raises(RuntimeError, match="synthetic dynamic failure"):
+ runnable.invoke(
+ [HumanMessage(content="What dynamic failure context?")],
+ config={"configurable": {"session_id": "dynamic-failure-session"}},
+ )
+
+ client.records.clear()
+ result = runnable.invoke(
+ [HumanMessage(content="No context now.")],
+ config={"configurable": {"session_id": "dynamic-failure-session"}},
+ )
+
+ assert result.content == "recovered"
+ assistant_parts = client.sessions["dynamic-failure-session"][-1]["parts"]
+ assert not any(part["type"] == "context" for part in assistant_parts)
+
+
+def test_archive_tools_search_and_expand_committed_session():
+ client = InMemoryOpenVikingClient()
+ client.add_message("archive-session", "user", content="Remember cobalt archive detail.")
+ client.add_message("archive-session", "assistant", content="Cobalt archive detail stored.")
+ commit = client.commit_session("archive-session")
+ assert commit["archive_id"] == "archive_001"
+
+ tools = {tool.name: tool for tool in create_openviking_tools(client=client)}
+ searched = tools["viking_archive_search"].invoke(
+ {
+ "session_id": "archive-session",
+ "archive_id": "archive_001",
+ "query": "cobalt archive",
+ }
+ )
+ expanded = tools["viking_archive_expand"].invoke(
+ {"session_id": "archive-session", "archive_id": "archive_001"}
+ )
+
+ assert "Cobalt archive detail" in searched
+ assert "archive_001" in expanded
+ assert "Remember cobalt archive detail" in expanded
+
+
+def test_archive_search_without_archive_id_searches_raw_history():
+ client = InMemoryOpenVikingClient()
+ client.add_message("archive-search-session", "user", content="Hidden cobalt archive detail.")
+ commit = client.commit_session("archive-search-session")
+ assert commit["archive_id"] == "archive_001"
+ client.archives["archive-search-session"][0]["overview"] = "compressed summary"
+ client.archives["archive-search-session"][0]["abstract"] = "compressed summary"
+
+ tools = {tool.name: tool for tool in create_openviking_tools(client=client)}
+ searched = tools["viking_archive_search"].invoke(
+ {
+ "session_id": "archive-search-session",
+ "query": "hidden cobalt archive",
+ }
+ )
+
+ assert "Hidden cobalt archive detail" in searched
+ assert "viking://session/archive-search-session/history" in searched
+
+
+def test_archive_grep_pattern_uses_backend_safe_token_regex():
+ assert _archive_grep_pattern("hidden cobalt archive") == "hidden"
+ assert "(?=" not in _archive_grep_pattern("hidden cobalt archive")
+
+
+def test_commit_policy_commits_when_threshold_is_reached():
+ client = InMemoryOpenVikingClient()
+ history = OpenVikingChatMessageHistory(
+ session_id="commit-session",
+ client=client,
+ commit_policy=OpenVikingCommitPolicy(
+ mode="pending_tokens",
+ pending_token_threshold=1,
+ ),
+ )
+
+ history.add_messages(
+ [
+ HumanMessage(content="first message"),
+ AIMessage(content="second message"),
+ ]
+ )
+
+ assert client.archives["commit-session"]
+ assert client.sessions["commit-session"] == []
+
+
+def test_history_is_empty_after_commit_archives_tool_messages():
+ client = InMemoryOpenVikingClient()
+ history = OpenVikingChatMessageHistory(
+ session_id="orphan-tool-session",
+ client=client,
+ commit_policy=OpenVikingCommitPolicy(
+ mode="pending_tokens",
+ pending_token_threshold=1,
+ ),
+ )
+
+ history.add_messages(
+ [
+ HumanMessage(content="Find release notes."),
+ AIMessage(
+ content="Searching.",
+ tool_calls=[
+ {
+ "id": "call-orphan",
+ "name": "viking_find",
+ "args": {"query": "release"},
+ }
+ ],
+ ),
+ ToolMessage(
+ content="Release notes found.",
+ tool_call_id="call-orphan",
+ name="viking_find",
+ ),
+ ]
+ )
+
+ assert client.sessions["orphan-tool-session"] == []
+ assert history.messages == []
+
+
+def test_chat_message_history_clear_raises_when_delete_fails():
+ class DeleteDeniedClient(InMemoryOpenVikingClient):
+ def delete_session(self, session_id: str) -> None:
+ raise PermissionError(f"cannot delete {session_id}")
+
+ client = DeleteDeniedClient()
+ history = OpenVikingChatMessageHistory(session_id="clear-session", client=client)
+ history.add_messages([HumanMessage(content="private stale context")])
+
+ with pytest.raises(PermissionError, match="cannot delete clear-session"):
+ history.clear()
+
+ assert len(client.sessions["clear-session"]) == 1
+
+
+def test_langgraph_store_round_trip_and_semantic_search():
+ client = InMemoryOpenVikingClient()
+ store = OpenVikingStore(client=client)
+
+ store.put(
+ ("users", "ada"),
+ "preferences",
+ {"color": "azure", "framework": "langgraph", "nested": {"rank": 3}},
+ )
+ store.put(("users", "ada"), "profile", {"color": "teal", "framework": "langgraph"})
+ store.put(
+ ("users", "ada"),
+ "bad-rank",
+ {"color": "navy", "framework": "langgraph", "nested": {"rank": "high"}},
+ )
+
+ item = store.get(("users", "ada"), "preferences")
+ assert item.value["framework"] == "langgraph"
+
+ filtered = store.search(("users",), filter={"nested.rank": {"$gte": 3}}, limit=5)
+ assert [item.key for item in filtered] == ["preferences"]
+
+ bad_in_filter = store.search(("users",), filter={"framework": {"$in": 3}}, limit=5)
+ assert bad_in_filter == []
+
+ semantic = store.search(("users",), query="azure", limit=5)
+ assert semantic[0].namespace == ("users", "ada")
+ assert semantic[0].value["color"] == "azure"
+
+ assert store.list_namespaces(prefix=("users",)) == [("users", "ada")]
+
+
+def test_langgraph_store_rejects_ttl_writes():
+ store = OpenVikingStore(client=InMemoryOpenVikingClient())
+
+ with pytest.raises(NotImplementedError, match="TTL is not supported"):
+ store.put(("users", "ada"), "temporary", {"note": "expires"}, ttl=60)
+
+
+def test_langgraph_store_batch_rejects_ttl_writes():
+ store = OpenVikingStore(client=InMemoryOpenVikingClient())
+
+ with pytest.raises(NotImplementedError, match="TTL is not supported"):
+ store.batch(
+ [
+ PutOp(
+ namespace=("users", "ada"),
+ key="temporary",
+ value={"note": "expires"},
+ ttl=60,
+ )
+ ]
+ )
+
+
+ ("root_uri", "shorthand_prefix", "canonical_prefix"),
+ [
+ (
+ "viking://user/memories/langgraph_store",
+ "viking://user/memories",
+ "viking://user/default/memories",
+ ),
+ (
+ "viking://user/memories/langgraph_store",
+ "viking://user/memories",
+ "viking://user/default/agent/support/memories",
+ ),
+ (
+ "viking://agent/memories/langgraph_store",
+ "viking://agent/memories",
+ "viking://agent/support/memories",
+ ),
+ (
+ "viking://agent/memories/langgraph_store",
+ "viking://agent/memories",
+ "viking://agent/support/user/default/memories",
+ ),
+ (
+ "viking://agent/skills/langgraph_store",
+ "viking://agent/skills",
+ "viking://agent/support/user/default/skills",
+ ),
+ ],
+ ids=[
+ "user-memory",
+ "user-memory-isolated-by-agent",
+ "agent-memory",
+ "agent-memory-isolated-by-user",
+ "agent-skills-isolated-by-user",
+ ],
+)
+def test_langgraph_store_accepts_canonical_result_uris_for_shorthand_root(
+ root_uri,
+ shorthand_prefix,
+ canonical_prefix,
+):
+ class CanonicalizingClient(InMemoryOpenVikingClient):
+ def _canonicalize(self, value):
+ if isinstance(value, str):
+ return value.replace(f"{shorthand_prefix}/", f"{canonical_prefix}/", 1)
+ if isinstance(value, list):
+ return [self._canonicalize(item) for item in value]
+ return value
+
+ def write(self, uri, content, mode="replace", **kwargs):
+ return super().write(self._canonicalize(uri), content, mode=mode, **kwargs)
+
+ def read(self, uri, *args, **kwargs):
+ return super().read(self._canonicalize(uri), *args, **kwargs)
+
+ def glob(self, pattern, uri="viking://"):
+ return super().glob(pattern, self._canonicalize(uri))
+
+ def find(self, query, target_uri="", **kwargs):
+ return super().find(query, self._canonicalize(target_uri), **kwargs)
+
+ def rm(self, uri, recursive=False):
+ return super().rm(self._canonicalize(uri), recursive=recursive)
+
+ client = CanonicalizingClient()
+ store = OpenVikingStore(client=client, root_uri=root_uri)
+
+ store.put(("users", "ada"), "preferences", {"color": "azure"})
+
+ semantic = store.search(("users",), query="azure", limit=5)
+
+ assert semantic[0].namespace == ("users", "ada")
+ assert semantic[0].key == "preferences"
+ assert semantic[0].value["color"] == "azure"
+
+
+def test_langgraph_store_ignores_unrelated_canonical_result_uris():
+ store = OpenVikingStore(
+ client=InMemoryOpenVikingClient(),
+ root_uri="viking://user/memories/langgraph_store",
+ )
+
+ assert (
+ store._parse_index_uri(
+ "viking://user/default/agent/support/memories/other_store/index/users/ada.md"
+ )
+ is None
+ )
+ assert (
+ store._parse_index_uri(
+ "viking://agent/support/user/default/memories/langgraph_store/index/users/ada.md"
+ )
+ is None
+ )
+
+
+def test_langgraph_store_waits_for_indexing_by_default():
+ class RecordingClient(InMemoryOpenVikingClient):
+ def __init__(self):
+ super().__init__()
+ self.write_wait_values = []
+
+ def write(self, *args, wait=False, **kwargs):
+ self.write_wait_values.append(wait)
+ return super().write(*args, wait=wait, **kwargs)
+
+ client = RecordingClient()
+ store = OpenVikingStore(client=client)
+
+ store.put(("users",), "ada", {"color": "azure"})
+
+ assert client.write_wait_values
+ assert all(wait is True for wait in client.write_wait_values)
+
+ async_client = RecordingClient()
+ async_store = OpenVikingStore(client=async_client, wait=False)
+ async_store.put(("users",), "ada", {"color": "green"})
+
+ assert async_client.write_wait_values
+ assert all(wait is False for wait in async_client.write_wait_values)
+
+
+def test_langgraph_store_uses_create_first_and_preserves_created_at_on_replace():
+ class RecordingClient(InMemoryOpenVikingClient):
+ def __init__(self):
+ super().__init__()
+ self.write_modes = []
+
+ def write(self, uri, content, mode="replace", **kwargs):
+ self.write_modes.append((uri, mode))
+ return super().write(uri, content, mode=mode, **kwargs)
+
+ client = RecordingClient()
+ store = OpenVikingStore(client=client)
+
+ store.put(("users",), "ada", {"color": "azure"})
+ first = store.get(("users",), "ada")
+ store.put(("users",), "ada", {"color": "teal"})
+ second = store.get(("users",), "ada")
+
+ data_uri = "viking://user/memories/langgraph_store/data/users/ada.json"
+ assert client.write_modes[0] == (data_uri, "create")
+ assert (data_uri, "replace") in client.write_modes
+ assert second.created_at == first.created_at
+ assert second.updated_at >= first.updated_at
+ assert second.value["color"] == "teal"
+
+
+def test_pending_token_commit_does_not_create_missing_session():
+ client = InMemoryOpenVikingClient()
+ result = maybe_commit_session(
+ client,
+ "missing-commit-session",
+ OpenVikingCommitPolicy(mode="pending_tokens", pending_token_threshold=1),
+ )
+
+ assert result is None
+ assert "missing-commit-session" not in client.sessions
+
+
+def test_langgraph_middleware_injects_recall_and_captures_messages():
+ client = InMemoryOpenVikingClient(
+ {"viking://user/memories/profile.md": "The user prefers azure deployments."}
+ )
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ target_uri="viking://user/memories",
+ session_id_resolver=lambda state, runtime: "middleware-session",
+ commit_on_after_agent=True,
+ )
+
+ captured_request = {}
+
+ class Request:
+ messages = [HumanMessage(content="What deployment color?")]
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get("system_message", self.system_message)
+ return new_request
+
+ def handler(request):
+ captured_request["request"] = request
+ return AIMessage(content="ok")
+
+ middleware.wrap_model_call(Request(), handler)
+ assert "OpenViking context" in captured_request["request"].system_message.content
+ assert "azure deployments" in captured_request["request"].system_message.content
+
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="Remember this."),
+ AIMessage(content="I will."),
+ ]
+ },
+ runtime=None,
+ )
+ assert client.sessions["middleware-session"] == []
+ assert client.archives["middleware-session"]
+ archived_messages = client.archives["middleware-session"][0]["messages"]
+ assert len(archived_messages) == 2
+ assistant_parts = archived_messages[1]["parts"]
+ assert any(part["type"] == "context" for part in assistant_parts)
+
+
+def test_langgraph_middleware_does_not_duplicate_active_messages_in_context():
+ client = InMemoryOpenVikingClient(
+ {"viking://user/memories/profile.md": "Middleware recall uses green context."}
+ )
+ client.add_message(
+ "middleware-active-session",
+ "user",
+ content="OpenViking active duplicate user turn.",
+ )
+ client.add_message(
+ "middleware-active-session",
+ "assistant",
+ content="OpenViking active duplicate assistant turn.",
+ )
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ target_uri="viking://user/memories",
+ session_id_resolver=lambda state, runtime: "middleware-active-session",
+ )
+ captured_request = {}
+
+ class Request:
+ messages = [HumanMessage(content="What middleware recall?")]
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get("system_message", self.system_message)
+ return new_request
+
+ def handler(request):
+ captured_request["request"] = request
+ return AIMessage(content="ok")
+
+ middleware.wrap_model_call(Request(), handler)
+ system_content = captured_request["request"].system_message.content
+ assert "Middleware recall uses green context" in system_content
+ assert "OpenViking active duplicate user turn" not in system_content
+ assert "OpenViking active duplicate assistant turn" not in system_content
+
+
+def test_langgraph_middleware_uses_runtime_thread_id():
+ client = InMemoryOpenVikingClient(
+ {"viking://user/memories/profile.md": "Runtime thread users prefer teal."}
+ )
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ target_uri="viking://user/memories",
+ )
+ captured_request = {}
+
+ class Runtime:
+ config = {"configurable": {"thread_id": "runtime-thread"}}
+
+ class Request:
+ state = {}
+ runtime = Runtime()
+ messages = [HumanMessage(content="What runtime color?")]
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get("system_message", self.system_message)
+ return new_request
+
+ def handler(request):
+ captured_request["request"] = request
+ return AIMessage(content="ok")
+
+ middleware.wrap_model_call(Request(), handler)
+ assert "Runtime thread users prefer teal" in captured_request["request"].system_message.content
+ assert client.search_calls[-1]["session_id"] == "runtime-thread"
+
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="Remember runtime thread."),
+ AIMessage(content="Stored for runtime thread."),
+ ]
+ },
+ Runtime(),
+ )
+ assert len(client.sessions["runtime-thread"]) == 2
+
+
+def test_langgraph_middleware_requires_explicit_session_id():
+ client = InMemoryOpenVikingClient(
+ {"viking://user/memories/profile.md": "Shared fallback should never be used."}
+ )
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ target_uri="viking://user/memories",
+ )
+
+ class Request:
+ state = {}
+ runtime = None
+ messages = [HumanMessage(content="What context?")]
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get("system_message", self.system_message)
+ return new_request
+
+ def handler(request):
+ return AIMessage(content="ok")
+
+ with pytest.raises(ValueError, match="thread_id"):
+ middleware.wrap_model_call(Request(), handler)
+
+ with pytest.raises(ValueError, match="session_id"):
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="Remember this."),
+ AIMessage(content="Stored."),
+ ]
+ },
+ runtime=None,
+ )
+
+ assert "langgraph-default" not in client.sessions
+
+
+def test_langgraph_middleware_captures_cumulative_state_once():
+ client = InMemoryOpenVikingClient()
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ session_id_resolver=lambda state, runtime: "middleware-cumulative",
+ )
+ first_turn = [
+ HumanMessage(content="Remember first turn."),
+ AIMessage(content="First turn stored."),
+ ]
+ second_turn = first_turn + [
+ HumanMessage(content="Remember second turn."),
+ AIMessage(content="Second turn stored."),
+ ]
+
+ middleware.after_agent({"messages": first_turn}, runtime=None)
+ middleware.after_agent({"messages": second_turn}, runtime=None)
+ middleware.after_agent({"messages": second_turn}, runtime=None)
+
+ assert [
+ message["parts"][0]["text"] for message in client.sessions["middleware-cumulative"]
+ ] == [
+ "Remember first turn.",
+ "First turn stored.",
+ "Remember second turn.",
+ "Second turn stored.",
+ ]
+
+
+def test_langgraph_middleware_captures_latest_only_state_each_turn():
+ client = InMemoryOpenVikingClient()
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ session_id_resolver=lambda state, runtime: "middleware-latest-only",
+ )
+ first_turn = [
+ HumanMessage(content="Remember latest first."),
+ AIMessage(content="Latest first stored."),
+ ]
+ replayed_first_turn = [
+ HumanMessage(content="Remember latest first."),
+ AIMessage(content="Latest first stored."),
+ ]
+ second_turn = [
+ HumanMessage(content="Remember latest second."),
+ AIMessage(content="Latest second stored."),
+ ]
+
+ middleware.after_agent({"messages": first_turn}, runtime=None)
+ middleware.after_agent({"messages": replayed_first_turn}, runtime=None)
+ middleware.after_agent({"messages": second_turn}, runtime=None)
+
+ assert [
+ message["parts"][0]["text"] for message in client.sessions["middleware-latest-only"]
+ ] == [
+ "Remember latest first.",
+ "Latest first stored.",
+ "Remember latest second.",
+ "Latest second stored.",
+ ]
+
+
+def test_langgraph_middleware_captures_in_place_message_mutation():
+ client = InMemoryOpenVikingClient()
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ session_id_resolver=lambda state, runtime: "middleware-mutated",
+ )
+ messages = [
+ HumanMessage(content="Remember mutable first."),
+ AIMessage(content="Mutable first stored."),
+ ]
+
+ middleware.after_agent({"messages": messages}, runtime=None)
+ messages[0].content = "Remember mutable second."
+ messages[1].content = "Mutable second stored."
+ middleware.after_agent({"messages": messages}, runtime=None)
+
+ assert [message["parts"][0]["text"] for message in client.sessions["middleware-mutated"]] == [
+ "Remember mutable first.",
+ "Mutable first stored.",
+ "Remember mutable second.",
+ "Mutable second stored.",
+ ]
+
+
+def test_langgraph_middleware_captures_same_id_changed_content():
+ client = InMemoryOpenVikingClient()
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ session_id_resolver=lambda state, runtime: "middleware-same-id",
+ )
+
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="Remember same id first.", id="user-stable"),
+ AIMessage(content="Same id first stored.", id="assistant-stable"),
+ ]
+ },
+ runtime=None,
+ )
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="Remember same id second.", id="user-stable"),
+ AIMessage(content="Same id second stored.", id="assistant-stable"),
+ ]
+ },
+ runtime=None,
+ )
+
+ assert [message["parts"][0]["text"] for message in client.sessions["middleware-same-id"]] == [
+ "Remember same id first.",
+ "Same id first stored.",
+ "Remember same id second.",
+ "Same id second stored.",
+ ]
+
+
+def test_langgraph_middleware_signature_includes_dict_tool_output():
+ first = {
+ "role": "tool",
+ "tool_call_id": "call-dict",
+ "name": "viking_find",
+ "tool_output": "first output",
+ }
+ second = {
+ "role": "tool",
+ "tool_call_id": "call-dict",
+ "name": "viking_find",
+ "tool_output": "second output",
+ }
+
+ assert _message_signature(first) != _message_signature(second)
+ assert _message_signature(second) == _message_signature(dict(second))
+
+
+def test_langgraph_middleware_clears_pending_context_on_duplicate_retry():
+ client = InMemoryOpenVikingClient(
+ {"viking://user/memories/profile.md": "Retry cleanup context."}
+ )
+ middleware = OpenVikingContextMiddleware(
+ client=client,
+ target_uri="viking://user/memories",
+ session_id_resolver=lambda state, runtime: "middleware-pending-cleanup",
+ )
+
+ class Request:
+ messages = [HumanMessage(content="What retry context?")]
+ system_message = None
+
+ def override(self, **overrides):
+ new_request = Request()
+ new_request.messages = overrides.get("messages", self.messages)
+ new_request.system_message = overrides.get("system_message", self.system_message)
+ return new_request
+
+ def handler(request):
+ return AIMessage(content="Retry context stored.")
+
+ middleware.wrap_model_call(Request(), handler)
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="What retry context?"),
+ AIMessage(content="Retry context stored."),
+ ]
+ },
+ runtime=None,
+ )
+ middleware.wrap_model_call(Request(), handler)
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="What retry context?"),
+ AIMessage(content="Retry context stored."),
+ ]
+ },
+ runtime=None,
+ )
+ middleware.after_agent(
+ {
+ "messages": [
+ HumanMessage(content="Remember unrelated turn."),
+ AIMessage(content="Unrelated turn stored."),
+ ]
+ },
+ runtime=None,
+ )
+
+ unrelated_assistant_parts = client.sessions["middleware-pending-cleanup"][-1]["parts"]
+ assert unrelated_assistant_parts == [{"type": "text", "text": "Unrelated turn stored."}]
diff --git a/uv.lock b/uv.lock
index 9605a6786..72bfd8620 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3673,6 +3673,14 @@ gemini-async = [
{ name = "anyio" },
{ name = "google-genai" },
]
+langchain = [
+ { name = "langchain-core" },
+]
+langgraph = [
+ { name = "langchain" },
+ { name = "langchain-core" },
+ { name = "langgraph" },
+]
local-embed = [
{ name = "llama-cpp-python" },
]
@@ -3728,9 +3736,13 @@ requires-dist = [
{ name = "jinja2", specifier = ">=3.1.6" },
{ name = "json-repair", specifier = ">=0.25.0" },
{ name = "langchain", marker = "extra == 'benchmark'", specifier = ">=1.0.0" },
+ { name = "langchain", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },
{ name = "langchain-core", marker = "extra == 'benchmark'", specifier = ">=1.0.0" },
+ { name = "langchain-core", marker = "extra == 'langchain'", specifier = ">=1.0.0,<2.0.0" },
+ { name = "langchain-core", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },
{ name = "langchain-openai", marker = "extra == 'benchmark'", specifier = ">=1.0.0" },
{ name = "langfuse", marker = "extra == 'bot-langfuse'", specifier = ">=3.0.0" },
+ { name = "langgraph", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },
{ name = "lark-oapi", specifier = ">=1.5.3" },
{ name = "lark-oapi", marker = "extra == 'bot-feishu'", specifier = ">=1.0.0" },
{ name = "litellm", specifier = ">=1.83.7,<1.83.13" },
@@ -3818,7 +3830,7 @@ requires-dist = [
{ name = "xlrd", specifier = ">=2.0.1" },
{ name = "xxhash", specifier = ">=3.0.0" },
]
-provides-extras = ["test", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "bot-langfuse", "bot-telegram", "bot-feishu", "bot-dingtalk", "bot-slack", "bot-qq", "bot-sandbox", "bot-fuse", "bot-opencode", "bot-full", "benchmark", "local-embed"]
+provides-extras = ["test", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "bot-langfuse", "bot-telegram", "bot-feishu", "bot-dingtalk", "bot-slack", "bot-qq", "bot-sandbox", "bot-fuse", "bot-opencode", "bot-full", "benchmark", "langchain", "langgraph", "local-embed"]
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=9.0.2" }]