Skip to content

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

feat(search): add context type filter support (#2583)

Qin Haojie775e3f1193c8
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index af8699a4e..65a3a182b 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -386,6 +386,7 @@ impl HttpClient {
until: Option<String>,
time_field: Option<String>,
level: Option<Vec<i32>>,
+ context_type: Option<Vec<String>>,
peer_id: Option<String>,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
@@ -397,6 +398,7 @@ impl HttpClient {
"until": until,
"time_field": time_field,
"level": level,
+ "context_type": context_type,
"peer_id": peer_id,
});
self.post("/api/v1/search/find", &body).await
@@ -413,6 +415,7 @@ impl HttpClient {
until: Option<String>,
time_field: Option<String>,
level: Option<Vec<i32>>,
+ context_type: Option<Vec<String>>,
peer_id: Option<String>,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
@@ -425,6 +428,7 @@ impl HttpClient {
"until": until,
"time_field": time_field,
"level": level,
+ "context_type": context_type,
"peer_id": peer_id,
});
self.post("/api/v1/search/search", &body).await
diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rs
index fae633b0f..b5b16395c 100644
--- a/crates/ov_cli/src/commands/search.rs
+++ b/crates/ov_cli/src/commands/search.rs
@@ -54,6 +54,7 @@ pub async fn find(
until: Option<&str>,
time_field: Option<&str>,
level: Option<Vec<i32>>,
+ context_type: Option<Vec<String>>,
peer_id: Option<&str>,
output_format: OutputFormat,
compact: bool,
@@ -68,6 +69,7 @@ pub async fn find(
until.map(|s| s.to_string()),
time_field.map(|s| s.to_string()),
level,
+ context_type,
peer_id.map(|s| s.to_string()),
)
.await?;
@@ -91,6 +93,7 @@ pub async fn search(
until: Option<&str>,
time_field: Option<&str>,
level: Option<Vec<i32>>,
+ context_type: Option<Vec<String>>,
peer_id: Option<&str>,
output_format: OutputFormat,
compact: bool,
@@ -106,6 +109,7 @@ pub async fn search(
until.map(|s| s.to_string()),
time_field.map(|s| s.to_string()),
level,
+ context_type,
peer_id.map(|s| s.to_string()),
)
.await?;
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index f1e9d1039..4ef88752e 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -1116,6 +1116,7 @@ pub async fn handle_find(
after: Option<String>,
before: Option<String>,
level: Option<Vec<i32>>,
+ context_type: Option<Vec<String>>,
peer_id: Option<String>,
ctx: CliContext,
) -> Result<()> {
@@ -1133,6 +1134,9 @@ pub async fn handle_find(
.join(",")
));
}
+ if let Some(ref context_types) = context_type {
+ params.push(format!("--context-type {}", context_types.join(",")));
+ }
if let Some(ref p) = peer_id {
params.push(format!("--peer-id {}", p));
}
@@ -1149,6 +1153,7 @@ pub async fn handle_find(
before.as_deref(),
None,
level,
+ context_type,
peer_id.as_deref(),
ctx.output_format,
ctx.compact,
@@ -1165,6 +1170,7 @@ pub async fn handle_search(
after: Option<String>,
before: Option<String>,
level: Option<Vec<i32>>,
+ context_type: Option<Vec<String>>,
peer_id: Option<String>,
ctx: CliContext,
) -> Result<()> {
@@ -1185,6 +1191,9 @@ pub async fn handle_search(
.join(",")
));
}
+ if let Some(ref context_types) = context_type {
+ params.push(format!("--context-type {}", context_types.join(",")));
+ }
if let Some(ref p) = peer_id {
params.push(format!("--peer-id {}", p));
}
@@ -1202,6 +1211,7 @@ pub async fn handle_search(
before.as_deref(),
None,
level,
+ context_type,
peer_id.as_deref(),
ctx.output_format,
ctx.compact,
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index 6191fc726..3397bbf97 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -2590,6 +2590,10 @@ mod tests {
rendered.contains("--peer-id <id>"),
"missing --peer-id for {command} in:\n{rendered}"
);
+ assert!(
+ rendered.contains("--context-type <type>"),
+ "missing --context-type for {command} in:\n{rendered}"
+ );
}
}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 5ba1dcb5d..68f7c5bdf 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -548,6 +548,14 @@ enum Commands {
help_heading = "Common options"
)]
level: Option<Vec<i32>>,
+ /// Only include results with specific context type(s) (memory, resource, skill)
+ #[arg(
+ long = "context-type",
+ value_delimiter = ',',
+ value_name = "type",
+ help_heading = "Common options"
+ )]
+ context_type: Option<Vec<String>>,
/// Limit memory retrieval to this peer plus the current user memory
#[arg(long = "peer-id", value_name = "id", help_heading = "Advanced options")]
peer_id: Option<String>,
@@ -601,6 +609,14 @@ enum Commands {
help_heading = "Advanced options"
)]
level: Option<Vec<i32>>,
+ /// Only include results with specific context type(s) (memory, resource, skill)
+ #[arg(
+ long = "context-type",
+ value_delimiter = ',',
+ value_name = "type",
+ help_heading = "Advanced options"
+ )]
+ context_type: Option<Vec<String>>,
/// Limit memory retrieval to this peer plus the current user memory
#[arg(long = "peer-id", value_name = "id", help_heading = "Advanced options")]
peer_id: Option<String>,
@@ -1780,6 +1796,7 @@ fn consumes_plain_help_value(token: &str) -> bool {
| "--threshold"
| "--after"
| "--before"
+ | "--context-type"
| "--peer-id"
| "-s"
| "--skill"
@@ -1838,6 +1855,7 @@ fn consumes_plain_help_value(token: &str) -> bool {
|| token.starts_with("--threshold=")
|| token.starts_with("--after=")
|| token.starts_with("--before=")
+ || token.starts_with("--context-type=")
|| token.starts_with("--peer-id=")
|| token.starts_with("--skill=")
|| token.starts_with("--session=")
@@ -2898,10 +2916,20 @@ async fn main() {
after,
before,
level,
+ context_type,
peer_id,
} => {
handlers::handle_find(
- query, uri, node_limit, threshold, after, before, level, peer_id, ctx,
+ query,
+ uri,
+ node_limit,
+ threshold,
+ after,
+ before,
+ level,
+ context_type,
+ peer_id,
+ ctx,
)
.await
}
@@ -2914,10 +2942,21 @@ async fn main() {
after,
before,
level,
+ context_type,
peer_id,
} => {
handlers::handle_search(
- query, uri, session_id, node_limit, threshold, after, before, level, peer_id, ctx,
+ query,
+ uri,
+ session_id,
+ node_limit,
+ threshold,
+ after,
+ before,
+ level,
+ context_type,
+ peer_id,
+ ctx,
)
.await
}
@@ -2998,6 +3037,23 @@ mod tests {
}
}
+ #[test]
+ fn cli_parses_find_context_type() {
+ let cli =
+ Cli::try_parse_from(["ov", "find", "invoice", "--context-type", "memory,resource"])
+ .expect("find context type should parse");
+
+ match cli.command {
+ Commands::Find { context_type, .. } => {
+ assert_eq!(
+ context_type,
+ Some(vec!["memory".to_string(), "resource".to_string()])
+ );
+ }
+ _ => panic!("expected find command"),
+ }
+ }
+
#[test]
fn cli_parses_search_peer_id() {
let cli =
@@ -3012,6 +3068,19 @@ mod tests {
}
}
+ #[test]
+ fn cli_parses_search_context_type() {
+ let cli = Cli::try_parse_from(["ov", "search", "invoice", "--context-type", "skill"])
+ .expect("search context type should parse");
+
+ match cli.command {
+ Commands::Search { context_type, .. } => {
+ assert_eq!(context_type, Some(vec!["skill".to_string()]));
+ }
+ _ => panic!("expected search command"),
+ }
+ }
+
#[test]
fn cli_chat_sender_uses_long_flag_and_session_keeps_short_s() {
Cli::command().debug_assert();
diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.md
index 3f9bf35d5..77a9fc1bf 100644
--- a/docs/en/api/06-retrieval.md
+++ b/docs/en/api/06-retrieval.md
@@ -56,6 +56,7 @@ The `find()` method performs pure vector similarity search for simple query scen
|-----------|------|----------|---------|-------------|
| query | str | Yes | - | Search query string |
| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix |
+| context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` |
| peer_id | str | No | None | Stable interaction peer ID. When searching default user-scoped targets, results include this peer's memories and resources in addition to current-user content. CLI maps `--peer-id` to this field |
| node_limit | int | No | None | Maximum number of results |
| score_threshold | float | No | None | Minimum relevance score threshold |
@@ -132,10 +133,23 @@ curl -X POST http://localhost:1933/api/v1/search/find \
}'
```
+**Search by Context Type**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/search/find \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -d '{
+ "query": "authentication",
+ "context_type": ["memory", "resource"]
+ }'
+```
+
**Python SDK**
```python
import openviking as ov
+from openviking.retrieve import ContextType
client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")
client.initialize()
@@ -151,6 +165,12 @@ recent_emails = client.find(
time_field="created_at",
)
+# Search only memories and resources
+typed_results = client.find(
+ "authentication",
+ context_type=[ContextType.MEMORY, ContextType.RESOURCE],
+)
+
# Iterate through results
for ctx in results.resources:
print(f"URI: {ctx.uri}")
@@ -209,6 +229,9 @@ openviking find "how to authenticate users"
# Specify URI scope
openviking find "how to authenticate users" --uri "viking://resources"
+# Limit to context types
+openviking find "authentication" --context-type memory,resource
+
# With time filter
openviking find "invoice" --after 7d
@@ -292,6 +315,7 @@ The `search()` method adds session context understanding and intent analysis cap
| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix |
| session | Session | No | None | Session for context-aware search (SDK) |
| session_id | str | No | None | Session ID for context-aware search (HTTP) |
+| context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` |
| peer_id | str | No | None | Stable interaction peer ID. When searching default user-scoped targets, results include this peer's memories and resources in addition to current-user content. CLI maps `--peer-id` to this field |
| node_limit | int | No | None | Maximum number of results |
| score_threshold | float | No | None | Minimum relevance score threshold |
@@ -320,6 +344,7 @@ curl -X POST http://localhost:1933/api/v1/search/search \
-d '{
"query": "best practices",
"session_id": "abc123",
+ "context_type": "skill",
"since": "2h",
"time_field": "updated_at",
"limit": 10
@@ -341,6 +366,7 @@ curl -X POST http://localhost:1933/api/v1/search/search \
```python
import openviking as ov
+from openviking.retrieve import ContextType
from openviking.message import TextPart
client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")
@@ -359,6 +385,7 @@ session.add_message("assistant", [
results = client.search(
"best practices",
session=session,
+ context_type=ContextType.SKILL,
since="2h"
)
@@ -386,6 +413,9 @@ for ctx in results.resources:
# Search with session ID
openviking search "best practices" --session-id abc123
+# Limit to a context type
+openviking search "best practices" --context-type skill
+
# Search with time filter
openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20
diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.md
index 24611e8bc..6d1d68891 100644
--- a/docs/zh/api/06-retrieval.md
+++ b/docs/zh/api/06-retrieval.md
@@ -56,6 +56,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带
|------|------|------|--------|------|
| query | str | 是 | - | 搜索查询字符串 |
| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |
+| context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` |
| peer_id | str | 否 | None | 稳定交互对象 ID。检索默认 user-scoped 目标时,会在当前用户内容之外额外检索该 peer 的 memories 和 resources。CLI `--peer-id` 会映射到这个字段 |
| limit | int | 否 | 10 | 最大返回结果数 |
| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit |
@@ -133,10 +134,23 @@ curl -X POST http://localhost:1933/api/v1/search/find \
}'
```
+**按 Context Type 搜索**
+
+```bash
+curl -X POST http://localhost:1933/api/v1/search/find \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -d '{
+ "query": "authentication",
+ "context_type": ["memory", "resource"]
+ }'
+```
+
**Python SDK**
```python
import openviking as ov
+from openviking.retrieve import ContextType
client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")
client.initialize()
@@ -152,6 +166,12 @@ recent_emails = client.find(
time_field="created_at",
)
+# 仅搜索 memories 和 resources
+typed_results = client.find(
+ "authentication",
+ context_type=[ContextType.MEMORY, ContextType.RESOURCE],
+)
+
# 遍历结果
for ctx in results.resources:
print(f"URI: {ctx.uri}")
@@ -210,6 +230,9 @@ openviking find "how to authenticate users"
# 指定 URI 范围
openviking find "how to authenticate users" --uri "viking://resources"
+# 限定上下文类型
+openviking find "authentication" --context-type memory,resource
+
# 带时间过滤
openviking find "invoice" --after 7d
@@ -293,6 +316,7 @@ openviking find "how to authenticate users" -L 1,2
| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |
| session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|
| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|
+| context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` |
| peer_id | str | 否 | None | 稳定交互对象 ID。检索默认 user-scoped 目标时,会在当前用户内容之外额外检索该 peer 的 memories 和 resources。CLI `--peer-id` 会映射到这个字段 |
| limit | int | 否 | 10 | 最大返回结果数 |
| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit |
@@ -322,6 +346,7 @@ curl -X POST http://localhost:1933/api/v1/search/search \
-d '{
"query": "best practices",
"session_id": "abc123",
+ "context_type": "skill",
"since": "2h",
"time_field": "updated_at",
"limit": 10
@@ -343,6 +368,7 @@ curl -X POST http://localhost:1933/api/v1/search/search \
```python
import openviking as ov
+from openviking.retrieve import ContextType
from openviking.message import TextPart
client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")
@@ -361,6 +387,7 @@ session.add_message("assistant", [
results = client.search(
"best practices",
session=session,
+ context_type=ContextType.SKILL,
since="2h"
)
@@ -388,6 +415,9 @@ for ctx in results.resources:
# 带会话 ID 的搜索
openviking search "best practices" --session-id abc123
+# 限定上下文类型
+openviking search "best practices" --context-type skill
+
# 带时间过滤的搜索
openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 331247583..9df8874ea 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union
from openviking.client import LocalClient, Session
from openviking.service.debug_service import SystemStatus
from openviking.telemetry import TelemetryRequest
+from openviking.utils.search_filters import SearchContextTypeInput
from openviking_cli.client.base import BaseClient
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger
@@ -365,6 +366,7 @@ class AsyncOpenViking:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
since: Optional[str] = None,
until: Optional[str] = None,
@@ -395,6 +397,7 @@ class AsyncOpenViking:
limit=limit,
score_threshold=score_threshold,
filter=filter,
+ context_type=context_type,
telemetry=telemetry,
since=since,
until=until,
@@ -410,6 +413,7 @@ class AsyncOpenViking:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
since: Optional[str] = None,
until: Optional[str] = None,
@@ -425,6 +429,7 @@ class AsyncOpenViking:
limit=limit,
score_threshold=score_threshold,
filter=filter,
+ context_type=context_type,
telemetry=telemetry,
since=since,
until=until,
diff --git a/openviking/client/local.py b/openviking/client/local.py
index 87c09901e..094730eec 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -15,7 +15,7 @@ from openviking.telemetry.execution import (
attach_telemetry_payload,
run_with_telemetry,
)
-from openviking.utils.search_filters import merge_time_filter
+from openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter
from openviking_cli.client.base import BaseClient
from openviking_cli.exceptions import NotFoundError
from openviking_cli.session.user_id import UserIdentifier
@@ -36,13 +36,15 @@ def _to_jsonable(value: Any) -> Any:
def _resolve_search_filter(
filter: Optional[Dict[str, Any]],
+ context_type: Optional[SearchContextTypeInput],
since: Optional[str],
until: Optional[str],
time_field: Optional[str],
) -> Optional[Dict[str, Any]]:
- """Merge optional retrieval time bounds into the metadata filter."""
- return merge_time_filter(
+ """Merge public retrieval filter shortcuts into the metadata filter."""
+ return merge_search_filter(
filter,
+ context_type=context_type,
since=since,
until=until,
time_field=time_field,
@@ -296,6 +298,7 @@ class LocalClient(BaseClient):
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
since: Optional[str] = None,
until: Optional[str] = None,
@@ -304,7 +307,7 @@ class LocalClient(BaseClient):
peer_id: Optional[str] = None,
) -> Any:
"""Semantic search without session context."""
- resolved_filter = _resolve_search_filter(filter, since, until, time_field)
+ resolved_filter = _resolve_search_filter(filter, context_type, since, until, time_field)
execution = await run_with_telemetry(
operation="search.find",
telemetry=telemetry,
@@ -332,6 +335,7 @@ class LocalClient(BaseClient):
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
since: Optional[str] = None,
until: Optional[str] = None,
@@ -340,7 +344,7 @@ class LocalClient(BaseClient):
peer_id: Optional[str] = None,
) -> Any:
"""Semantic search with optional session context."""
- resolved_filter = _resolve_search_filter(filter, since, until, time_field)
+ resolved_filter = _resolve_search_filter(filter, context_type, since, until, time_field)
async def _search():
session = None
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index 31569ea1a..afae542dd 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -18,7 +18,11 @@ from openviking.server.identity import RequestContext
from openviking.server.models import Response
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
-from openviking.utils.search_filters import _resolve_levels, merge_time_filter
+from openviking.utils.search_filters import (
+ SearchContextTypeInput,
+ _resolve_levels,
+ merge_search_filter,
+)
from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
@@ -45,13 +49,15 @@ def _resolve_search_limit(limit: int, node_limit: Optional[int]) -> int:
def _resolve_search_filter(
request_filter: Optional[Dict[str, Any]],
+ context_type: Optional[SearchContextTypeInput],
since: Optional[str],
until: Optional[str],
time_field: Optional[TimeField],
) -> Optional[Dict[str, Any]]:
try:
- return merge_time_filter(
+ return merge_search_filter(
request_filter,
+ context_type=context_type,
since=since,
until=until,
time_field=time_field,
@@ -72,6 +78,7 @@ class FindRequest(BaseModel):
query: str
target_uri: Union[str, List[str]] = ""
+ context_type: Optional[Union[str, List[str]]] = None
peer_id: Optional[str] = None
limit: int = 10
node_limit: Optional[int] = None
@@ -95,6 +102,7 @@ class SearchRequest(BaseModel):
query: str
target_uri: Union[str, List[str]] = ""
+ context_type: Optional[Union[str, List[str]]] = None
peer_id: Optional[str] = None
session_id: Optional[str] = None
limit: int = 10
@@ -144,6 +152,7 @@ async def find(
actual_limit = _resolve_search_limit(request.limit, request.node_limit)
effective_filter = _resolve_search_filter(
request.filter,
+ request.context_type,
request.since,
request.until,
request.time_field,
@@ -184,6 +193,7 @@ async def search(
actual_limit = _resolve_search_limit(request.limit, request.node_limit)
effective_filter = _resolve_search_filter(
request.filter,
+ request.context_type,
request.since,
request.until,
request.time_field,
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index 6ecc91726..a2f0ccdd3 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -13,6 +13,7 @@ if TYPE_CHECKING:
from openviking.async_client import AsyncOpenViking
from openviking.telemetry import TelemetryRequest
+from openviking.utils.search_filters import SearchContextTypeInput
from openviking_cli.utils import run_async
@@ -228,6 +229,7 @@ class SyncOpenViking:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
since: Optional[str] = None,
until: Optional[str] = None,
@@ -245,6 +247,7 @@ class SyncOpenViking:
limit=limit,
score_threshold=score_threshold,
filter=filter,
+ context_type=context_type,
telemetry=telemetry,
since=since,
until=until,
@@ -261,6 +264,7 @@ class SyncOpenViking:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
since: Optional[str] = None,
until: Optional[str] = None,
@@ -276,6 +280,7 @@ class SyncOpenViking:
limit,
score_threshold,
filter,
+ context_type,
telemetry,
since,
until,
diff --git a/openviking/utils/search_filters.py b/openviking/utils/search_filters.py
index d2c04e32d..c07802ac4 100644
--- a/openviking/utils/search_filters.py
+++ b/openviking/utils/search_filters.py
@@ -8,11 +8,91 @@ from datetime import datetime, time, timedelta, timezone
from typing import Any, Dict, List, Literal, Optional, Union
from openviking.utils.time_utils import format_iso8601, parse_iso_datetime
+from openviking_cli.retrieve.types import ContextType
+_CONTEXT_TYPE_INPUT_ERROR = (
+ "context_type must be a ContextType, string, or list of ContextType/string values"
+)
_DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_RELATIVE_RE = re.compile(r"^(?P<value>\d+)(?P<unit>[smhdw])$")
TimeField = Literal["updated_at", "created_at"]
VALID_TIME_FIELDS = {"updated_at", "created_at"}
+SearchContextTypeValue = Union[ContextType, str]
+SearchContextTypeInput = Union[SearchContextTypeValue, List[SearchContextTypeValue]]
+
+
+def merge_search_filter(
+ existing_filter: Optional[Dict[str, Any]],
+ *,
+ context_type: Optional[SearchContextTypeInput] = None,
+ since: Optional[str] = None,
+ until: Optional[str] = None,
+ time_field: Optional[TimeField] = None,
+ now: Optional[datetime] = None,
+) -> Optional[Dict[str, Any]]:
+ """Merge public search filter shortcuts into one metadata filter tree."""
+ merged = merge_context_type_filter(existing_filter, context_type)
+ return merge_time_filter(
+ merged,
+ since=since,
+ until=until,
+ time_field=time_field,
+ now=now,
+ )
+
+
+def merge_context_type_filter(
+ existing_filter: Optional[Dict[str, Any]],
+ context_type: Optional[SearchContextTypeInput] = None,
+) -> Optional[Dict[str, Any]]:
+ """Merge context type shortcut into an existing metadata filter tree."""
+ context_types = resolve_context_types(context_type)
+ if not context_types:
+ return existing_filter
+ context_filter = {"op": "must", "field": "context_type", "conds": context_types}
+ return _and_filters(existing_filter, context_filter)
+
+
+def resolve_context_types(context_type: Optional[SearchContextTypeInput]) -> List[str]:
+ """Resolve context_type parameter into normalized retrieval context types."""
+ if context_type is None:
+ return []
+
+ values: List[str] = []
+ if isinstance(context_type, ContextType):
+ values = [context_type.value]
+ elif isinstance(context_type, str):
+ values = context_type.split(",")
+ elif isinstance(context_type, list):
+ for item in context_type:
+ if isinstance(item, ContextType):
+ values.append(item.value)
+ elif isinstance(item, str):
+ values.extend(item.split(","))
+ else:
+ raise ValueError(_CONTEXT_TYPE_INPUT_ERROR)
+ else:
+ raise ValueError(_CONTEXT_TYPE_INPUT_ERROR)
+
+ normalized_values: List[str] = []
+ invalid_values: List[str] = []
+ for value in values:
+ normalized = value.strip().lower()
+ if not normalized:
+ continue
+ try:
+ resolved = ContextType(normalized).value
+ except ValueError:
+ invalid_values.append(value)
+ continue
+ if resolved not in normalized_values:
+ normalized_values.append(resolved)
+
+ if invalid_values:
+ valid_values = ", ".join(sorted(context_type.value for context_type in ContextType))
+ raise ValueError(f"context_type must be one or more of: {valid_values}")
+
+ return normalized_values
def merge_time_filter(
@@ -41,7 +121,24 @@ def merge_time_filter(
return time_filter
# Preserve any caller-supplied metadata predicates by AND-ing the time range
# into the existing filter tree instead of replacing it.
- return {"op": "and", "conds": [existing_filter, time_filter]}
+ return _and_filters(existing_filter, time_filter)
+
+
+def _and_filters(
+ left: Optional[Dict[str, Any]],
+ right: Optional[Dict[str, Any]],
+) -> Optional[Dict[str, Any]]:
+ if not left:
+ return right
+ if not right:
+ return left
+ conds: List[Dict[str, Any]] = []
+ for item in (left, right):
+ if item.get("op") == "and" and isinstance(item.get("conds"), list):
+ conds.extend(item["conds"])
+ else:
+ conds.append(item)
+ return {"op": "and", "conds": conds}
def _resolve_levels(level: Optional[Union[int, str, List[int], List[str]]]) -> List[int]:
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 066f12b6d..d27618655 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -9,6 +9,7 @@ from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Union
from openviking.telemetry import TelemetryRequest
+from openviking.utils.search_filters import SearchContextTypeInput
class BaseClient(ABC):
@@ -167,6 +168,7 @@ class BaseClient(ABC):
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
peer_id: Optional[str] = None,
) -> Any:
@@ -182,6 +184,7 @@ class BaseClient(ABC):
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
peer_id: Optional[str] = None,
) -> Any:
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index cb84fd31e..84a9aa597 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union
import httpx
from openviking.telemetry import TelemetryRequest, normalize_telemetry_request
+from openviking.utils.search_filters import SearchContextTypeInput
from openviking_cli.client.base import BaseClient
from openviking_cli.exceptions import (
AbortedError,
@@ -687,6 +688,7 @@ class AsyncHTTPClient(BaseClient):
node_limit: Optional[int] = None,
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
peer_id: Optional[str] = None,
) -> FindResult:
@@ -700,6 +702,7 @@ class AsyncHTTPClient(BaseClient):
"limit": actual_limit,
"score_threshold": score_threshold,
"filter": filter,
+ "context_type": context_type,
"telemetry": telemetry,
}
if peer_id is not None:
@@ -718,6 +721,7 @@ class AsyncHTTPClient(BaseClient):
node_limit: Optional[int] = None,
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
peer_id: Optional[str] = None,
) -> FindResult:
@@ -733,6 +737,7 @@ class AsyncHTTPClient(BaseClient):
"limit": actual_limit,
"score_threshold": score_threshold,
"filter": filter,
+ "context_type": context_type,
"telemetry": telemetry,
}
if peer_id is not None:
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index a624896f8..5dc53da48 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -8,6 +8,7 @@ Wraps AsyncHTTPClient with synchronous methods.
from typing import Any, Dict, List, Optional, Union
from openviking.telemetry import TelemetryRequest
+from openviking.utils.search_filters import SearchContextTypeInput
from openviking_cli.client.http import AsyncHTTPClient
from openviking_cli.utils import run_async
@@ -285,6 +286,7 @@ class SyncHTTPClient:
node_limit: Optional[int] = None,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
peer_id: Optional[str] = None,
):
@@ -299,6 +301,7 @@ class SyncHTTPClient:
node_limit=node_limit,
score_threshold=score_threshold,
filter=filter,
+ context_type=context_type,
telemetry=telemetry,
peer_id=peer_id,
)
@@ -312,6 +315,7 @@ class SyncHTTPClient:
node_limit: Optional[int] = None,
score_threshold: Optional[float] = None,
filter: Optional[Dict] = None,
+ context_type: Optional[SearchContextTypeInput] = None,
telemetry: TelemetryRequest = False,
peer_id: Optional[str] = None,
):
@@ -324,6 +328,7 @@ class SyncHTTPClient:
node_limit,
score_threshold,
filter,
+ context_type,
telemetry=telemetry,
peer_id=peer_id,
)
diff --git a/tests/api_test/api/client.py b/tests/api_test/api/client.py
index a8c16bb91..45b5a7efb 100644
--- a/tests/api_test/api/client.py
+++ b/tests/api_test/api/client.py
@@ -174,6 +174,7 @@ class OpenVikingAPIClient:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[str | list[str]] = None,
peer_id: Optional[str] = None,
) -> requests.Response:
endpoint = "/api/v1/search/find"
@@ -187,6 +188,8 @@ class OpenVikingAPIClient:
payload["score_threshold"] = score_threshold
if filter:
payload["filter"] = filter
+ if context_type:
+ payload["context_type"] = context_type
return self._request_with_retry("POST", url, json=payload)
def search(
@@ -197,6 +200,7 @@ class OpenVikingAPIClient:
limit: int = 10,
score_threshold: Optional[float] = None,
filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[str | list[str]] = None,
peer_id: Optional[str] = None,
) -> requests.Response:
endpoint = "/api/v1/search/search"
@@ -212,6 +216,8 @@ class OpenVikingAPIClient:
payload["score_threshold"] = score_threshold
if filter:
payload["filter"] = filter
+ if context_type:
+ payload["context_type"] = context_type
return self._request_with_retry("POST", url, json=payload)
def grep(
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index 2089ece98..7f7c2fe6a 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -7,6 +7,7 @@ import httpx
import pytest
from openviking_cli.client.http import AsyncHTTPClient
+from openviking_cli.retrieve.types import ContextType
from openviking_cli.utils.config import OPENVIKING_CLI_CONFIG_ENV
@@ -323,6 +324,7 @@ async def test_async_http_client_find_sends_peer_id(tmp_path, monkeypatch):
"limit": 10,
"score_threshold": None,
"filter": None,
+ "context_type": None,
"telemetry": False,
"peer_id": "web-visitor-alice",
},
@@ -357,8 +359,72 @@ async def test_async_http_client_search_sends_peer_id(tmp_path, monkeypatch):
"limit": 10,
"score_threshold": None,
"filter": None,
+ "context_type": None,
"telemetry": False,
"peer_id": "web-visitor-alice",
},
)
]
+
+
+async def test_async_http_client_find_sends_context_type(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ http = FakeSearchHTTP()
+ client = AsyncHTTPClient(url="http://explicit-host:1933", api_key="key")
+ client._http = http
+
+ await client.find(
+ "invoice",
+ context_type=[ContextType.MEMORY, ContextType.RESOURCE],
+ )
+
+ assert http.calls == [
+ (
+ "/api/v1/search/find",
+ {
+ "query": "invoice",
+ "target_uri": "",
+ "limit": 10,
+ "score_threshold": None,
+ "filter": None,
+ "context_type": ["memory", "resource"],
+ "telemetry": False,
+ },
+ )
+ ]
+
+
+async def test_async_http_client_search_sends_context_type(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}")
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(config_path))
+
+ http = FakeSearchHTTP()
+ client = AsyncHTTPClient(url="http://explicit-host:1933", api_key="key")
+ client._http = http
+
+ await client.search(
+ "invoice",
+ context_type="skill",
+ )
+
+ assert http.calls == [
+ (
+ "/api/v1/search/search",
+ {
+ "query": "invoice",
+ "target_uri": "",
+ "session_id": None,
+ "limit": 10,
+ "score_threshold": None,
+ "filter": None,
+ "context_type": "skill",
+ "telemetry": False,
+ },
+ )
+ ]
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index 634cdff67..0af324cf7 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -476,6 +476,71 @@ async def test_find_combines_existing_filter_with_time_range(
}
+async def test_find_with_context_type_compiles_filter(
+ client: httpx.AsyncClient, service, monkeypatch
+):
+ captured = {}
+
+ async def fake_find(*, filter=None, **kwargs):
+ captured["filter"] = filter
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample", "context_type": "memory"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["filter"] == {"op": "must", "field": "context_type", "conds": ["memory"]}
+
+
+async def test_search_combines_context_type_list_with_existing_filter(
+ client: httpx.AsyncClient, service, monkeypatch
+):
+ captured = {}
+
+ async def fake_search(*, filter=None, **kwargs):
+ captured["filter"] = filter
+ return {"items": []}
+
+ monkeypatch.setattr(service.search, "search", fake_search)
+
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={
+ "query": "sample",
+ "context_type": ["memory", "resource"],
+ "filter": {"op": "must", "field": "kind", "conds": ["email"]},
+ },
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+ assert captured["filter"] == {
+ "op": "and",
+ "conds": [
+ {"op": "must", "field": "kind", "conds": ["email"]},
+ {"op": "must", "field": "context_type", "conds": ["memory", "resource"]},
+ ],
+ }
+
+
+async def test_find_with_invalid_context_type_returns_invalid_argument(client: httpx.AsyncClient):
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": "sample", "context_type": "archive"},
+ )
+
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
+ assert "context_type" in body["error"]["message"]
+
+
async def test_find_with_invalid_time_returns_invalid_argument(client: httpx.AsyncClient):
resp = await client.post(
"/api/v1/search/find",