Skip to content

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

refactor: rename batch_add_messages to add_messages, add CLI add-messages command and update api docs (#2218)

zgy8be3d4dae719
diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rs
index 990693f05..3d025f656 100644
--- a/crates/ov_cli/src/commands/session.rs
+++ b/crates/ov_cli/src/commands/session.rs
@@ -91,6 +91,48 @@ pub async fn delete_session(
Ok(())
}
+fn parse_messages(input: &str) -> Result<Vec<(String, String)>> {
+ if let Ok(value) = serde_json::from_str::<serde_json::Value>(input) {
+ if let Some(arr) = value.as_array() {
+ let messages: std::result::Result<Vec<(String, String)>, _> = arr
+ .iter()
+ .enumerate()
+ .map(|(i, item)| {
+ let role = item["role"].as_str().ok_or_else(|| {
+ crate::error::Error::Api(format!(
+ "messages[{}]: 'role' must be a string, got {:?}",
+ i, item["role"]
+ ))
+ })?;
+ let content = item["content"].as_str().ok_or_else(|| {
+ crate::error::Error::Api(format!(
+ "messages[{}]: 'content' must be a string, got {:?}",
+ i, item["content"]
+ ))
+ })?;
+ Ok((role.to_string(), content.to_string()))
+ })
+ .collect();
+ return messages;
+ } else if value.get("role").is_some() || value.get("content").is_some() {
+ let role = value["role"].as_str().ok_or_else(|| {
+ crate::error::Error::Api(format!(
+ "'role' must be a string, got {:?}",
+ value["role"]
+ ))
+ })?;
+ let content = value["content"].as_str().ok_or_else(|| {
+ crate::error::Error::Api(format!(
+ "'content' must be a string, got {:?}",
+ value["content"]
+ ))
+ })?;
+ return Ok(vec![(role.to_string(), content.to_string())]);
+ }
+ }
+ Ok(vec![("user".to_string(), input.to_string())])
+}
+
pub async fn add_message(
client: &HttpClient,
session_id: &str,
@@ -110,6 +152,28 @@ pub async fn add_message(
Ok(())
}
+pub async fn add_messages(
+ client: &HttpClient,
+ session_id: &str,
+ input: &str,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let messages = parse_messages(input)?;
+ let path = format!(
+ "/api/v1/sessions/{}/messages/batch",
+ url_encode(session_id)
+ );
+ let messages_json: Vec<serde_json::Value> = messages
+ .iter()
+ .map(|(role, content)| json!({"role": role, "content": content}))
+ .collect();
+ let body = json!({"messages": messages_json});
+ let response: serde_json::Value = client.post(&path, &body).await?;
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
pub async fn commit_session(
client: &HttpClient,
session_id: &str,
@@ -134,31 +198,7 @@ pub async fn add_memory(
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
- // Parse input to determine messages
- let messages: Vec<(String, String)> =
- if let Ok(value) = serde_json::from_str::<serde_json::Value>(input) {
- if let Some(arr) = value.as_array() {
- // JSON array of {role, content}
- arr.iter()
- .map(|item| {
- let role = item["role"].as_str().unwrap_or("user").to_string();
- let content = item["content"].as_str().unwrap_or("").to_string();
- (role, content)
- })
- .collect()
- } else if value.get("role").is_some() || value.get("content").is_some() {
- // Single JSON object with role/content
- let role = value["role"].as_str().unwrap_or("user").to_string();
- let content = value["content"].as_str().unwrap_or("").to_string();
- vec![(role, content)]
- } else {
- // JSON but not a message object, treat as plain string
- vec![("user".to_string(), input.to_string())]
- }
- } else {
- // Plain string
- vec![("user".to_string(), input.to_string())]
- };
+ let messages = parse_messages(input)?;
// 1. Create a new session
let session_response: serde_json::Value = client.post("/api/v1/sessions", &json!({})).await?;
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index 37ef730b7..3f1747807 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -350,6 +350,19 @@ pub async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()>
)
.await
}
+ SessionCommands::AddMessages {
+ session_id,
+ messages,
+ } => {
+ commands::session::add_messages(
+ &client,
+ &session_id,
+ &messages,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
SessionCommands::Commit { session_id } => {
commands::session::commit_session(&client, &session_id, ctx.output_format, ctx.compact)
.await
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index d0773b3e6..4e00aea5c 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -816,6 +816,13 @@ enum SessionCommands {
#[arg(long)]
content: String,
},
+ /// Add multiple messages to a session
+ AddMessages {
+ /// Session ID
+ session_id: String,
+ /// Messages as JSON array of {role, content} objects
+ messages: String,
+ },
/// Commit a session (archive messages and extract memories)
Commit {
/// Session ID
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md
index 096109609..29a8b83e1 100644
--- a/docs/en/api/05-sessions.md
+++ b/docs/en/api/05-sessions.md
@@ -702,6 +702,101 @@ ov session add-message a1b2c3d4 --role user --content "How do I authenticate use
---
+### batch_add_messages()
+
+#### 1. API Implementation Introduction
+
+Add multiple messages to a session in a single request. Suitable for scenarios that require writing a large number of messages at once (e.g., importing conversation history, memory extraction), offering significantly better performance than calling `add_message()` repeatedly.
+
+**Difference from `add_message()`**:
+- `add_message()`: Add 1 message per request
+- `batch_add_messages()`: Add multiple messages per request (max 100), reducing network round trips and file I/O
+
+**Code Entry Points**:
+- `openviking/session/session.py:Session.add_messages()` - Core implementation
+- `openviking/server/routers/sessions.py:batch_add_messages()` - HTTP route
+- `openviking_cli/client/base.py:BaseClient.batch_add_messages()` - Python SDK
+- `crates/ov_cli/src/commands/session.rs:add_messages()` - CLI command
+
+#### 2. Interface and Parameter Description
+
+**Parameters**
+
+| Parameter | Type | Required | Default | Description |
+|------|------|------|--------|------|
+| session_id | str | Yes | - | Session ID |
+| messages | List[AddMessageRequest] | Yes | - | List of messages, each following the same format as `add_message()`, max 100 |
+| telemetry | bool | No | False | Whether to attach operation telemetry data |
+
+> **Note**: Each message follows the exact same format as `add_message()`, supporting both `content` (simple mode) and `parts` (Parts mode). If you need to add more than 100 messages, call in batches.
+
+#### 3. Usage Examples
+
+**HTTP API**
+
+```http
+POST /api/v1/sessions/{session_id}/messages/batch
+```
+
+```bash
+# Add multiple messages in batch
+curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages/batch \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -d '{
+ "messages": [
+ {"role": "user", "content": "How do I authenticate users?"},
+ {"role": "assistant", "content": "You can use OAuth 2.0 for authentication."},
+ {"role": "user", "content": "Any specific recommendations?"}
+ ]
+ }'
+```
+
+**Python SDK**
+
+```python
+import openviking as ov
+
+client = ov.Client(base_url="http://localhost:1933", api_key="your-key")
+
+# Add messages in batch
+result = await client.batch_add_messages(
+ session_id="a1b2c3d4",
+ messages=[
+ {"role": "user", "content": "How do I authenticate users?"},
+ {"role": "assistant", "content": "You can use OAuth 2.0 for authentication."},
+ {"role": "user", "content": "Any specific recommendations?"},
+ ],
+)
+print(f"Added: {result['added']}, Total: {result['message_count']}")
+```
+
+**CLI**
+
+```bash
+# Add multiple messages to a session
+ov session add-messages a1b2c3d4 '[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"}]'
+
+# ov add-memory also uses the batch interface internally
+ov add-memory '[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"}]'
+```
+
+**Response Example**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "session_id": "a1b2c3d4",
+ "message_count": 5,
+ "added": 3
+ },
+ "time": 0.1
+}
+```
+
+---
+
### used()
#### 1. API Implementation Introduction
diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md
index 56fbdb1c3..173999452 100644
--- a/docs/zh/api/05-sessions.md
+++ b/docs/zh/api/05-sessions.md
@@ -702,6 +702,101 @@ ov session add-message a1b2c3d4 --role user --content "How do I authenticate use
---
+### batch_add_messages()
+
+#### 1. API 实现介绍
+
+向会话中批量添加多条消息。适用于需要一次性写入大量消息的场景(如历史对话导入、记忆抽取),相比逐条调用 `add_message()` 可显著提升性能。
+
+**与 `add_message()` 的区别**:
+- `add_message()`:单次请求添加 1 条消息
+- `batch_add_messages()`:单次请求添加多条消息(上限 100 条),减少网络往返和文件 I/O
+
+**代码入口**:
+- `openviking/session/session.py:Session.add_messages()` - 核心实现
+- `openviking/server/routers/sessions.py:batch_add_messages()` - HTTP 路由
+- `openviking_cli/client/base.py:BaseClient.batch_add_messages()` - Python SDK
+- `crates/ov_cli/src/commands/session.rs:add_messages()` - CLI 命令
+
+#### 2. 接口和参数说明
+
+**参数**
+
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| session_id | str | 是 | - | 会话 ID |
+| messages | List[AddMessageRequest] | 是 | - | 消息列表,每条消息格式与 `add_message()` 相同,最多 100 条 |
+| telemetry | bool | 否 | False | 是否附加操作遥测数据 |
+
+> **注意**:每条消息的格式与 `add_message()` 完全一致,支持 `content`(简单模式)和 `parts`(Parts 模式)。超过 100 条需分批调用。
+
+#### 3. 使用示例
+
+**HTTP API**
+
+```http
+POST /api/v1/sessions/{session_id}/messages/batch
+```
+
+```bash
+# 批量添加多条消息
+curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages/batch \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: your-key" \
+ -d '{
+ "messages": [
+ {"role": "user", "content": "How do I authenticate users?"},
+ {"role": "assistant", "content": "You can use OAuth 2.0 for authentication."},
+ {"role": "user", "content": "Any specific recommendations?"}
+ ]
+ }'
+```
+
+**Python SDK**
+
+```python
+import openviking as ov
+
+client = ov.Client(base_url="http://localhost:1933", api_key="your-key")
+
+# 批量添加消息
+result = await client.batch_add_messages(
+ session_id="a1b2c3d4",
+ messages=[
+ {"role": "user", "content": "How do I authenticate users?"},
+ {"role": "assistant", "content": "You can use OAuth 2.0 for authentication."},
+ {"role": "user", "content": "Any specific recommendations?"},
+ ],
+)
+print(f"Added: {result['added']}, Total: {result['message_count']}")
+```
+
+**CLI**
+
+```bash
+# 向会话中批量添加消息
+ov session add-messages a1b2c3d4 '[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"}]'
+
+# ov add-memory 内部也自动使用批量接口
+ov add-memory '[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"}]'
+```
+
+**响应示例**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "session_id": "a1b2c3d4",
+ "message_count": 5,
+ "added": 3
+ },
+ "time": 0.1
+}
+```
+
+---
+
### used()
#### 1. API 实现介绍
diff --git a/openviking/session/session.py b/openviking/session/session.py
index d1f6eb939..9839fb873 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -794,7 +794,11 @@ class Session:
role, parts, role_id (optional), created_at (optional)
"""
all_messages = []
- for spec in messages_spec:
+ for i, spec in enumerate(messages_spec):
+ if "role" not in spec:
+ raise ValueError(f"messages_spec[{i}]: missing required key 'role'")
+ if "parts" not in spec:
+ raise ValueError(f"messages_spec[{i}]: missing required key 'parts'")
role = spec["role"]
parts = spec["parts"]
role_id = spec.get("role_id")