Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
Feat/add parts support to http api (#270)
SeanZea93ad04e962
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex d2ff520d0..b0df222ea 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -207,8 +207,14 @@ Add a message to the session.| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| role | str | Yes | - | Message role: "user" or "assistant" |-| parts | List[Part] | Yes | - | List of message parts (SDK) |-| content | str | Yes | - | Message text content (HTTP API) |+| parts | List[Part] | Conditional | - | List of message parts (Required for Python SDK; Optional for HTTP API, mutually exclusive with content) |+| content | str | Conditional | - | Message text content (HTTP API simple mode, mutually exclusive with parts) |++> **Note**: HTTP API supports two modes:+> 1. **Simple mode**: Use `content` string (backward compatible)+> 2. **Parts mode**: Use `parts` array (full Part support)+>+> If both `content` and `parts` are provided, `parts` takes precedence.**Part Types (Python SDK)**@@ -260,6 +266,8 @@ session.add_message("assistant", [POST /api/v1/sessions/{session_id}/messages```+**Simple Mode (Backward Compatible)**+```bash# Add user messagecurl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \@@ -269,14 +277,33 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \"role": "user","content": "How do I authenticate users?"}'+```++**Parts Mode (Full Part Support)**++```bash+# Add assistant message with context reference+curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "role": "assistant",+ "parts": [+ {"type": "text", "text": "Based on the authentication guide..."},+ {"type": "context", "uri": "viking://resources/docs/auth/", "context_type": "resource", "abstract": "Auth guide"}+ ]+ }'-# Add assistant message+# Add assistant message with tool callcurl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"role": "assistant",- "content": "You can use OAuth 2.0 for authentication..."+ "parts": [+ {"type": "text", "text": "Let me search for that..."},+ {"type": "tool", "tool_id": "call_123", "tool_name": "search_web", "tool_input": {"query": "OAuth"}, "tool_status": "completed", "tool_output": "Results..."}+ ]}'```diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 7573492ea..ea8289448 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -207,8 +207,14 @@ openviking session delete a1b2c3d4| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| role | str | 是 | - | 消息角色:"user" 或 "assistant" |-| parts | List[Part] | 是 | - | 消息部分列表(SDK) |-| content | str | 是 | - | 消息文本内容(HTTP API) |+| parts | List[Part] | 条件必填 | - | 消息部分列表(Python SDK 必填;HTTP API 可选,与 content 二选一) |+| content | str | 条件必填 | - | 消息文本内容(HTTP API 简单模式,与 parts 二选一) |++> **注意**:HTTP API 支持两种模式:+> 1. **简单模式**:使用 `content` 字符串(向后兼容)+> 2. **Parts 模式**:使用 `parts` 数组(完整 Part 支持)+>+> 如果同时提供 `content` 和 `parts`,`parts` 优先。**Part 类型(Python SDK)**@@ -260,6 +266,8 @@ session.add_message("assistant", [POST /api/v1/sessions/{session_id}/messages```+**简单模式(向后兼容)**+```bash# 添加用户消息curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \@@ -269,14 +277,33 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \"role": "user","content": "How do I authenticate users?"}'+```++**Parts 模式(完整 Part 支持)**++```bash+# 添加带有上下文引用的助手消息+curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "role": "assistant",+ "parts": [+ {"type": "text", "text": "Based on the authentication guide..."},+ {"type": "context", "uri": "viking://resources/docs/auth/", "context_type": "resource", "abstract": "Auth guide"}+ ]+ }'-# 添加助手消息+# 添加带有工具调用的助手消息curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"role": "assistant",- "content": "You can use OAuth 2.0 for authentication..."+ "parts": [+ {"type": "text", "text": "Let me search for that..."},+ {"type": "tool", "tool_id": "call_123", "tool_name": "search_web", "tool_input": {"query": "OAuth"}, "tool_status": "completed", "tool_output": "Results..."}+ ]}'```diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 2523476e6..e35355506 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -6,7 +6,7 @@ Implements BaseClient interface using direct service calls (embedded mode)."""from typing import Any, Dict, List, Optional, Union-from openviking.message.part import TextPart+from openviking.service import OpenVikingServicefrom openviking_cli.client.base import BaseClientfrom openviking_cli.session.user_id import UserIdentifier@@ -145,7 +145,13 @@ class LocalClient(BaseClient):# ============= Content Reading =============async def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:- """Read file content."""+ """Read file content.++ Args:+ uri: Viking URI+ offset: Starting line number (0-indexed). Default 0.+ limit: Number of lines to read. -1 means read to end. Default -1.+ """return await self._service.fs.read(uri, offset=offset, limit=limit)async def abstract(self, uri: str) -> str:@@ -252,11 +258,37 @@ class LocalClient(BaseClient):"""Commit a session (archive and extract memories)."""return await self._service.sessions.commit(session_id)- async def add_message(self, session_id: str, role: str, content: str) -> Dict[str, Any]:- """Add a message to a session."""+ async def add_message(+ self,+ session_id: str,+ role: str,+ content: str | None = None,+ parts: list[dict] | None = None,+ ) -> Dict[str, Any]:+ """Add a message to a session.++ Args:+ session_id: Session ID+ role: Message role ("user" or "assistant")+ content: Text content (simple mode, backward compatible)+ parts: Parts array (full Part support mode)++ If both content and parts are provided, parts takes precedence.+ """+ from openviking.message.part import Part, TextPart, part_from_dict+session = self._service.sessions.session(session_id)await session.load()- session.add_message(role, [TextPart(text=content)])++ message_parts: list[Part]+ if parts is not None:+ message_parts = [part_from_dict(p) for p in parts]+ elif content is not None:+ message_parts = [TextPart(text=content)]+ else:+ raise ValueError("Either content or parts must be provided")++ session.add_message(role, message_parts)return {"session_id": session_id,"message_count": len(session.messages),diff --git a/openviking/message/part.py b/openviking/message/part.pyindex 870debada..334e1c802 100644--- a/openviking/message/part.py+++ b/openviking/message/part.py@@ -48,3 +48,35 @@ class ToolPart:Part = Union[TextPart, ContextPart, ToolPart]+++def part_from_dict(data: dict) -> Part:+ """Convert a dict to a Part object.++ Args:+ data: Dictionary with part data. Must contain 'type' field.++ Returns:+ Part object (TextPart, ContextPart, or ToolPart)+ """+ part_type = data.get("type", "text")+ if part_type == "text":+ return TextPart(text=data.get("text", ""))+ elif part_type == "context":+ return ContextPart(+ uri=data.get("uri", ""),+ context_type=data.get("context_type", "memory"),+ abstract=data.get("abstract", ""),+ )+ elif part_type == "tool":+ return ToolPart(+ tool_id=data.get("tool_id", ""),+ tool_name=data.get("tool_name", ""),+ tool_uri=data.get("tool_uri", ""),+ skill_uri=data.get("skill_uri", ""),+ tool_input=data.get("tool_input"),+ tool_output=data.get("tool_output", ""),+ tool_status=data.get("tool_status", "pending"),+ )+ else:+ return TextPart(text=str(data))diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex 6fc0c6a9d..985c41b1f 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -2,12 +2,12 @@# SPDX-License-Identifier: Apache-2.0"""Sessions endpoints for OpenViking HTTP Server."""-from typing import Any+from typing import Any, Dict, List, Literal, Optionalfrom fastapi import APIRouter, Depends, Path-from pydantic import BaseModel+from pydantic import BaseModel, model_validator-from openviking.message.part import TextPart+from openviking.message.part import Part, TextPart, part_from_dictfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContext@@ -16,11 +16,57 @@ from openviking.server.models import Responserouter = APIRouter(prefix="/api/v1/sessions", tags=["sessions"])+class TextPartRequest(BaseModel):+ """Text part request model."""++ type: Literal["text"] = "text"+ text: str+++class ContextPartRequest(BaseModel):+ """Context part request model."""++ type: Literal["context"] = "context"+ uri: str = ""+ context_type: Literal["memory", "resource", "skill"] = "memory"+ abstract: str = ""+++class ToolPartRequest(BaseModel):+ """Tool part request model."""++ type: Literal["tool"] = "tool"+ tool_id: str = ""+ tool_name: str = ""+ tool_uri: str = ""+ skill_uri: str = ""+ tool_input: Optional[Dict[str, Any]] = None+ tool_output: str = ""+ tool_status: str = "pending"+++PartRequest = TextPartRequest | ContextPartRequest | ToolPartRequest++class AddMessageRequest(BaseModel):- """Request model for adding a message."""+ """Request model for adding a message.++ Supports two modes:+ 1. Simple mode: provide `content` string (backward compatible)+ 2. Parts mode: provide `parts` array for full Part support++ If both are provided, `parts` takes precedence.+ """role: str- content: str+ content: Optional[str] = None+ parts: Optional[List[Dict[str, Any]]] = None++ @model_validator(mode="after")+ def validate_content_or_parts(self) -> "AddMessageRequest":+ if self.content is None and self.parts is None:+ raise ValueError("Either 'content' or 'parts' must be provided")+ return selfdef _to_jsonable(value: Any) -> Any:@@ -119,11 +165,30 @@ async def add_message(session_id: str = Path(..., description="Session ID"),_ctx: RequestContext = Depends(get_request_context),):- """Add a message to a session."""+ """Add a message to a session.++ Supports two modes:+ 1. Simple mode: provide `content` string (backward compatible)+ Example: {"role": "user", "content": "Hello"}++ 2. Parts mode: provide `parts` array for full Part support+ Example: {"role": "assistant", "parts": [+ {"type": "text", "text": "Here's the answer"},+ {"type": "context", "uri": "viking://resources/doc.md", "abstract": "..."}+ ]}++ If both `content` and `parts` are provided, `parts` takes precedence.+ """service = get_service()session = service.sessions.session(session_id)await session.load()- session.add_message(request.role, [TextPart(text=request.content)])++ if request.parts is not None:+ parts = [part_from_dict(p) for p in request.parts]+ else:+ parts = [TextPart(text=request.content or "")]++ session.add_message(request.role, parts)return Response(status="ok",result={diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex d47bcf40e..b0754a704 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -768,6 +768,27 @@ class VikingFS:except Exception:return ""+ def _convert_agfs_error(self, e: Exception, uri: str) -> Exception:+ """Convert AGFSClientError to appropriate Python standard exception.++ This preserves the semantic meaning of errors:+ - "No such file or directory" -> FileNotFoundError+ - "Permission denied" -> PermissionError+ - Connection/timeout errors -> IOError+ - Other errors -> IOError with original message+ """+ error_msg = str(e).lower()+ if "no such file" in error_msg or "not found" in error_msg:+ return FileNotFoundError(f"File not found: {uri}")+ elif "permission denied" in error_msg:+ return PermissionError(f"Permission denied: {uri}")+ elif "connection refused" in error_msg or "server not running" in error_msg:+ return IOError(f"AGFS server unavailable: {e}")+ elif "timeout" in error_msg:+ return IOError(f"Request timeout: {uri}")+ else:+ return IOError(f"Failed to access {uri}: {e}")+def _infer_context_type(self, uri: str):"""Infer context_type from URI."""from openviking_cli.retrieve import ContextType@@ -974,9 +995,17 @@ class VikingFS:uri: Viking URIoffset: Starting line number (0-indexed). Default 0.limit: Number of lines to read. -1 means read to end. Default -1.++ Raises:+ FileNotFoundError: If the file does not exist.+ PermissionError: If permission denied.+ IOError: For other I/O related errors (connection, timeout, etc.)."""path = self._uri_to_path(uri)- content = self.agfs.read(path)+ try:+ content = self.agfs.read(path)+ except Exception as e:+ raise self._convert_agfs_error(e, uri) from etext = self._handle_agfs_content(content)if offset == 0 and limit == -1:return text@@ -988,12 +1017,18 @@ class VikingFS:self,uri: str,) -> bytes:- """Read single binary file."""+ """Read single binary file.++ Raises:+ FileNotFoundError: If the file does not exist.+ PermissionError: If permission denied.+ IOError: For other I/O related errors (connection, timeout, etc.).+ """path = self._uri_to_path(uri)try:return self._handle_agfs_read(self.agfs.read(path))except Exception as e:- raise FileNotFoundError(f"Failed to read {uri}: {e}")+ raise self._convert_agfs_error(e, uri) from easync def write_file_bytes(self,@@ -1065,7 +1100,7 @@ class VikingFS:try:entries = self._ls_entries(path)except Exception as e:- raise FileNotFoundError(f"Failed to list {uri}: {e}")+ raise self._convert_agfs_error(e, uri) from e# basic infonow = datetime.now()all_entries = []@@ -1114,7 +1149,7 @@ class VikingFS:all_entries.append(new_entry)return all_entriesexcept Exception as e:- raise FileNotFoundError(f"Failed to list {uri}: {e}")+ raise self._convert_agfs_error(e, uri) from easync def move_file(self,diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex 13e44b31d..4619f7886 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -418,7 +418,13 @@ class AsyncHTTPClient(BaseClient):# ============= Content Reading =============async def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:- """Read file content."""+ """Read file content.++ Args:+ uri: Viking URI+ offset: Starting line number (0-indexed). Default 0.+ limit: Number of lines to read. -1 means read to end. Default -1.+ """uri = VikingURI.normalize(uri)response = await self._http.get("/api/v1/content/read",@@ -583,11 +589,34 @@ class AsyncHTTPClient(BaseClient):response = await self._http.post(f"/api/v1/sessions/{session_id}/commit")return self._handle_response(response)- async def add_message(self, session_id: str, role: str, content: str) -> Dict[str, Any]:- """Add a message to a session."""+ async def add_message(+ self,+ session_id: str,+ role: str,+ content: str | None = None,+ parts: list[dict] | None = None,+ ) -> Dict[str, Any]:+ """Add a message to a session.++ Args:+ session_id: Session ID+ role: Message role ("user" or "assistant")+ content: Text content (simple mode, backward compatible)+ parts: Parts array (full Part support mode)++ If both content and parts are provided, parts takes precedence.+ """+ payload: Dict[str, Any] = {"role": role}+ if parts is not None:+ payload["parts"] = parts+ elif content is not None:+ payload["content"] = content+ else:+ raise ValueError("Either content or parts must be provided")+response = await self._http.post(f"/api/v1/sessions/{session_id}/messages",- json={"role": role, "content": content},+ json=payload,)return self._handle_response(response)