Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,38 @@ EXECUTOR_MANAGER_PORT=8001
# Used by executor manager to connect to executor containers in host mode
# DOCKER_HOST_ADDR=host.docker.internal

# =============================================================================
# KNOWLEDGE RUNTIME
# =============================================================================

# Knowledge Runtime port (default: 8200)
# Used by both docker-compose and start.sh
KNOWLEDGE_RUNTIME_PORT=8200

# RAG Runtime Mode (IMPORTANT for remote mode)
# - "local" (default): RAG operations execute locally in Backend
# - "remote" or {"default":"remote"}: Forward RAG operations to knowledge_runtime
# For remote mode with knowledge_runtime service, set to:
# RAG_RUNTIME_MODE={"default":"remote"}

# Backend internal URL for Knowledge Runtime to fetch content
# In docker-compose, this defaults to http://backend:8000
# In local dev, this defaults to http://localhost:8000
# BACKEND_INTERNAL_URL=http://backend:8000

# Knowledge Runtime URL for Backend to call
# In docker-compose, this defaults to http://knowledge_runtime:8200
# In local dev, this defaults to http://localhost:8200
# KNOWLEDGE_RUNTIME_URL=http://knowledge_runtime:8200

# Content fetching timeout in seconds (default: 120)
# CONTENT_FETCH_TIMEOUT=120

# Logging configuration (file logging enabled by default)
# LOG_FILE_ENABLED=true
# LOG_DIR=/app/logs
# LOG_LEVEL=INFO

# =============================================================================
# MCP (Model Context Protocol)
# =============================================================================
Expand Down
20 changes: 20 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Wegent is an open-source AI-native operating system for defining, organizing, an
- **Executor**: Task execution engine (Claude Code, Agno, Dify, ImageValidator)
- **Executor Manager**: Task orchestration via Docker
- **Chat Shell**: Lightweight AI chat engine for Chat Shell type (LangGraph + multi-LLM)
- **Knowledge Runtime**: Standalone RAG HTTP service called by Backend (reuses knowledge_engine)
- **Shared**: Common utilities, models, and cryptography

**Core principles:**
Expand Down Expand Up @@ -542,6 +543,24 @@ t('actions.save') // Ambiguous - which namespace?
- `package` - Python package imported by Backend
- `cli` - Command-line interface for interactive chat

### Knowledge Runtime

**Tech:** FastAPI, HTTP client, reuses knowledge_engine

**Purpose:** Standalone HTTP service for RAG operations. Backend calls this service instead of using knowledge_engine directly.

**Endpoints:**
- `GET /internal/rag/health` - Health check
- `POST /internal/rag/index` - Index document
- `POST /internal/rag/query` - Query documents
- `POST /internal/rag/delete-document-index` - Delete document index
- `POST /internal/rag/purge-knowledge-index` - Purge knowledge base
- `POST /internal/rag/drop-knowledge-index` - Drop physical index
- `POST /internal/rag/all-chunks` - List all chunks
- `POST /internal/rag/test-connection` - Test storage connection

**Port:** 8200 (default)


---

Expand Down Expand Up @@ -579,6 +598,7 @@ cd backend && uv run pytest
cd executor && uv run pytest
cd executor_manager && uv run pytest
cd chat_shell && uv run pytest
cd knowledge_runtime && uv run pytest
cd shared && uv run pytest
cd frontend && npm test

Expand Down
2 changes: 0 additions & 2 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,6 @@ def parse_rag_runtime_mode(cls, v: Any) -> str | dict[str, str]:
EXECUTOR_MANAGER_URL: str = "http://localhost:8001"
# Chat Shell service authentication token (only used when CHAT_SHELL_MODE="http")
CHAT_SHELL_TOKEN: str = ""
# Internal service authentication token (for HTTP mode communication)
INTERNAL_SERVICE_TOKEN: str = ""
# Backend internal URL (for service-to-service communication)
# Used by chat_shell to download skill binaries
BACKEND_INTERNAL_URL: str = "http://localhost:8000"
Expand Down
4 changes: 4 additions & 0 deletions backend/app/services/rag/gateway_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ def get_query_gateway() -> RagGateway:

def get_delete_gateway() -> RagGateway:
return _build_gateway(settings.get_rag_runtime_mode("delete"))


def get_list_chunks_gateway() -> RagGateway:
return _build_gateway(settings.get_rag_runtime_mode("list_chunks"))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
6 changes: 0 additions & 6 deletions backend/app/services/rag/remote_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,16 @@ def __init__(
self,
*,
base_url: str | None = None,
token: str | None = None,
timeout: float = 30.0,
) -> None:
self._base_url = (base_url or settings.KNOWLEDGE_RUNTIME_URL).rstrip("/")
self._token = token if token is not None else settings.INTERNAL_SERVICE_TOKEN
self._timeout = timeout

def _build_headers(self) -> dict[str, str]:
return {"Authorization": f"Bearer {self._token}"}

async def _post_model(self, path: str, payload: Any) -> dict[str, Any]:
try:
async with httpx.AsyncClient(timeout=self._timeout) as client:
response = await client.post(
f"{self._base_url}{path}",
headers=self._build_headers(),
json=payload.model_dump(mode="json", exclude_none=True),
)
except httpx.RequestError as exc:
Expand Down
110 changes: 35 additions & 75 deletions backend/app/services/rag/retrieval_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -722,119 +722,79 @@ async def get_all_chunks_from_knowledge_base(
query: Optional[str] = None,
metadata_condition: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
"""
Get all chunks from a knowledge base without permission check.
"""Get all chunks from a knowledge base without permission check.

This method is used for smart context injection where we need all
chunks from a knowledge base to determine if direct injection is possible.

Uses gateway (local or remote based on RAG_RUNTIME_MODE) instead of
directly accessing storage backend, enabling proper architecture separation.

Args:
knowledge_base_id: Knowledge base ID
db: Database session
max_chunks: Maximum number of chunks to retrieve (safety limit)
query: Optional query string for logging purposes
metadata_condition: Optional metadata filter conditions

Returns:
List of chunk dicts with content, title, chunk_id, doc_ref, metadata

Raises:
ValueError: If knowledge base not found or configuration invalid
"""
from app.models.kind import Kind

# Get knowledge base directly without permission check
kb = (
db.query(Kind)
.filter(
Kind.id == knowledge_base_id,
Kind.kind == "KnowledgeBase",
Kind.is_active,
)
.first()
)

if not kb:
raise ValueError(f"Knowledge base {knowledge_base_id} not found")
from app.services.rag.gateway_factory import get_list_chunks_gateway
from app.services.rag.runtime_resolver import RagRuntimeResolver

resolved_config = self._build_runtime_query_config(
kb=kb,
# Build runtime spec via resolver
runtime_resolver = RagRuntimeResolver()
spec = runtime_resolver.build_internal_list_chunks_runtime_spec(
db=db,
)
storage_backend = create_storage_backend_from_runtime_config(
resolved_config.retriever_config
knowledge_base_id=knowledge_base_id,
max_chunks=max_chunks,
query=query,
metadata_condition=metadata_condition,
)

# Use knowledge base ID as knowledge_id
knowledge_id = str(kb.id)
backend_name = storage_backend.__class__.__name__
index_name = ""
try:
index_name = storage_backend.get_index_name(
knowledge_id, user_id=kb.user_id
)
except Exception as e:
logger.warning(
"[RAG] Failed to precompute index name for get_all_chunks: kb_id=%s, "
"knowledge_id=%s, backend=%s, error=%s",
knowledge_base_id,
knowledge_id,
backend_name,
e,
)

query_log = f", query={query[:50]}..." if query else ""
logger.info(
"[RAG] get_all_chunks start: kb_id=%s, kb_name=%s, knowledge_id=%s, "
"namespace=%s, backend=%s, retriever=%s/%s, index_name=%s, max_chunks=%s, "
"kb_owner_id=%s%s",
"[RAG] get_all_chunks start: kb_id=%s, max_chunks=%s%s",
knowledge_base_id,
kb.name,
knowledge_id,
kb.namespace,
backend_name,
resolved_config.retriever_config.namespace,
resolved_config.retriever_config.name,
index_name or "<unknown>",
max_chunks,
kb.user_id,
query_log,
)

# Get all chunks from storage backend
# Run in thread pool to avoid event loop conflicts
chunks = await asyncio.to_thread(
storage_backend.get_all_chunks,
knowledge_id=knowledge_id,
max_chunks=max_chunks,
user_id=kb.user_id,
metadata_condition=metadata_condition,
)
# Use gateway to get chunks (supports local and remote modes)
rag_gateway = get_list_chunks_gateway()
result = await rag_gateway.list_chunks(spec, db=db)
Comment thread
sunnights marked this conversation as resolved.
Resolved

chunks = result.get("chunks", [])
total = result.get("total", 0)

logger.info(
"[RAG] get_all_chunks completed: kb_id=%s, kb_name=%s, chunk_count=%s, "
"backend=%s, index_name=%s%s",
"[RAG] get_all_chunks completed: kb_id=%s, chunk_count=%s%s",
knowledge_base_id,
kb.name,
len(chunks),
backend_name,
index_name or "<unknown>",
total,
query_log,
)
if not chunks:
logger.warning(
"[RAG] get_all_chunks returned empty result: kb_id=%s, kb_name=%s, "
"knowledge_id=%s, backend=%s, index_name=%s, retriever=%s/%s%s",
"[RAG] get_all_chunks returned empty result: kb_id=%s%s",
knowledge_base_id,
kb.name,
knowledge_id,
backend_name,
index_name or "<unknown>",
resolved_config.retriever_config.namespace,
resolved_config.retriever_config.name,
query_log,
)

return chunks
# Convert RemoteListChunkRecord to dict format for backward compatibility
return [
{
"content": chunk.get("content", ""),
"title": chunk.get("title", ""),
"chunk_id": chunk.get("chunk_id"),
"doc_ref": chunk.get("doc_ref"),
"metadata": chunk.get("metadata"),
}
for chunk in chunks
]


# Backward compatibility alias
Expand Down
5 changes: 5 additions & 0 deletions docker-compose.build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ services:
build:
dockerfile: docker/executor_manager/Dockerfile
pull_policy: build

knowledge_runtime:
build:
dockerfile: docker/knowledge_runtime/Dockerfile
pull_policy: build
48 changes: 45 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,13 @@ services:
restart: always
ports:
- "${BACKEND_PORT:-8000}:8000"
# volumes:
# To customize init data, uncomment the following line to override the built-in data:
# - ./custom_init_data:/app/init_data:ro
volumes:
- ./logs/backend:/app/logs
environment:
# Logging configuration
LOG_FILE_ENABLED: ${LOG_FILE_ENABLED:-true}
LOG_DIR: /app/logs
LOG_LEVEL: ${LOG_LEVEL:-INFO}
# Disable litellm network request for model cost map to prevent startup blocking
LITELLM_LOCAL_MODEL_COST_MAP: "True"
ENVIRONMENT: ${BACKEND_ENVIRONMENT:-development}
Expand Down Expand Up @@ -110,6 +113,11 @@ services:
# INTERNAL_SERVICE_TOKEN: ${INTERNAL_SERVICE_TOKEN:-chat-shell-token}
# Internal URL for MCP and other internal service calls (use container name in Docker)
BACKEND_INTERNAL_URL: http://backend:8000
# Knowledge Runtime URL for RAG operations
KNOWLEDGE_RUNTIME_URL: ${KNOWLEDGE_RUNTIME_URL:-http://knowledge_runtime:8200}
# RAG Runtime Mode: "local" (default) or "remote" to use knowledge_runtime
# For remote mode, set to: {"default":"remote"}
RAG_RUNTIME_MODE: ${RAG_RUNTIME_MODE:-local}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
# Task Dispatch Configuration
# Mode: 'push' (default) or 'pull' (deprecated, executor_manager polls)
TASK_DISPATCH_MODE: ${TASK_DISPATCH_MODE:-push}
Expand Down Expand Up @@ -255,6 +263,40 @@ services:
networks:
- wegent-network

knowledge_runtime:
Comment thread
sunnights marked this conversation as resolved.
Resolved
image: ghcr.io/wecode-ai/wegent-knowledge-runtime:latest
pull_policy: ${DOCKER_PULL_POLICY:-always}
container_name: wegent-knowledge-runtime
restart: always
ports:
- "${KNOWLEDGE_RUNTIME_PORT:-8200}:8200"
environment:
- TZ=${TZ:-Asia/Shanghai}
# Backend URL for fetching content
- BACKEND_INTERNAL_URL=${BACKEND_INTERNAL_URL:-http://backend:8000}
# Content fetching timeout in seconds
- CONTENT_FETCH_TIMEOUT=${CONTENT_FETCH_TIMEOUT:-120}
# Logging configuration
- LOG_FILE_ENABLED=${LOG_FILE_ENABLED:-true}
- LOG_DIR=${LOG_DIR:-/app/logs}
- LOG_LEVEL=${LOG_LEVEL:-INFO}
# OpenTelemetry Configuration (uncomment to enable)
# - OTEL_ENABLED=true
# - OTEL_SERVICE_NAME=wegent-knowledge-runtime
# - OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
depends_on:
- backend
volumes:
- ./logs/knowledge_runtime:/app/logs
networks:
- wegent-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8200/internal/rag/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s

volumes:
mysql_data:
driver: local
Expand Down
42 changes: 42 additions & 0 deletions docker/knowledge_runtime/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# SPDX-FileCopyrightText: 2026 Weibo, Inc.
#
# SPDX-License-Identifier: Apache-2.0

FROM ghcr.io/wecode-ai/wegent-base-python3.12:latest

# Set working directory
WORKDIR /app

# Copy and install shared module first
COPY shared /app/shared
RUN uv pip install --system --no-cache /app/shared

# Copy and install knowledge_engine module
COPY knowledge_engine /app/knowledge_engine
RUN uv pip install --system --no-cache /app/knowledge_engine

# Copy pyproject.toml and install dependencies
# Remove [tool.uv.sources] section as dependencies are already installed
COPY knowledge_runtime/pyproject.toml .
RUN sed -i '/\[tool\.uv\.sources\]/,/^$/d' pyproject.toml && \
uv pip install --system --no-cache -r pyproject.toml

# Copy application code
COPY knowledge_runtime/knowledge_runtime /app/knowledge_runtime

# Environment variables
ENV PORT=8200
ENV HOST=0.0.0.0

# Create log directory
RUN mkdir -p /app/logs

# Expose port
EXPOSE ${PORT}

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:${PORT}/internal/rag/health || exit 1

# Start command
CMD ["sh", "-c", "exec uvicorn knowledge_runtime.main:app --host ${HOST} --port ${PORT}"]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Loading
Loading