|
|
@ -0,0 +1,46 @@
|
|||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main ./cmd/server"
|
||||
delay = 1000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations", "node_modules", "docs"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
# 使用 full_bin 来设置环境变量(从父进程继承)
|
||||
full_bin = ""
|
||||
include_dir = []
|
||||
include_ext = ["go", "tpl", "tmpl", "html", "yaml"]
|
||||
include_file = []
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
poll = false
|
||||
poll_interval = 0
|
||||
rerun = false
|
||||
rerun_delay = 500
|
||||
send_interrupt = false
|
||||
stop_on_error = false
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
main_only = false
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
keep_scroll = true
|
||||
|
||||
|
|
@ -59,6 +59,10 @@ TENANT_AES_KEY=weknorarag-api-key-secret-secret
|
|||
# 是否开启知识图谱构建和检索(构建阶段需调用大模型,耗时较长)
|
||||
ENABLE_GRAPH_RAG=false
|
||||
|
||||
|
||||
# 配置 JWT_SECRET 用于前端登录刷新Token
|
||||
JWT_SECRET=weknora-jwt-secret
|
||||
|
||||
# MinIO端口
|
||||
# MINIO_PORT=9000
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ node_modules/
|
|||
# 临时文件
|
||||
tmp/
|
||||
temp/
|
||||
logs/
|
||||
*.pid
|
||||
|
||||
WeKnora
|
||||
/models/
|
||||
|
|
@ -36,4 +38,6 @@ data/files/
|
|||
### macOS
|
||||
# General
|
||||
.DS_Store
|
||||
PROGRESS_RU.md
|
||||
/scripts/scale_dev_jobs.sh
|
||||
server
|
||||
frontend/.vite
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
version: 2
|
||||
linters-settings:
|
||||
lll:
|
||||
line-length: 120
|
||||
tab-width: 4
|
||||
linters:
|
||||
enable:
|
||||
- lll # 控制行宽
|
||||
- govet
|
||||
- revive
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- gofumpt
|
||||
80
CHANGELOG.md
|
|
@ -2,6 +2,85 @@
|
|||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [0.2.0] - 2025-12-05
|
||||
|
||||
### 🚀 Major Features
|
||||
- **NEW**: ReACT Agent Mode
|
||||
- Added ReACT Agent mode that can use built-in tools to retrieve knowledge bases
|
||||
- Support for calling user-configured MCP tools and web search tools to access external services
|
||||
- Multiple iterations and reflection to provide comprehensive summary reports
|
||||
- Cross-knowledge base retrieval support, allowing selection of multiple knowledge bases
|
||||
- **NEW**: Model Management System
|
||||
- Centralized model configuration
|
||||
- Added model selection in knowledge base settings page
|
||||
- Built-in model sharing functionality across multiple tenants
|
||||
- Tenants can use shared models but are restricted from editing or viewing model details
|
||||
- **NEW**: Multi-Type Knowledge Base Support
|
||||
- Support for creating FAQ and document knowledge base types
|
||||
- Folder import functionality
|
||||
- URL import functionality
|
||||
- Tag management system
|
||||
- Online knowledge entry capability
|
||||
- **NEW**: FAQ Knowledge Base
|
||||
- New FAQ-type knowledge base
|
||||
- Batch import and batch delete functionality
|
||||
- Online FAQ entry
|
||||
- Online FAQ testing capability
|
||||
- **NEW**: Conversation Strategy Configuration
|
||||
- Support for configuring Agent models and normal mode models
|
||||
- Configurable retrieval thresholds
|
||||
- Online Prompt configuration
|
||||
- Precise control over multi-turn conversation behavior and retrieval execution methods
|
||||
- **NEW**: Web Search Integration
|
||||
- Support for extensible web search engines
|
||||
- Built-in DuckDuckGo search engine
|
||||
- **NEW**: MCP Tool Integration
|
||||
- Support for extending Agent capabilities through MCP
|
||||
- Built-in uvx and npx MCP launcher tools
|
||||
- Support for three transport methods: Stdio, HTTP Streamable, and SSE
|
||||
|
||||
### 🎨 UI/UX Improvements
|
||||
- **REDESIGNED**: Conversation interface with Agent mode/normal mode switching
|
||||
- Added Agent mode/normal mode toggle in conversation input box
|
||||
- Support for enabling/disabling web search
|
||||
- Support for selecting conversation models
|
||||
- **REDESIGNED**: Login page UI adjustments
|
||||
- **ENHANCED**: Session list with time-ordered grouping
|
||||
- **NEW**: Quick Actions area for unified UI visual effects
|
||||
- **IMPROVED**: Knowledge base list cards
|
||||
- Display knowledge base type, knowledge count, build status
|
||||
- Show advanced settings capabilities
|
||||
- **NEW**: Breadcrumb navigation in FAQ and document list pages
|
||||
- Quick navigation and knowledge base switching
|
||||
- **ENHANCED**: Knowledge base settings in document list page
|
||||
- **REDESIGNED**: Knowledge base settings page
|
||||
- Separate configuration for knowledge base type, models, chunking methods, and advanced settings
|
||||
- **NEW**: Global settings page for permissions
|
||||
- Configure models, web search, MCP services, and Agent mode
|
||||
- **IMPROVED**: Chunk details page display
|
||||
- **NEW**: Knowledge classification and tagging support
|
||||
- **ENHANCED**: Conversation flow page with tool call execution process display
|
||||
|
||||
### ⚡ Infrastructure Upgrades
|
||||
- **NEW**: MQ-based async task management
|
||||
- Introduced MQ for async task state maintenance
|
||||
- Ensures task integrity even after service abnormal restart
|
||||
- **NEW**: Automatic database migration
|
||||
- Support for automatic database schema and data migration during version upgrades
|
||||
- **NEW**: Fast development mode
|
||||
- Added docker-compose.dev.yml file for quick development environment startup
|
||||
- Improved development workflow efficiency
|
||||
- **IMPROVED**: Log structure optimization
|
||||
- **NEW**: Event subscription and publishing mechanism
|
||||
- Support for event handling at various steps in user query processing flow
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
- Various bug fixes and stability improvements
|
||||
|
||||
### 📚 Documentation Updates
|
||||
- Updated README files with v0.2.0 highlights (English, Chinese, Japanese)
|
||||
- Added latest updates section in all README files
|
||||
- Updated architecture diagrams and feature matrices
|
||||
## [0.1.6] - 2025-11-24
|
||||
|
||||
### Document Parser Enhancements
|
||||
|
|
@ -174,6 +253,7 @@ All notable changes to this project will be documented in this file.
|
|||
- Docker Compose for quick startup and service orchestration.
|
||||
- MCP server support for integrating with MCP-compatible clients.
|
||||
|
||||
[0.2.0]: https://github.com/Tencent/WeKnora/tree/v0.2.0
|
||||
[0.1.4]: https://github.com/Tencent/WeKnora/tree/v0.1.4
|
||||
[0.1.3]: https://github.com/Tencent/WeKnora/tree/v0.1.3
|
||||
[0.1.2]: https://github.com/Tencent/WeKnora/tree/v0.1.2
|
||||
|
|
|
|||
60
Makefile
|
|
@ -1,4 +1,4 @@
|
|||
.PHONY: help build run test clean docker-build-app docker-build-docreader docker-build-frontend docker-build-all docker-run migrate-up migrate-down docker-restart docker-stop start-all stop-all start-ollama stop-ollama build-images build-images-app build-images-docreader build-images-frontend clean-images check-env list-containers pull-images show-platform
|
||||
.PHONY: help build run test clean docker-build-app docker-build-docreader docker-build-frontend docker-build-all docker-run migrate-up migrate-down docker-restart docker-stop start-all stop-all start-ollama stop-ollama build-images build-images-app build-images-docreader build-images-frontend clean-images check-env list-containers pull-images show-platform dev-start dev-stop dev-restart dev-logs dev-status dev-app dev-frontend
|
||||
|
||||
# Show help
|
||||
help:
|
||||
|
|
@ -46,6 +46,15 @@ help:
|
|||
@echo " list-containers 列出运行中的容器"
|
||||
@echo " pull-images 拉取最新镜像"
|
||||
@echo " show-platform 显示当前构建平台"
|
||||
@echo ""
|
||||
@echo "开发模式(推荐):"
|
||||
@echo " dev-start 启动开发环境基础设施(仅启动依赖服务)"
|
||||
@echo " dev-stop 停止开发环境"
|
||||
@echo " dev-restart 重启开发环境"
|
||||
@echo " dev-logs 查看开发环境日志"
|
||||
@echo " dev-status 查看开发环境状态"
|
||||
@echo " dev-app 启动后端应用(本地运行,需先运行 dev-start)"
|
||||
@echo " dev-frontend 启动前端(本地运行,需先运行 dev-start)"
|
||||
|
||||
# Go related variables
|
||||
BINARY_NAME=WeKnora
|
||||
|
|
@ -158,6 +167,33 @@ migrate-up:
|
|||
migrate-down:
|
||||
./scripts/migrate.sh down
|
||||
|
||||
migrate-version:
|
||||
./scripts/migrate.sh version
|
||||
|
||||
migrate-create:
|
||||
@if [ -z "$(name)" ]; then \
|
||||
echo "Error: migration name is required"; \
|
||||
echo "Usage: make migrate-create name=your_migration_name"; \
|
||||
exit 1; \
|
||||
fi
|
||||
./scripts/migrate.sh create $(name)
|
||||
|
||||
migrate-force:
|
||||
@if [ -z "$(version)" ]; then \
|
||||
echo "Error: version is required"; \
|
||||
echo "Usage: make migrate-force version=4"; \
|
||||
exit 1; \
|
||||
fi
|
||||
./scripts/migrate.sh force $(version)
|
||||
|
||||
migrate-goto:
|
||||
@if [ -z "$(version)" ]; then \
|
||||
echo "Error: version is required"; \
|
||||
echo "Usage: make migrate-goto version=3"; \
|
||||
exit 1; \
|
||||
fi
|
||||
./scripts/migrate.sh goto $(version)
|
||||
|
||||
# Generate API documentation
|
||||
docs:
|
||||
swag init -g $(MAIN_PATH)/main.go -o ./docs
|
||||
|
|
@ -212,4 +248,26 @@ show-platform:
|
|||
@echo "当前系统架构: $(shell uname -m)"
|
||||
@echo "Docker构建平台: $(PLATFORM)"
|
||||
|
||||
# Development mode commands
|
||||
dev-start:
|
||||
./scripts/dev.sh start
|
||||
|
||||
dev-stop:
|
||||
./scripts/dev.sh stop
|
||||
|
||||
dev-restart:
|
||||
./scripts/dev.sh restart
|
||||
|
||||
dev-logs:
|
||||
./scripts/dev.sh logs
|
||||
|
||||
dev-status:
|
||||
./scripts/dev.sh status
|
||||
|
||||
dev-app:
|
||||
./scripts/dev.sh app
|
||||
|
||||
dev-frontend:
|
||||
./scripts/dev.sh frontend
|
||||
|
||||
|
||||
|
|
|
|||
73
README.md
|
|
@ -15,7 +15,7 @@
|
|||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="Version" src="https://img.shields.io/badge/version-0.1.3-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="Version" src="https://img.shields.io/badge/version-0.2.0-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
|
@ -41,6 +41,18 @@ It adopts a modular architecture that combines multimodal preprocessing, semanti
|
|||
|
||||
**Website:** https://weknora.weixin.qq.com
|
||||
|
||||
## ✨ Latest Updates
|
||||
|
||||
**v0.2.0 Highlights:**
|
||||
|
||||
- 🤖 **Agent Mode**: New ReACT Agent mode that can call built-in tools, MCP tools, and web search, providing comprehensive summary reports through multiple iterations and reflection
|
||||
- 📚 **Multi-Type Knowledge Bases**: Support for FAQ and document knowledge base types, with new features including folder import, URL import, tag management, and online entry
|
||||
- ⚙️ **Conversation Strategy**: Support for configuring Agent models, normal mode models, retrieval thresholds, and Prompts, with precise control over multi-turn conversation behavior
|
||||
- 🌐 **Web Search**: Support for extensible web search engines with built-in DuckDuckGo search engine
|
||||
- 🔌 **MCP Tool Integration**: Support for extending Agent capabilities through MCP, with built-in uvx and npx launchers, supporting multiple transport methods
|
||||
- 🎨 **New UI**: Optimized conversation interface with Agent mode/normal mode switching, tool call process display, and comprehensive knowledge base management interface upgrade
|
||||
- ⚡ **Infrastructure Upgrade**: Introduced MQ async task management, support for automatic database migration, and fast development mode
|
||||
|
||||
## 🔒 Security Notice
|
||||
|
||||
**Important:** Starting from v0.1.3, WeKnora includes login authentication functionality to enhance system security. For production deployments, we strongly recommend:
|
||||
|
|
@ -52,16 +64,21 @@ It adopts a modular architecture that combines multimodal preprocessing, semanti
|
|||
|
||||
## 🏗️ Architecture
|
||||
|
||||

|
||||

|
||||
|
||||
WeKnora employs a modern modular design to build a complete document understanding and retrieval pipeline. The system primarily includes document parsing, vector processing, retrieval engine, and large model inference as core modules, with each component being flexibly configurable and extendable.
|
||||
|
||||
## 🎯 Key Features
|
||||
|
||||
- **🤖 Agent Mode**: Support for ReACT Agent mode that can use built-in tools to retrieve knowledge bases, MCP tools, and web search tools to access external services, providing comprehensive summary reports through multiple iterations and reflection
|
||||
- **🔍 Precise Understanding**: Structured content extraction from PDFs, Word documents, images and more into unified semantic views
|
||||
- **🧠 Intelligent Reasoning**: Leverages LLMs to understand document context and user intent for accurate Q&A and multi-turn conversations
|
||||
- **📚 Multi-Type Knowledge Bases**: Support for FAQ and document knowledge base types, with folder import, URL import, tag management, and online entry capabilities
|
||||
- **🔧 Flexible Extension**: All components from parsing and embedding to retrieval and generation are decoupled for easy customization
|
||||
- **⚡ Efficient Retrieval**: Hybrid retrieval strategies combining keywords, vectors, and knowledge graphs
|
||||
- **⚡ Efficient Retrieval**: Hybrid retrieval strategies combining keywords, vectors, and knowledge graphs, with cross-knowledge base retrieval support
|
||||
- **🌐 Web Search**: Support for extensible web search engines with built-in DuckDuckGo search engine
|
||||
- **🔌 MCP Tool Integration**: Support for extending Agent capabilities through MCP, with built-in uvx and npx launchers, supporting multiple transport methods
|
||||
- **⚙️ Conversation Strategy**: Support for configuring Agent models, normal mode models, retrieval thresholds, and Prompts, with precise control over multi-turn conversation behavior
|
||||
- **🎯 User-Friendly**: Intuitive web interface and standardized APIs for zero technical barriers
|
||||
- **🔒 Secure & Controlled**: Support for local deployment and private cloud, ensuring complete data sovereignty
|
||||
|
||||
|
|
@ -79,15 +96,22 @@ WeKnora employs a modern modular design to build a complete document understandi
|
|||
|
||||
| Module | Support | Description |
|
||||
|---------|---------|------|
|
||||
| Agent Mode | ✅ ReACT Agent Mode | Support for using built-in tools to retrieve knowledge bases, MCP tools, and web search, with cross-knowledge base retrieval and multiple iterations |
|
||||
| Knowledge Base Types | ✅ FAQ / Document | Support for creating FAQ and document knowledge base types, with folder import, URL import, tag management, and online entry |
|
||||
| Document Formats | ✅ PDF / Word / Txt / Markdown / Images (with OCR / Caption) | Support for structured and unstructured documents with text extraction from images |
|
||||
| Model Management | ✅ Centralized configuration, built-in model sharing | Centralized model configuration with model selection in knowledge base settings, support for multi-tenant shared built-in models |
|
||||
| Embedding Models | ✅ Local models, BGE / GTE APIs, etc. | Customizable embedding models, compatible with local deployment and cloud vector generation APIs |
|
||||
| Vector DB Integration | ✅ PostgreSQL (pgvector), Elasticsearch | Support for mainstream vector index backends, flexible switching for different retrieval scenarios |
|
||||
| Retrieval Strategies | ✅ BM25 / Dense Retrieval / GraphRAG | Support for sparse/dense recall and knowledge graph-enhanced retrieval with customizable retrieve-rerank-generate pipelines |
|
||||
| LLM Integration | ✅ Support for Qwen, DeepSeek, etc., with thinking/non-thinking mode switching | Compatible with local models (e.g., via Ollama) or external API services with flexible inference configuration |
|
||||
| Conversation Strategy | ✅ Agent models, normal mode models, retrieval thresholds, Prompt configuration | Support for configuring Agent models, normal mode models, retrieval thresholds, online Prompt configuration, precise control over multi-turn conversation behavior |
|
||||
| Web Search | ✅ Extensible search engines, DuckDuckGo | Support for extensible web search engines with built-in DuckDuckGo search engine |
|
||||
| MCP Tools | ✅ uvx, npx launchers, Stdio/HTTP Streamable/SSE | Support for extending Agent capabilities through MCP, with built-in uvx and npx launchers, supporting three transport methods |
|
||||
| QA Capabilities | ✅ Context-aware, multi-turn dialogue, prompt templates | Support for complex semantic modeling, instruction control and chain-of-thought Q&A with configurable prompts and context windows |
|
||||
| E2E Testing | ✅ Retrieval+generation process visualization and metric evaluation | End-to-end testing tools for evaluating recall hit rates, answer coverage, BLEU/ROUGE and other metrics |
|
||||
| Deployment Modes | ✅ Support for local deployment / Docker images | Meets private, offline deployment and flexible operation requirements |
|
||||
| User Interfaces | ✅ Web UI + RESTful API | Interactive interface and standard API endpoints, suitable for both developers and business users |
|
||||
| Deployment Modes | ✅ Support for local deployment / Docker images | Meets private, offline deployment and flexible operation requirements, with fast development mode support |
|
||||
| User Interfaces | ✅ Web UI + RESTful API | Interactive interface and standard API endpoints, with Agent mode/normal mode switching and tool call process display |
|
||||
| Task Management | ✅ MQ async tasks, automatic database migration | MQ-based async task state maintenance, support for automatic database schema and data migration during version upgrades |
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
|
|
@ -264,15 +288,19 @@ On your first visit, you will be automatically redirected to the registration/lo
|
|||
|
||||
<table>
|
||||
<tr>
|
||||
<td><b>Knowledge Upload</b><br/><img src="./docs/images/knowledges.png" alt="Knowledge Upload Interface"></td>
|
||||
<td><b>Q&A Entry</b><br/><img src="./docs/images/qa.png" alt="Q&A Entry Interface"></td>
|
||||
<td><b>Knowledge Base Management</b><br/><img src="./docs/images/knowledgebases.png" alt="Knowledge Base Management"></td>
|
||||
<td><b>Conversation Settings</b><br/><img src="./docs/images/settings.png" alt="Conversation Settings"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2"><b>Rich Text & Image Responses</b><br/><img src="./docs/images/answer.png" alt="Rich Answer Interface"></td>
|
||||
<td colspan="2"><b>Agent Mode Tool Call Process</b><br/><img src="./docs/images/agent-qa.png" alt="Agent Mode Tool Call Process"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
**Knowledge Base Management:** Support for dragging and dropping various documents, automatically identifying document structures and extracting core knowledge to establish indexes. The system clearly displays processing progress and document status, achieving efficient knowledge base management.
|
||||
**Knowledge Base Management:** Support for creating FAQ and document knowledge base types, with multiple import methods including drag-and-drop, folder import, and URL import. Automatically identifies document structures and extracts core knowledge to establish indexes. Supports tag management and online entry. The system clearly displays processing progress and document status, achieving efficient knowledge base management.
|
||||
|
||||
**Agent Mode:** Support for ReACT Agent mode that can use built-in tools to retrieve knowledge bases, call user-configured MCP tools and web search tools to access external services, providing comprehensive summary reports through multiple iterations and reflection. Supports cross-knowledge base retrieval, allowing selection of multiple knowledge bases for simultaneous retrieval.
|
||||
|
||||
**Conversation Strategy:** Support for configuring Agent models, normal mode models, retrieval thresholds, and online Prompt configuration, with precise control over multi-turn conversation behavior and retrieval execution methods. The conversation input box supports Agent mode/normal mode switching, enabling/disabling web search, and selecting conversation models.
|
||||
|
||||
### Document Knowledge Graph
|
||||
|
||||
|
|
@ -292,6 +320,33 @@ Detailed API documentation is available at: [API Docs](./docs/API.md)
|
|||
|
||||
## 🧭 Developer Guide
|
||||
|
||||
### ⚡ Fast Development Mode (Recommended)
|
||||
|
||||
If you need to frequently modify code, **you don't need to rebuild Docker images every time**! Use fast development mode:
|
||||
|
||||
```bash
|
||||
# Method 1: Using Make commands (Recommended)
|
||||
make dev-start # Start infrastructure
|
||||
make dev-app # Start backend (new terminal)
|
||||
make dev-frontend # Start frontend (new terminal)
|
||||
|
||||
# Method 2: One-click start
|
||||
./scripts/quick-dev.sh
|
||||
|
||||
# Method 3: Using scripts
|
||||
./scripts/dev.sh start # Start infrastructure
|
||||
./scripts/dev.sh app # Start backend (new terminal)
|
||||
./scripts/dev.sh frontend # Start frontend (new terminal)
|
||||
```
|
||||
|
||||
**Development Advantages:**
|
||||
- ✅ Frontend modifications auto hot-reload (no restart needed)
|
||||
- ✅ Backend modifications quick restart (5-10 seconds, supports Air hot-reload)
|
||||
- ✅ No need to rebuild Docker images
|
||||
- ✅ Support IDE breakpoint debugging
|
||||
|
||||
**Detailed Documentation:** [Development Environment Quick Start](./docs/开发指南.md)
|
||||
|
||||
### 📁 Directory Structure
|
||||
|
||||
```
|
||||
|
|
|
|||
73
README_CN.md
|
|
@ -15,7 +15,7 @@
|
|||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="版本" src="https://img.shields.io/badge/version-0.1.3-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="版本" src="https://img.shields.io/badge/version-0.2.0-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
|
@ -41,6 +41,18 @@
|
|||
|
||||
**官网:** https://weknora.weixin.qq.com
|
||||
|
||||
## ✨ 最新更新
|
||||
|
||||
**v0.2.0 版本亮点:**
|
||||
|
||||
- 🤖 **Agent模式**:新增ReACT Agent模式,支持调用内置工具、MCP工具和网络搜索,通过多次迭代和反思提供全面总结报告
|
||||
- 📚 **多类型知识库**:支持FAQ和文档两种类型知识库,新增文件夹导入、URL导入、标签管理和在线录入功能
|
||||
- ⚙️ **对话策略**:支持配置Agent模型、普通模式模型、检索阈值和Prompt,精确控制多轮对话行为
|
||||
- 🌐 **网络搜索**:支持可扩展的网络搜索引擎,内置DuckDuckGo搜索引擎
|
||||
- 🔌 **MCP工具集成**:支持通过MCP扩展Agent能力,内置uvx、npx启动工具,支持多种传输方式
|
||||
- 🎨 **全新UI**:优化对话界面,支持Agent模式/普通模式切换,展示工具调用过程,知识库管理界面全面升级
|
||||
- ⚡ **底层升级**:引入MQ异步任务管理,支持数据库自动迁移,提供快速开发模式
|
||||
|
||||
## 🔒 安全声明
|
||||
|
||||
**重要提示:** 从 v0.1.3 版本开始,WeKnora 提供了登录鉴权功能,以增强系统安全性。在生产环境部署时,我们强烈建议:
|
||||
|
|
@ -52,16 +64,21 @@
|
|||
|
||||
## 🏗️ 架构设计
|
||||
|
||||

|
||||

|
||||
|
||||
WeKnora 采用现代化模块化设计,构建了一条完整的文档理解与检索流水线。系统主要包括文档解析、向量化处理、检索引擎和大模型推理等核心模块,每个组件均可灵活配置与扩展。
|
||||
|
||||
## 🎯 核心特性
|
||||
|
||||
- **🤖 Agent模式**:支持ReACT Agent模式,可调用内置工具检索知识库、MCP工具和网络搜索,通过多次迭代和反思给出全面总结报告
|
||||
- **🔍 精准理解**:支持 PDF、Word、图片等文档的结构化内容提取,统一构建语义视图
|
||||
- **🧠 智能推理**:借助大语言模型理解文档上下文与用户意图,支持精准问答与多轮对话
|
||||
- **📚 多类型知识库**:支持FAQ和文档两种类型知识库,支持文件夹导入、URL导入、标签管理和在线录入
|
||||
- **🔧 灵活扩展**:从解析、嵌入、召回到生成全流程解耦,便于灵活集成与定制扩展
|
||||
- **⚡ 高效检索**:混合多种检索策略:关键词、向量、知识图谱
|
||||
- **⚡ 高效检索**:混合多种检索策略:关键词、向量、知识图谱,支持跨知识库检索
|
||||
- **🌐 网络搜索**:支持可扩展的网络搜索引擎,内置DuckDuckGo搜索引擎
|
||||
- **🔌 MCP工具集成**:支持通过MCP扩展Agent能力,内置uvx、npx启动工具,支持多种传输方式
|
||||
- **⚙️ 对话策略**:支持配置Agent模型、普通模式模型、检索阈值和Prompt,精确控制多轮对话行为
|
||||
- **🎯 简单易用**:直观的Web界面与标准API,零技术门槛快速上手
|
||||
- **🔒 安全可控**:支持本地化与私有云部署,数据完全自主可控
|
||||
|
||||
|
|
@ -79,15 +96,22 @@ WeKnora 采用现代化模块化设计,构建了一条完整的文档理解与
|
|||
|
||||
| 功能模块 | 支持情况 | 说明 |
|
||||
|---------|---------|------|
|
||||
| Agent模式 | ✅ ReACT Agent模式 | 支持使用内置工具检索知识库、MCP工具和网络搜索,跨知识库检索,多次迭代和反思 |
|
||||
| 知识库类型 | ✅ FAQ / 文档 | 支持创建FAQ和文档两种类型知识库,支持文件夹导入、URL导入、标签管理和在线录入 |
|
||||
| 文档格式支持 | ✅ PDF / Word / Txt / Markdown / 图片(含 OCR / Caption) | 支持多种结构化与非结构化文档内容解析,支持图文混排与图像文字提取 |
|
||||
| 模型管理 | ✅ 集中配置、内置模型共享 | 模型集中配置,知识库设置页增加模型选择,支持多租户共享内置模型 |
|
||||
| 嵌入模型支持 | ✅ 本地模型、BGE / GTE API 等 | 支持自定义 embedding 模型,兼容本地部署与云端向量生成接口 |
|
||||
| 向量数据库接入 | ✅ PostgreSQL(pgvector)、Elasticsearch | 支持主流向量索引后端,可灵活切换与扩展,适配不同检索场景 |
|
||||
| 检索机制 | ✅ BM25 / Dense Retrieve / GraphRAG | 支持稠密/稀疏召回、知识图谱增强检索等多种策略,可自由组合召回-重排-生成流程 |
|
||||
| 大模型集成 | ✅ 支持 Qwen、DeepSeek 等,思考/非思考模式切换 | 可接入本地大模型(如 Ollama 启动)或调用外部 API 服务,支持推理模式灵活配置 |
|
||||
| 对话策略 | ✅ Agent模型、普通模式模型、检索阈值、Prompt配置 | 支持配置Agent模型、普通模式所需的模型、检索阈值,在线配置Prompt,精确控制多轮对话行为 |
|
||||
| 网络搜索 | ✅ 可扩展搜索引擎、DuckDuckGo | 支持可扩展的网络搜索引擎,内置DuckDuckGo搜索引擎 |
|
||||
| MCP工具 | ✅ uvx、npx启动工具,Stdio/HTTP Streamable/SSE | 支持通过MCP扩展Agent能力,内置uvx、npx两种MCP启动工具,支持三种传输方式 |
|
||||
| 问答能力 | ✅ 上下文感知、多轮对话、提示词模板 | 支持复杂语义建模、指令控制与链式问答,可配置提示词与上下文窗口 |
|
||||
| 端到端测试支持 | ✅ 检索+生成过程可视化与指标评估 | 提供一体化链路测试工具,支持评估召回命中率、回答覆盖度、BLEU / ROUGE 等主流指标 |
|
||||
| 部署模式 | ✅ 支持本地部署 / Docker 镜像 | 满足私有化、离线部署与灵活运维的需求 |
|
||||
| 用户界面 | ✅ Web UI + RESTful API | 提供交互式界面与标准 API 接口,适配开发者与业务用户使用习惯 |
|
||||
| 部署模式 | ✅ 支持本地部署 / Docker 镜像 | 满足私有化、离线部署与灵活运维的需求,支持快速开发模式 |
|
||||
| 用户界面 | ✅ Web UI + RESTful API | 提供交互式界面与标准 API 接口,支持Agent模式/普通模式切换,展示工具调用过程 |
|
||||
| 任务管理 | ✅ MQ异步任务、数据库自动迁移 | 引入MQ对异步任务进行状态维护,支持版本升级时的数据库表结构和数据自动迁移 |
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
|
|
@ -266,15 +290,19 @@ http://localhost
|
|||
|
||||
<table>
|
||||
<tr>
|
||||
<td><b>知识上传</b><br/><img src="./docs/images/knowledges.png" alt="知识上传界面"></td>
|
||||
<td><b>知识问答入口</b><br/><img src="./docs/images/qa.png" alt="知识问答入口"></td>
|
||||
<td><b>知识库管理</b><br/><img src="./docs/images/knowledgebases.png" alt="知识库管理"></td>
|
||||
<td><b>对话设置</b><br/><img src="./docs/images/settings.png" alt="对话设置"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2"><b>图文结果回答</b><br/><img src="./docs/images/answer.png" alt="图文结果回答"></td>
|
||||
<td colspan="2"><b>Agent模式工具调用过程</b><br/><img src="./docs/images/agent-qa.png" alt="Agent模式工具调用过程"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
**知识库管理:** 支持拖拽上传各类文档,自动识别文档结构并提取核心知识,建立索引。系统清晰展示处理进度和文档状态,实现高效的知识库管理。
|
||||
**知识库管理:** 支持创建FAQ和文档两种类型知识库,支持拖拽上传、文件夹导入、URL导入等多种方式,自动识别文档结构并提取核心知识,建立索引。支持标签管理和在线录入,系统清晰展示处理进度和文档状态,实现高效的知识库管理。
|
||||
|
||||
**Agent模式:** 支持开启ReACT Agent模式,可使用内置工具检索知识库,调用用户配置的MCP工具和网络搜索工具访问外部服务,通过多次迭代和反思,最终给出全面的总结报告。支持跨知识库检索,可以选择多个知识库同时检索。
|
||||
|
||||
**对话策略:** 支持配置Agent模型、普通模式所需的模型、检索阈值,支持在线配置Prompt,精确控制多轮对话行为和检索召回执行方式。对话输入框支持Agent模式/普通模式切换,支持开启和关闭网络搜索,支持选择对话模型。
|
||||
|
||||
### 文档知识图谱
|
||||
|
||||
|
|
@ -294,6 +322,33 @@ WeKnora 支持将文档转化为知识图谱,展示文档中不同段落之间
|
|||
|
||||
## 🧭 开发指南
|
||||
|
||||
### ⚡ 快速开发模式(推荐)
|
||||
|
||||
如果你需要频繁修改代码,**不需要每次重新构建 Docker 镜像**!使用快速开发模式:
|
||||
|
||||
```bash
|
||||
# 方式 1:使用 Make 命令(推荐)
|
||||
make dev-start # 启动基础设施
|
||||
make dev-app # 启动后端(新终端)
|
||||
make dev-frontend # 启动前端(新终端)
|
||||
|
||||
# 方式 2:一键启动
|
||||
./scripts/quick-dev.sh
|
||||
|
||||
# 方式 3:使用脚本
|
||||
./scripts/dev.sh start # 启动基础设施
|
||||
./scripts/dev.sh app # 启动后端(新终端)
|
||||
./scripts/dev.sh frontend # 启动前端(新终端)
|
||||
```
|
||||
|
||||
**开发优势:**
|
||||
- ✅ 前端修改自动热重载(无需重启)
|
||||
- ✅ 后端修改快速重启(5-10秒,支持 Air 热重载)
|
||||
- ✅ 无需重新构建 Docker 镜像
|
||||
- ✅ 支持 IDE 断点调试
|
||||
|
||||
**详细文档:** [开发环境快速入门](./docs/开发指南.md)
|
||||
|
||||
### 📁 项目目录结构
|
||||
|
||||
```
|
||||
|
|
|
|||
75
README_JA.md
|
|
@ -15,7 +15,7 @@
|
|||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="バージョン" src="https://img.shields.io/badge/version-0.1.3-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="バージョン" src="https://img.shields.io/badge/version-0.2.0-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
|
@ -41,9 +41,21 @@
|
|||
|
||||
**公式サイト:** https://weknora.weixin.qq.com
|
||||
|
||||
## ✨ 最新アップデート
|
||||
|
||||
**v0.2.0 バージョンのハイライト:**
|
||||
|
||||
- 🤖 **Agentモード**:新規ReACT Agentモードを追加、組み込みツール、MCPツール、Web検索を呼び出し、複数回の反復とリフレクションを通じて包括的なサマリーレポートを提供
|
||||
- 📚 **複数タイプのナレッジベース**:FAQとドキュメントの2種類のナレッジベースをサポート、フォルダーインポート、URLインポート、タグ管理、オンライン入力機能を新規追加
|
||||
- ⚙️ **対話戦略**:Agentモデル、通常モードモデル、検索閾値、Promptの設定をサポート、マルチターン対話の動作を精密に制御
|
||||
- 🌐 **Web検索**:拡張可能なWeb検索エンジンをサポート、DuckDuckGo検索エンジンを組み込み
|
||||
- 🔌 **MCPツール統合**:MCPを通じてAgent機能を拡張、uvx、npx起動ツールを組み込み、複数の転送方式をサポート
|
||||
- 🎨 **新UI**:対話インターフェースを最適化、Agentモード/通常モードの切り替え、ツール呼び出しプロセスの表示、ナレッジベース管理インターフェースの全面的なアップグレード
|
||||
- ⚡ **インフラストラクチャのアップグレード**:MQ非同期タスク管理を導入、データベース自動マイグレーションをサポート、高速開発モードを提供
|
||||
|
||||
## 🔒 セキュリティ通知
|
||||
|
||||
**重要:** v0.1.3バージョンより、WeKnoraにはシステムセキュリティを強化するためのログイン認証機能が含まれています。本番環境でのデプロイメントにおいて、以下を強く推奨します:
|
||||
**重要:** v0.1.3バージョンより、WeKnoraにはシステムセキュリティを強化するためのログイン認証機能が含まれています。v0.2.0では、さらに多くの機能強化と改善が追加されました。本番環境でのデプロイメントにおいて、以下を強く推奨します:
|
||||
|
||||
- WeKnoraサービスはパブリックインターネットではなく、内部/プライベートネットワーク環境にデプロイしてください
|
||||
- 重要な情報漏洩を防ぐため、サービスを直接パブリックネットワークに公開することは避けてください
|
||||
|
|
@ -52,16 +64,21 @@
|
|||
|
||||
## 🏗️ アーキテクチャ設計
|
||||
|
||||

|
||||

|
||||
|
||||
WeKnoraは現代的なモジュラー設計を採用し、完全な文書理解と検索パイプラインを構築しています。システムには主に文書解析、ベクトル化処理、検索エンジン、大規模モデル推論などのコアモジュールが含まれ、各コンポーネントは柔軟に設定および拡張できます。
|
||||
|
||||
## 🎯 コア機能
|
||||
|
||||
- **🤖 Agentモード**:ReACT Agentモードをサポート、組み込みツールでナレッジベースを検索、MCPツールとWeb検索を呼び出し、複数回の反復とリフレクションを通じて包括的なサマリーレポートを提供
|
||||
- **🔍 正確な理解**:PDF、Word、画像などの文書の構造化コンテンツ抽出をサポートし、統一された意味ビューを構築
|
||||
- **🧠 インテリジェント推論**:大規模言語モデルを活用して文書コンテキストとユーザーの意図を理解し、正確なQ&Aとマルチターン対話をサポート
|
||||
- **📚 複数タイプのナレッジベース**:FAQとドキュメントの2種類のナレッジベースをサポート、フォルダーインポート、URLインポート、タグ管理、オンライン入力機能
|
||||
- **🔧 柔軟な拡張**:解析、埋め込み、検索から生成までの全プロセスを分離し、柔軟な統合とカスタマイズ拡張を容易に
|
||||
- **⚡ 効率的な検索**:複数の検索戦略のハイブリッド:キーワード、ベクトル、ナレッジグラフ
|
||||
- **⚡ 効率的な検索**:複数の検索戦略のハイブリッド:キーワード、ベクトル、ナレッジグラフ、クロスナレッジベース検索をサポート
|
||||
- **🌐 Web検索**:拡張可能なWeb検索エンジンをサポート、DuckDuckGo検索エンジンを組み込み
|
||||
- **🔌 MCPツール統合**:MCPを通じてAgent機能を拡張、uvx、npx起動ツールを組み込み、複数の転送方式をサポート
|
||||
- **⚙️ 対話戦略**:Agentモデル、通常モードモデル、検索閾値、Promptの設定をサポート、マルチターン対話の動作を精密に制御
|
||||
- **🎯 使いやすさ**:直感的なWebインターフェースと標準API、技術的な障壁なしで素早く開始可能
|
||||
- **🔒 セキュアで制御可能**:ローカルおよびプライベートクラウドデプロイメントをサポート、データは完全に自己管理可能
|
||||
|
||||
|
|
@ -79,15 +96,22 @@ WeKnoraは現代的なモジュラー設計を採用し、完全な文書理解
|
|||
|
||||
| 機能モジュール | サポート状況 | 説明 |
|
||||
|---------|---------|------|
|
||||
| Agentモード | ✅ ReACT Agentモード | 組み込みツールでナレッジベースを検索、MCPツールとWeb検索を使用、クロスナレッジベース検索、複数回の反復とリフレクションをサポート |
|
||||
| ナレッジベースタイプ | ✅ FAQ / ドキュメント | FAQとドキュメントの2種類のナレッジベースの作成をサポート、フォルダーインポート、URLインポート、タグ管理、オンライン入力機能 |
|
||||
| 文書フォーマットサポート | ✅ PDF / Word / Txt / Markdown / 画像(OCR / Caption含む) | 様々な構造化・非構造化文書コンテンツの解析をサポート、図文混在と画像文字抽出をサポート |
|
||||
| モデル管理 | ✅ 集中設定、組み込みモデル共有 | モデルの集中設定、ナレッジベース設定ページにモデル選択を追加、マルチテナント間での組み込みモデル共有をサポート |
|
||||
| 埋め込みモデルサポート | ✅ ローカルモデル、BGE / GTE API等 | カスタムembeddingモデルをサポート、ローカルデプロイとクラウドベクトル生成インターフェースに対応 |
|
||||
| ベクトルデータベース接続 | ✅ PostgreSQL(pgvector)、Elasticsearch | 主流のベクトルインデックスバックエンドをサポート、柔軟な切り替えと拡張が可能、異なる検索シナリオに適応 |
|
||||
| 検索メカニズム | ✅ BM25 / Dense Retrieve / GraphRAG | 密・疎検索、ナレッジグラフ強化検索など複数の戦略をサポート、検索-再ランキング-生成プロセスを自由に組み合わせ可能 |
|
||||
| 大規模モデル統合 | ✅ Qwen、DeepSeek等をサポート、思考/非思考モード切り替え | ローカル大規模モデル(Ollama起動など)に接続可能、または外部APIサービスを呼び出し、推論モードの柔軟な設定をサポート |
|
||||
| 対話戦略 | ✅ Agentモデル、通常モードモデル、検索閾値、Prompt設定 | Agentモデル、通常モードに必要なモデル、検索閾値の設定をサポート、オンラインPrompt設定、マルチターン対話の動作を精密に制御 |
|
||||
| Web検索 | ✅ 拡張可能な検索エンジン、DuckDuckGo | 拡張可能なWeb検索エンジンをサポート、DuckDuckGo検索エンジンを組み込み |
|
||||
| MCPツール | ✅ uvx、npx起動ツール、Stdio/HTTP Streamable/SSE | MCPを通じてAgent機能を拡張、uvx、npxの2種類のMCP起動ツールを組み込み、3種類の転送方式をサポート |
|
||||
| Q&A能力 | ✅ コンテキスト認識、マルチターン対話、プロンプトテンプレート | 複雑な意味モデリング、指示制御、チェーンQ&Aをサポート、プロンプトとコンテキストウィンドウを設定可能 |
|
||||
| エンドツーエンドテストサポート | ✅ 検索+生成プロセスの可視化と指標評価 | 一体化されたリンクテストツールを提供、リコール的中率、回答カバレッジ、BLEU / ROUGE等の主流指標の評価をサポート |
|
||||
| デプロイメントモード | ✅ ローカルデプロイメント / Dockerイメージをサポート | プライベート化、オフラインデプロイメント、柔軟な運用保守のニーズに対応 |
|
||||
| ユーザーインターフェース | ✅ Web UI + RESTful API | インタラクティブインターフェースと標準APIインターフェースを提供、開発者とビジネスユーザーの使用習慣に適応 |
|
||||
| デプロイメントモード | ✅ ローカルデプロイメント / Dockerイメージ | プライベート化、オフラインデプロイメント、柔軟な運用保守のニーズに対応、高速開発モードをサポート |
|
||||
| ユーザーインターフェース | ✅ Web UI + RESTful API | インタラクティブインターフェースと標準APIインターフェースを提供、Agentモード/通常モードの切り替え、ツール呼び出しプロセスの表示をサポート |
|
||||
| タスク管理 | ✅ MQ非同期タスク、データベース自動マイグレーション | MQによる非同期タスクの状態維持を導入、バージョンアップ時のデータベーステーブル構造とデータの自動マイグレーションをサポート |
|
||||
|
||||
## 🚀 クイックスタート
|
||||
|
||||
|
|
@ -265,15 +289,19 @@ http://localhost
|
|||
|
||||
<table>
|
||||
<tr>
|
||||
<td><b>ナレッジアップロード</b><br/><img src="./docs/images/knowledges.png" alt="ナレッジアップロードインターフェース"></td>
|
||||
<td><b>ナレッジQ&Aエントリー</b><br/><img src="./docs/images/qa.png" alt="ナレッジQ&Aエントリー"></td>
|
||||
<td><b>ナレッジベース管理</b><br/><img src="./docs/images/knowledgebases.png" alt="ナレッジベース管理"></td>
|
||||
<td><b>対話設定</b><br/><img src="./docs/images/settings.png" alt="対話設定"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2"><b>図文結果回答</b><br/><img src="./docs/images/answer.png" alt="図文結果回答"></td>
|
||||
<td colspan="2"><b>Agentモードツール呼び出しプロセス</b><br/><img src="./docs/images/agent-qa.png" alt="Agentモードツール呼び出しプロセス"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
**ナレッジベース管理:** 各種文書のドラッグ&ドロップアップロードをサポートし、文書構造を自動認識してコア知識を抽出し、インデックスを構築します。システムは処理の進行状況と文書のステータスを明確に表示し、効率的なナレッジベース管理を実現します。
|
||||
**ナレッジベース管理:** FAQとドキュメントの2種類のナレッジベースの作成をサポート、ドラッグ&ドロップアップロード、フォルダーインポート、URLインポートなど複数の方法をサポート、文書構造を自動認識してコア知識を抽出し、インデックスを構築します。タグ管理とオンライン入力をサポート、システムは処理の進行状況と文書のステータスを明確に表示し、効率的なナレッジベース管理を実現します。
|
||||
|
||||
**Agentモード:** ReACT Agentモードの有効化をサポート、組み込みツールでナレッジベースを検索、ユーザーが設定したMCPツールとWeb検索ツールを呼び出して外部サービスにアクセス、複数回の反復とリフレクションを通じて、最終的に包括的なサマリーレポートを提供します。クロスナレッジベース検索をサポート、複数のナレッジベースを同時に検索できます。
|
||||
|
||||
**対話戦略:** Agentモデル、通常モードに必要なモデル、検索閾値の設定をサポート、オンラインPrompt設定をサポート、マルチターン対話の動作と検索リコールの実行方法を精密に制御します。対話入力ボックスはAgentモード/通常モードの切り替えをサポート、Web検索の有効化/無効化をサポート、対話モデルの選択をサポートします。
|
||||
|
||||
### 文書ナレッジグラフ
|
||||
|
||||
|
|
@ -294,6 +322,33 @@ WeKnoraは文書をナレッジグラフに変換し、文書内の異なる段
|
|||
|
||||
## 🧭 開発ガイド
|
||||
|
||||
### ⚡ 高速開発モード(推奨)
|
||||
|
||||
コードを頻繁に変更する必要がある場合、**Dockerイメージを毎回再構築する必要はありません**!高速開発モードを使用してください:
|
||||
|
||||
```bash
|
||||
# 方法1:Makeコマンドを使用(推奨)
|
||||
make dev-start # インフラストラクチャを起動
|
||||
make dev-app # バックエンドを起動(新しいターミナル)
|
||||
make dev-frontend # フロントエンドを起動(新しいターミナル)
|
||||
|
||||
# 方法2:ワンクリック起動
|
||||
./scripts/quick-dev.sh
|
||||
|
||||
# 方法3:スクリプトを使用
|
||||
./scripts/dev.sh start # インフラストラクチャを起動
|
||||
./scripts/dev.sh app # バックエンドを起動(新しいターミナル)
|
||||
./scripts/dev.sh frontend # フロントエンドを起動(新しいターミナル)
|
||||
```
|
||||
|
||||
**開発の利点:**
|
||||
- ✅ フロントエンドの変更は自動ホットリロード(再起動不要)
|
||||
- ✅ バックエンドの変更は高速再起動(5-10秒、Airホットリロードをサポート)
|
||||
- ✅ Dockerイメージを再構築する必要がない
|
||||
- ✅ IDEブレークポイントデバッグをサポート
|
||||
|
||||
**詳細ドキュメント:** [開発環境クイックスタート](./docs/开发指南.md)
|
||||
|
||||
### 📁 プロジェクトディレクトリ構造
|
||||
|
||||
```
|
||||
|
|
|
|||
123
client/README.md
|
|
@ -11,9 +11,10 @@
|
|||
3. **知识管理**:添加、获取和删除知识内容
|
||||
4. **租户管理**:租户的CRUD操作
|
||||
5. **知识问答**:支持普通问答和流式问答
|
||||
6. **分块管理**:查询、更新和删除知识分块
|
||||
7. **消息管理**:获取和删除会话消息
|
||||
8. **模型管理**:创建、获取、更新和删除模型
|
||||
6. **Agent问答**:支持基于Agent的智能问答,包含思考过程、工具调用和反思
|
||||
7. **分块管理**:查询、更新和删除知识分块
|
||||
8. **消息管理**:获取和删除会话消息
|
||||
9. **模型管理**:创建、获取、更新和删除模型
|
||||
|
||||
## 使用方法
|
||||
|
||||
|
|
@ -114,6 +115,122 @@ if err != nil {
|
|||
}
|
||||
```
|
||||
|
||||
### 示例:Agent智能问答
|
||||
|
||||
Agent问答提供更强大的智能对话能力,支持工具调用、思考过程展示和自我反思。
|
||||
|
||||
```go
|
||||
// 创建Agent会话
|
||||
agentSession := apiClient.NewAgentSession(session.ID)
|
||||
|
||||
// 进行Agent问答,带完整事件处理
|
||||
err := agentSession.Ask(context.Background(), "搜索机器学习相关知识并总结要点",
|
||||
func(resp *client.AgentStreamResponse) error {
|
||||
switch resp.ResponseType {
|
||||
case client.AgentResponseTypeThinking:
|
||||
// Agent正在思考
|
||||
if resp.Done {
|
||||
fmt.Printf("💭 思考: %s\n", resp.Content)
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeToolCall:
|
||||
// Agent调用工具
|
||||
if resp.Data != nil {
|
||||
toolName := resp.Data["tool_name"]
|
||||
fmt.Printf("🔧 调用工具: %v\n", toolName)
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeToolResult:
|
||||
// 工具执行结果
|
||||
fmt.Printf("✓ 工具结果: %s\n", resp.Content)
|
||||
|
||||
case client.AgentResponseTypeReferences:
|
||||
// 知识引用
|
||||
if resp.KnowledgeReferences != nil {
|
||||
fmt.Printf("📚 找到 %d 条相关知识\n", len(resp.KnowledgeReferences))
|
||||
for _, ref := range resp.KnowledgeReferences {
|
||||
fmt.Printf(" - [%.3f] %s\n", ref.Score, ref.KnowledgeTitle)
|
||||
}
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeAnswer:
|
||||
// 最终答案(流式输出)
|
||||
fmt.Print(resp.Content)
|
||||
if resp.Done {
|
||||
fmt.Println() // 结束后换行
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeReflection:
|
||||
// Agent的自我反思
|
||||
if resp.Done {
|
||||
fmt.Printf("🤔 反思: %s\n", resp.Content)
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeError:
|
||||
// 错误信息
|
||||
fmt.Printf("❌ 错误: %s\n", resp.Content)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
// 处理错误
|
||||
}
|
||||
|
||||
// 简化版:只关心最终答案
|
||||
var finalAnswer string
|
||||
err = agentSession.Ask(context.Background(), "什么是深度学习?",
|
||||
func(resp *client.AgentStreamResponse) error {
|
||||
if resp.ResponseType == client.AgentResponseTypeAnswer {
|
||||
finalAnswer += resp.Content
|
||||
}
|
||||
return nil
|
||||
})
|
||||
```
|
||||
|
||||
### Agent事件类型说明
|
||||
|
||||
| 事件类型 | 说明 | 何时触发 |
|
||||
|---------|------|---------|
|
||||
| `AgentResponseTypeThinking` | Agent思考过程 | Agent分析问题和制定计划时 |
|
||||
| `AgentResponseTypeToolCall` | 工具调用 | Agent决定使用某个工具时 |
|
||||
| `AgentResponseTypeToolResult` | 工具执行结果 | 工具执行完成后 |
|
||||
| `AgentResponseTypeReferences` | 知识引用 | 检索到相关知识时 |
|
||||
| `AgentResponseTypeAnswer` | 最终答案 | Agent生成回答时(流式) |
|
||||
| `AgentResponseTypeReflection` | 自我反思 | Agent评估自己的回答时 |
|
||||
| `AgentResponseTypeError` | 错误 | 发生错误时 |
|
||||
|
||||
### Agent问答测试工具
|
||||
|
||||
我们提供了一个交互式命令行工具用于测试Agent功能:
|
||||
|
||||
```bash
|
||||
cd client/cmd/agent_test
|
||||
go build -o agent_test
|
||||
./agent_test -url http://localhost:8080 -kb <knowledge_base_id>
|
||||
```
|
||||
|
||||
该工具支持:
|
||||
- 创建和管理会话
|
||||
- 交互式Agent问答
|
||||
- 实时显示所有Agent事件
|
||||
- 性能统计和调试信息
|
||||
|
||||
详细使用说明请参考 `client/cmd/agent_test/README.md`。
|
||||
|
||||
### Agent问答的高级用法
|
||||
|
||||
更多高级用法示例,请参考 `agent_example.go` 文件,包括:
|
||||
- 基础Agent问答
|
||||
- 工具调用跟踪
|
||||
- 知识引用捕获
|
||||
- 完整事件跟踪
|
||||
- 自定义错误处理
|
||||
- 流取消控制
|
||||
- 多会话管理
|
||||
|
||||
```
|
||||
|
||||
### 示例:管理模型
|
||||
|
||||
```go
|
||||
|
|
|
|||
|
|
@ -0,0 +1,164 @@
|
|||
// Package client provides the implementation for interacting with the WeKnora API
|
||||
// The Agent related interfaces are used to manage agent-based question-answering
|
||||
package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AgentQARequest agent Q&A request payload.
|
||||
type AgentQARequest struct {
|
||||
Query string `json:"query"` // Required query text
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Optional KBs for this query
|
||||
AgentEnabled bool `json:"agent_enabled"` // Whether to run in agent mode
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether to enable web search
|
||||
SummaryModelID string `json:"summary_model_id,omitempty"` // Optional summary model override
|
||||
MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list
|
||||
}
|
||||
|
||||
// AgentResponseType defines the type of agent response
|
||||
type AgentResponseType string
|
||||
|
||||
const (
|
||||
AgentResponseTypeThinking AgentResponseType = "thinking"
|
||||
AgentResponseTypeToolCall AgentResponseType = "tool_call"
|
||||
AgentResponseTypeToolResult AgentResponseType = "tool_result"
|
||||
AgentResponseTypeReferences AgentResponseType = "references"
|
||||
AgentResponseTypeAnswer AgentResponseType = "answer"
|
||||
AgentResponseTypeReflection AgentResponseType = "reflection"
|
||||
AgentResponseTypeError AgentResponseType = "error"
|
||||
)
|
||||
|
||||
// AgentStreamResponse agent streaming response
|
||||
type AgentStreamResponse struct {
|
||||
ID string `json:"id"` // Unique identifier
|
||||
ResponseType AgentResponseType `json:"response_type"` // Response type
|
||||
Content string `json:"content,omitempty"` // Current content fragment
|
||||
Done bool `json:"done"` // Whether completed
|
||||
KnowledgeReferences []*SearchResult `json:"knowledge_references"` // Knowledge references
|
||||
Data map[string]interface{} `json:"data,omitempty"` // Additional event data
|
||||
}
|
||||
|
||||
// AgentEventCallback is called for each streaming event
|
||||
// Return error to stop processing the stream
|
||||
type AgentEventCallback func(*AgentStreamResponse) error
|
||||
|
||||
// AgentQAStream performs agent-based Q&A with SSE streaming using default agent settings.
|
||||
// Deprecated: prefer AgentQAStreamWithRequest to customize agent behavior.
|
||||
func (c *Client) AgentQAStream(ctx context.Context, sessionID string, query string, callback AgentEventCallback) error {
|
||||
req := &AgentQARequest{
|
||||
Query: query,
|
||||
AgentEnabled: true,
|
||||
}
|
||||
return c.AgentQAStreamWithRequest(ctx, sessionID, req, callback)
|
||||
}
|
||||
|
||||
// AgentQAStreamWithRequest performs agent-based Q&A with SSE streaming using the full request payload.
|
||||
func (c *Client) AgentQAStreamWithRequest(ctx context.Context,
|
||||
sessionID string, request *AgentQARequest, callback AgentEventCallback,
|
||||
) error {
|
||||
if request == nil {
|
||||
return fmt.Errorf("agent QA request cannot be nil")
|
||||
}
|
||||
if strings.TrimSpace(request.Query) == "" {
|
||||
return fmt.Errorf("agent QA query cannot be empty")
|
||||
}
|
||||
|
||||
path := fmt.Sprintf("/api/v1/agent-chat/%s", sessionID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, request, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Process SSE stream
|
||||
return c.processAgentSSEStream(resp.Body, callback)
|
||||
}
|
||||
|
||||
// processAgentSSEStream processes the SSE stream and invokes callback for each event
|
||||
func (c *Client) processAgentSSEStream(reader io.Reader, callback AgentEventCallback) error {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
var dataBuffer string
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
|
||||
// Empty line indicates the end of an event
|
||||
if line == "" {
|
||||
if dataBuffer != "" {
|
||||
var streamResponse AgentStreamResponse
|
||||
if err := json.Unmarshal([]byte(dataBuffer), &streamResponse); err != nil {
|
||||
return fmt.Errorf("failed to parse SSE data: %w", err)
|
||||
}
|
||||
|
||||
if err := callback(&streamResponse); err != nil {
|
||||
return err
|
||||
}
|
||||
dataBuffer = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Process lines with event: prefix (for future use)
|
||||
if strings.HasPrefix(line, "event:") {
|
||||
// Event type is available but not currently used
|
||||
// eventType := strings.TrimSpace(line[6:])
|
||||
continue
|
||||
}
|
||||
|
||||
// Process lines with data: prefix
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
dataBuffer = strings.TrimSpace(line[5:]) // Remove "data:" prefix
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("failed to read SSE stream: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AgentSession is a wrapper for agent-based interactions
|
||||
type AgentSession struct {
|
||||
client *Client
|
||||
sessionID string
|
||||
}
|
||||
|
||||
// NewAgentSession creates a new agent session wrapper
|
||||
func (c *Client) NewAgentSession(sessionID string) *AgentSession {
|
||||
return &AgentSession{
|
||||
client: c,
|
||||
sessionID: sessionID,
|
||||
}
|
||||
}
|
||||
|
||||
// Ask sends a query to the agent with default agent-enabled behavior.
|
||||
func (as *AgentSession) Ask(ctx context.Context, query string, callback AgentEventCallback) error {
|
||||
return as.client.AgentQAStream(ctx, as.sessionID, query, callback)
|
||||
}
|
||||
|
||||
// AskWithRequest sends a customized agent request for this session.
|
||||
func (as *AgentSession) AskWithRequest(
|
||||
ctx context.Context,
|
||||
request *AgentQARequest,
|
||||
callback AgentEventCallback,
|
||||
) error {
|
||||
return as.client.AgentQAStreamWithRequest(ctx, as.sessionID, request, callback)
|
||||
}
|
||||
|
||||
// GetSessionID returns the session ID
|
||||
func (as *AgentSession) GetSessionID() string {
|
||||
return as.sessionID
|
||||
}
|
||||
|
|
@ -14,23 +14,28 @@ import (
|
|||
// Chunk represents the information about a document chunk
|
||||
// Chunks are the basic units of storage and indexing in the knowledge base
|
||||
type Chunk struct {
|
||||
ID string `json:"id"` // Unique identifier of the chunk
|
||||
KnowledgeID string `json:"knowledge_id"` // Identifier of the parent knowledge
|
||||
TenantID uint `json:"tenant_id"` // Tenant ID
|
||||
Content string `json:"content"` // Text content of the chunk
|
||||
Embedding []float32 `json:"embedding"` // Vector embedding representation
|
||||
ChunkIndex int `json:"chunk_index"` // Index position of chunk in the document
|
||||
TotalChunks int `json:"total_chunks"` // Total number of chunks in the document
|
||||
IsEnabled bool `json:"is_enabled"` // Whether this chunk is enabled
|
||||
StartAt int `json:"start_at"` // Starting position in original text
|
||||
EndAt int `json:"end_at"` // Ending position in original text
|
||||
VectorStoreID string `json:"vector_store_id"` // Vector storage ID
|
||||
KeywordStoreID string `json:"keyword_store_id"` // Keyword storage ID
|
||||
EmbeddingStatus int `json:"embedding_status"` // Embedding status: 0-unprocessed, 1-processing, 2-completed
|
||||
ChunkType string `json:"chunk_type"`
|
||||
ImageInfo string `json:"image_info"`
|
||||
CreatedAt string `json:"created_at"` // Creation time
|
||||
UpdatedAt string `json:"updated_at"` // Last update time
|
||||
ID string `json:"id"` // Unique identifier of the chunk
|
||||
KnowledgeID string `json:"knowledge_id"` // Identifier of the parent knowledge
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base
|
||||
TenantID uint64 `json:"tenant_id"` // Tenant ID
|
||||
TagID string `json:"tag_id"` // Optional tag ID for categorization
|
||||
Content string `json:"content"` // Text content of the chunk
|
||||
ChunkIndex int `json:"chunk_index"` // Index position of chunk in the document
|
||||
IsEnabled bool `json:"is_enabled"` // Whether this chunk is enabled
|
||||
Status int `json:"status"` // Status of the chunk
|
||||
StartAt int `json:"start_at"` // Starting position in original text
|
||||
EndAt int `json:"end_at"` // Ending position in original text
|
||||
PreChunkID string `json:"pre_chunk_id"` // Previous chunk ID
|
||||
NextChunkID string `json:"next_chunk_id"` // Next chunk ID
|
||||
ChunkType string `json:"chunk_type"` // Chunk type (text, image_ocr, etc.)
|
||||
ParentChunkID string `json:"parent_chunk_id"` // Parent chunk ID
|
||||
RelationChunks any `json:"relation_chunks"` // Relation chunk IDs
|
||||
IndirectRelationChunks any `json:"indirect_relation_chunks"` // Indirect relation chunk IDs
|
||||
Metadata any `json:"metadata"` // Metadata for the chunk
|
||||
ContentHash string `json:"content_hash"` // Content hash for quick matching
|
||||
ImageInfo string `json:"image_info"` // Image information
|
||||
CreatedAt string `json:"created_at"` // Creation time
|
||||
UpdatedAt string `json:"updated_at"` // Last update time
|
||||
}
|
||||
|
||||
// ChunkResponse represents the response for a single chunk
|
||||
|
|
@ -59,6 +64,7 @@ type UpdateChunkRequest struct {
|
|||
IsEnabled bool `json:"is_enabled"` // Whether enabled
|
||||
StartAt int `json:"start_at"` // Start position
|
||||
EndAt int `json:"end_at"` // End position
|
||||
ImageInfo string `json:"image_info"` // Image information
|
||||
}
|
||||
|
||||
// ListKnowledgeChunks lists all chunks under a knowledge document
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ func ExampleUsage() {
|
|||
"source": "local",
|
||||
"type": "document",
|
||||
}
|
||||
knowledge, err := apiClient.CreateKnowledgeFromFile(context.Background(), createdKB.ID, filePath, metadata, nil)
|
||||
knowledge, err := apiClient.CreateKnowledgeFromFile(context.Background(), createdKB.ID, filePath, metadata, nil, "")
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to upload knowledge file: %v\n", err)
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,265 @@
|
|||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FAQEntry represents a FAQ item stored under a knowledge base.
|
||||
type FAQEntry struct {
|
||||
ID string `json:"id"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
IsEnabled bool `json:"is_enabled"`
|
||||
StandardQuestion string `json:"standard_question"`
|
||||
SimilarQuestions []string `json:"similar_questions"`
|
||||
NegativeQuestions []string `json:"negative_questions"`
|
||||
Answers []string `json:"answers"`
|
||||
IndexMode string `json:"index_mode"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Score float64 `json:"score,omitempty"`
|
||||
MatchType string `json:"match_type,omitempty"`
|
||||
ChunkType string `json:"chunk_type"`
|
||||
}
|
||||
|
||||
// FAQEntryPayload is used to create or update a FAQ entry.
|
||||
type FAQEntryPayload struct {
|
||||
StandardQuestion string `json:"standard_question"`
|
||||
SimilarQuestions []string `json:"similar_questions,omitempty"`
|
||||
NegativeQuestions []string `json:"negative_questions,omitempty"`
|
||||
Answers []string `json:"answers"`
|
||||
TagID string `json:"tag_id,omitempty"`
|
||||
IsEnabled *bool `json:"is_enabled,omitempty"`
|
||||
}
|
||||
|
||||
// FAQBatchUpsertPayload represents the request body for batch import (append/replace).
|
||||
type FAQBatchUpsertPayload struct {
|
||||
Entries []FAQEntryPayload `json:"entries"`
|
||||
Mode string `json:"mode"`
|
||||
KnowledgeID string `json:"knowledge_id,omitempty"`
|
||||
}
|
||||
|
||||
// FAQEntryStatusBatchRequest toggles enable states in bulk.
|
||||
type FAQEntryStatusBatchRequest struct {
|
||||
Updates map[string]bool `json:"updates"`
|
||||
}
|
||||
|
||||
// FAQEntryTagBatchRequest updates tags in bulk.
|
||||
type FAQEntryTagBatchRequest struct {
|
||||
Updates map[string]*string `json:"updates"`
|
||||
}
|
||||
|
||||
// FAQDeleteRequest deletes entries in bulk.
|
||||
type FAQDeleteRequest struct {
|
||||
IDs []string `json:"ids"`
|
||||
}
|
||||
|
||||
// FAQSearchRequest represents the hybrid FAQ search request.
|
||||
type FAQSearchRequest struct {
|
||||
QueryText string `json:"query_text"`
|
||||
VectorThreshold float64 `json:"vector_threshold"`
|
||||
MatchCount int `json:"match_count"`
|
||||
}
|
||||
|
||||
// FAQEntriesPage contains paginated FAQ results.
|
||||
type FAQEntriesPage struct {
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Entries []FAQEntry `json:"data"`
|
||||
}
|
||||
|
||||
// FAQEntriesResponse wraps the paginated FAQ response.
|
||||
type FAQEntriesResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data *FAQEntriesPage `json:"data"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// FAQUpsertResponse wraps the asynchronous import response.
|
||||
type FAQUpsertResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data *FAQTaskPayload `json:"data"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// FAQTaskPayload carries the task identifier for async imports.
|
||||
type FAQTaskPayload struct {
|
||||
TaskID string `json:"task_id"`
|
||||
}
|
||||
|
||||
// FAQSearchResponse wraps the hybrid FAQ search results.
|
||||
type FAQSearchResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []FAQEntry `json:"data"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// FAQEntryResponse wraps the single FAQ entry creation response.
|
||||
type FAQEntryResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data *FAQEntry `json:"data"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
type faqSimpleResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// ListFAQEntries returns paginated FAQ entries under a knowledge base.
|
||||
func (c *Client) ListFAQEntries(ctx context.Context,
|
||||
knowledgeBaseID string, page, pageSize int, tagID string, keyword string,
|
||||
) (*FAQEntriesPage, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries", knowledgeBaseID)
|
||||
query := url.Values{}
|
||||
if page > 0 {
|
||||
query.Add("page", strconv.Itoa(page))
|
||||
}
|
||||
if pageSize > 0 {
|
||||
query.Add("page_size", strconv.Itoa(pageSize))
|
||||
}
|
||||
if tagID != "" {
|
||||
query.Add("tag_id", tagID)
|
||||
}
|
||||
if keyword != "" {
|
||||
query.Add("keyword", keyword)
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response FAQEntriesResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.Data == nil {
|
||||
return &FAQEntriesPage{}, nil
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// UpsertFAQEntries imports or appends FAQ entries asynchronously and returns the task ID.
|
||||
func (c *Client) UpsertFAQEntries(ctx context.Context,
|
||||
knowledgeBaseID string, payload *FAQBatchUpsertPayload,
|
||||
) (string, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, payload, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var response FAQUpsertResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response.Data == nil {
|
||||
return "", fmt.Errorf("missing task information in response")
|
||||
}
|
||||
return response.Data.TaskID, nil
|
||||
}
|
||||
|
||||
// CreateFAQEntry creates a single FAQ entry synchronously.
|
||||
func (c *Client) CreateFAQEntry(ctx context.Context,
|
||||
knowledgeBaseID string, payload *FAQEntryPayload,
|
||||
) (*FAQEntry, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entry", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, payload, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response FAQEntryResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// UpdateFAQEntry updates a single FAQ entry.
|
||||
func (c *Client) UpdateFAQEntry(ctx context.Context,
|
||||
knowledgeBaseID, entryID string, payload *FAQEntryPayload,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%s", knowledgeBaseID, entryID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPut, path, payload, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var response faqSimpleResponse
|
||||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
||||
// UpdateFAQEntryStatusBatch enables/disables FAQ entries in bulk.
|
||||
func (c *Client) UpdateFAQEntryStatusBatch(ctx context.Context,
|
||||
knowledgeBaseID string, updates map[string]bool,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/status", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPut, path, &FAQEntryStatusBatchRequest{Updates: updates}, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var response faqSimpleResponse
|
||||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
||||
// UpdateFAQEntryTagBatch updates FAQ entry tags in bulk.
|
||||
func (c *Client) UpdateFAQEntryTagBatch(ctx context.Context,
|
||||
knowledgeBaseID string, updates map[string]*string,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/tags", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPut, path, &FAQEntryTagBatchRequest{Updates: updates}, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var response faqSimpleResponse
|
||||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
||||
// DeleteFAQEntries deletes FAQ entries in bulk.
|
||||
func (c *Client) DeleteFAQEntries(ctx context.Context,
|
||||
knowledgeBaseID string, ids []string,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodDelete, path, &FAQDeleteRequest{IDs: ids}, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var response faqSimpleResponse
|
||||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
||||
// SearchFAQEntries performs hybrid FAQ search inside a knowledge base.
|
||||
func (c *Client) SearchFAQEntries(ctx context.Context,
|
||||
knowledgeBaseID string, payload *FAQSearchRequest,
|
||||
) ([]FAQEntry, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/search", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, payload, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response FAQSearchResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return response.Data, nil
|
||||
}
|
||||
|
|
@ -22,8 +22,9 @@ import (
|
|||
// Knowledge represents knowledge information
|
||||
type Knowledge struct {
|
||||
ID string `json:"id"`
|
||||
TenantID uint `json:"tenant_id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
|
|
@ -34,7 +35,9 @@ type Knowledge struct {
|
|||
FileName string `json:"file_name"`
|
||||
FileType string `json:"file_type"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
FileHash string `json:"file_hash"`
|
||||
FilePath string `json:"file_path"`
|
||||
StorageSize int64 `json:"storage_size"`
|
||||
Metadata map[string]string `json:"metadata"` // Extensible metadata for storing machine information, paths, etc.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
|
@ -78,8 +81,14 @@ var ErrDuplicateFile = errors.New("file already exists")
|
|||
var ErrDuplicateURL = errors.New("URL already exists")
|
||||
|
||||
// CreateKnowledgeFromFile creates a knowledge entry from a local file path
|
||||
// Parameters:
|
||||
// - knowledgeBaseID: The ID of the knowledge base
|
||||
// - filePath: The local file path
|
||||
// - metadata: Optional metadata for the knowledge entry
|
||||
// - enableMultimodel: Optional flag to enable multimodal processing
|
||||
// - customFileName: Optional custom file name (useful for folder uploads with path)
|
||||
func (c *Client) CreateKnowledgeFromFile(ctx context.Context,
|
||||
knowledgeBaseID string, filePath string, metadata map[string]string, enableMultimodel *bool,
|
||||
knowledgeBaseID string, filePath string, metadata map[string]string, enableMultimodel *bool, customFileName string,
|
||||
) (*Knowledge, error) {
|
||||
// Open the local file
|
||||
file, err := os.Open(filePath)
|
||||
|
|
@ -133,6 +142,13 @@ func (c *Client) CreateKnowledgeFromFile(ctx context.Context,
|
|||
}
|
||||
}
|
||||
|
||||
// Add custom file name if provided
|
||||
if customFileName != "" {
|
||||
if err := writer.WriteField("fileName", customFileName); err != nil {
|
||||
return nil, fmt.Errorf("failed to write fileName field: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Close the multipart writer
|
||||
err = writer.Close()
|
||||
if err != nil {
|
||||
|
|
@ -172,15 +188,23 @@ func (c *Client) CreateKnowledgeFromFile(ctx context.Context,
|
|||
}
|
||||
|
||||
// CreateKnowledgeFromURL creates a knowledge entry from a web URL
|
||||
func (c *Client) CreateKnowledgeFromURL(ctx context.Context, knowledgeBaseID string, url string, enableMultimodel *bool) (*Knowledge, error) {
|
||||
func (c *Client) CreateKnowledgeFromURL(
|
||||
ctx context.Context,
|
||||
knowledgeBaseID string,
|
||||
url string,
|
||||
enableMultimodel *bool,
|
||||
title string,
|
||||
) (*Knowledge, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/knowledge/url", knowledgeBaseID)
|
||||
|
||||
reqBody := struct {
|
||||
URL string `json:"url"`
|
||||
EnableMultimodel *bool `json:"enable_multimodel"`
|
||||
Title string `json:"title"`
|
||||
}{
|
||||
URL: url,
|
||||
EnableMultimodel: enableMultimodel,
|
||||
Title: title,
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, reqBody, nil)
|
||||
|
|
@ -244,12 +268,16 @@ func (c *Client) ListKnowledge(ctx context.Context,
|
|||
knowledgeBaseID string,
|
||||
page int,
|
||||
pageSize int,
|
||||
tagID string,
|
||||
) ([]Knowledge, int64, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/knowledge", knowledgeBaseID)
|
||||
|
||||
queryParams := url.Values{}
|
||||
queryParams.Add("page", strconv.Itoa(page))
|
||||
queryParams.Add("page_size", strconv.Itoa(pageSize))
|
||||
if tagID != "" {
|
||||
queryParams.Add("tag_id", tagID)
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, queryParams)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
|
@ -16,28 +15,45 @@ import (
|
|||
type KnowledgeBase struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"` // Name must be unique within the same tenant
|
||||
Type string `json:"type"`
|
||||
IsTemporary bool `json:"is_temporary"`
|
||||
Description string `json:"description"`
|
||||
TenantID uint `json:"tenant_id"` // Changed to uint type
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
ChunkingConfig ChunkingConfig `json:"chunking_config"`
|
||||
ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"`
|
||||
FAQConfig *FAQConfig `json:"faq_config"`
|
||||
EmbeddingModelID string `json:"embedding_model_id"`
|
||||
SummaryModelID string `json:"summary_model_id"` // Summary model ID
|
||||
SummaryModelID string `json:"summary_model_id"`
|
||||
VLMConfig VLMConfig `json:"vlm_config"`
|
||||
StorageConfig StorageConfig `json:"cos_config"`
|
||||
ExtractConfig *ExtractConfig `json:"extract_config"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Computed fields (not stored in database)
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
ChunkCount int64 `json:"chunk_count"`
|
||||
IsProcessing bool `json:"is_processing"`
|
||||
ProcessingCount int64 `json:"processing_count"`
|
||||
}
|
||||
|
||||
// KnowledgeBaseConfig represents knowledge base configuration
|
||||
type KnowledgeBaseConfig struct {
|
||||
ChunkingConfig ChunkingConfig `json:"chunking_config"`
|
||||
ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"`
|
||||
FAQConfig *FAQConfig `json:"faq_config"`
|
||||
}
|
||||
|
||||
// ChunkingConfig represents document chunking configuration
|
||||
type ChunkingConfig struct {
|
||||
ChunkSize int `json:"chunk_size"` // Chunk size
|
||||
ChunkOverlap int `json:"chunk_overlap"` // Overlap size
|
||||
Separators []string `json:"separators"` // Separators
|
||||
EnableMultimodal bool `json:"enable_multimodal"` // Whether to enable multimodal processing
|
||||
ChunkSize int `json:"chunk_size"` // Chunk size
|
||||
ChunkOverlap int `json:"chunk_overlap"` // Overlap size
|
||||
Separators []string `json:"separators"` // Separators
|
||||
}
|
||||
|
||||
// FAQConfig represents faq-specific configuration
|
||||
type FAQConfig struct {
|
||||
IndexMode string `json:"index_mode"`
|
||||
QuestionIndexMode string `json:"question_index_mode"`
|
||||
}
|
||||
|
||||
// ImageProcessingConfig represents image processing configuration
|
||||
|
|
@ -45,6 +61,44 @@ type ImageProcessingConfig struct {
|
|||
ModelID string `json:"model_id"` // Multimodal model ID
|
||||
}
|
||||
|
||||
// VLMConfig represents the VLM configuration
|
||||
type VLMConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ModelID string `json:"model_id"`
|
||||
}
|
||||
|
||||
// StorageConfig represents the storage configuration
|
||||
type StorageConfig struct {
|
||||
SecretID string `json:"secret_id"`
|
||||
SecretKey string `json:"secret_key"`
|
||||
Region string `json:"region"`
|
||||
BucketName string `json:"bucket_name"`
|
||||
AppID string `json:"app_id"`
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
Provider string `json:"provider"`
|
||||
}
|
||||
|
||||
// ExtractConfig represents the extract configuration for a knowledge base
|
||||
type ExtractConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Nodes []*GraphNode `json:"nodes,omitempty"`
|
||||
Relations []*GraphRelation `json:"relations,omitempty"`
|
||||
}
|
||||
|
||||
// GraphNode represents a node in the graph extraction configuration
|
||||
type GraphNode struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// GraphRelation represents a relation in the graph extraction configuration
|
||||
type GraphRelation struct {
|
||||
Node1 string `json:"node1"`
|
||||
Node2 string `json:"node2"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// KnowledgeBaseResponse knowledge base response
|
||||
type KnowledgeBaseResponse struct {
|
||||
Success bool `json:"success"`
|
||||
|
|
@ -174,14 +228,23 @@ func (c *Client) DeleteKnowledgeBase(ctx context.Context, knowledgeBaseID string
|
|||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
||||
// SearchParams represents the search parameters for hybrid search
|
||||
type SearchParams struct {
|
||||
QueryText string `json:"query_text"`
|
||||
VectorThreshold float64 `json:"vector_threshold"`
|
||||
KeywordThreshold float64 `json:"keyword_threshold"`
|
||||
MatchCount int `json:"match_count"`
|
||||
DisableKeywordsMatch bool `json:"disable_keywords_match"`
|
||||
DisableVectorMatch bool `json:"disable_vector_match"`
|
||||
}
|
||||
|
||||
// HybridSearch performs hybrid search
|
||||
func (c *Client) HybridSearch(ctx context.Context, knowledgeBaseID string, query string) ([]*SearchResult, error) {
|
||||
// Note: The backend route is GET but expects JSON body, which is non-standard.
|
||||
// This client uses POST with JSON body for better compatibility.
|
||||
func (c *Client) HybridSearch(ctx context.Context, knowledgeBaseID string, params *SearchParams) ([]*SearchResult, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/hybrid-search", knowledgeBaseID)
|
||||
|
||||
queryParams := url.Values{}
|
||||
queryParams.Add("query", query)
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, queryParams)
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, params, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,32 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
// ToolResult represents the result of a tool execution
|
||||
type ToolResult struct {
|
||||
Success bool `json:"success"` // Whether the tool executed successfully
|
||||
Output string `json:"output"` // Human-readable output
|
||||
Data map[string]interface{} `json:"data,omitempty"` // Structured data for programmatic use
|
||||
Error string `json:"error,omitempty"` // Error message if execution failed
|
||||
}
|
||||
|
||||
// ToolCall represents a single tool invocation within an agent step
|
||||
type ToolCall struct {
|
||||
ID string `json:"id"` // Function call ID from LLM
|
||||
Name string `json:"name"` // Tool name
|
||||
Args map[string]interface{} `json:"args"` // Tool arguments
|
||||
Result *ToolResult `json:"result"` // Execution result
|
||||
Reflection string `json:"reflection,omitempty"` // Agent's reflection on this tool call result
|
||||
Duration int64 `json:"duration"` // Execution time in milliseconds
|
||||
}
|
||||
|
||||
// AgentStep represents one iteration of the ReAct loop
|
||||
type AgentStep struct {
|
||||
Iteration int `json:"iteration"` // Iteration number (0-indexed)
|
||||
Thought string `json:"thought"` // LLM's reasoning/thinking (Think phase)
|
||||
ToolCalls []ToolCall `json:"tool_calls"` // Tools called in this step (Act phase)
|
||||
Timestamp time.Time `json:"timestamp"` // When this step occurred
|
||||
}
|
||||
|
||||
// Message message information
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
|
|
@ -19,7 +45,8 @@ type Message struct {
|
|||
RequestID string `json:"request_id"`
|
||||
Content string `json:"content"`
|
||||
Role string `json:"role"`
|
||||
KnowledgeReferences []*SearchResult `json:"knowledge_references" `
|
||||
KnowledgeReferences []*SearchResult `json:"knowledge_references"`
|
||||
AgentSteps []AgentStep `json:"agent_steps,omitempty"` // Agent execution steps (only for assistant messages)
|
||||
IsCompleted bool `json:"is_completed"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
|
@ -32,7 +59,12 @@ type MessageListResponse struct {
|
|||
}
|
||||
|
||||
// LoadMessages loads session messages, supports pagination and time filtering
|
||||
func (c *Client) LoadMessages(ctx context.Context, sessionID string, limit int, beforeTime *time.Time) ([]Message, error) {
|
||||
func (c *Client) LoadMessages(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
limit int,
|
||||
beforeTime *time.Time,
|
||||
) ([]Message, error) {
|
||||
path := fmt.Sprintf("/api/v1/messages/%s/load", sessionID)
|
||||
|
||||
queryParams := url.Values{}
|
||||
|
|
@ -61,7 +93,12 @@ func (c *Client) GetRecentMessages(ctx context.Context, sessionID string, limit
|
|||
}
|
||||
|
||||
// GetMessagesBefore gets messages before a specified time
|
||||
func (c *Client) GetMessagesBefore(ctx context.Context, sessionID string, beforeTime time.Time, limit int) ([]Message, error) {
|
||||
func (c *Client) GetMessagesBefore(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
beforeTime time.Time,
|
||||
limit int,
|
||||
) ([]Message, error) {
|
||||
return c.LoadMessages(ctx, sessionID, limit, &beforeTime)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -49,32 +49,52 @@ type SummaryConfig struct {
|
|||
MaxCompletionTokens int `json:"max_completion_tokens"`
|
||||
}
|
||||
|
||||
// SessionAgentConfig defines session-level agent configuration (matches server struct).
|
||||
// Sessions only store Enabled and KnowledgeBases; other configs are read from Tenant at runtime
|
||||
type SessionAgentConfig struct {
|
||||
AgentModeEnabled bool `json:"agent_mode_enabled"` // Whether agent mode is enabled for this session
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this session
|
||||
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs for this session
|
||||
}
|
||||
|
||||
// CreateSessionRequest session creation request
|
||||
type CreateSessionRequest struct {
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"` // Associated knowledge base ID
|
||||
SessionStrategy *SessionStrategy `json:"session_strategy"` // Session strategy
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"` // Associated knowledge base ID (optional in agent mode)
|
||||
SessionStrategy *SessionStrategy `json:"session_strategy"` // Session strategy
|
||||
AgentConfig *SessionAgentConfig `json:"agent_config"` // Agent configuration (optional, for agent mode)
|
||||
}
|
||||
|
||||
// ContextConfig configures LLM context management
|
||||
type ContextConfig struct {
|
||||
MaxTokens int `json:"max_tokens"` // Maximum tokens allowed in LLM context
|
||||
CompressionStrategy string `json:"compression_strategy"` // Compression strategy: "sliding_window" or "smart"
|
||||
RecentMessageCount int `json:"recent_message_count"` // Number of recent messages to keep
|
||||
SummarizeThreshold int `json:"summarize_threshold"` // Number of messages before summarization
|
||||
}
|
||||
|
||||
// Session session information
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
TenantID uint `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Title string `json:"title"`
|
||||
MaxRounds int `json:"max_rounds"`
|
||||
EnableRewrite bool `json:"enable_rewrite"`
|
||||
FallbackStrategy string `json:"fallback_strategy"`
|
||||
FallbackResponse string `json:"fallback_response"`
|
||||
EmbeddingTopK int `json:"embedding_top_k"`
|
||||
KeywordThreshold float64 `json:"keyword_threshold"`
|
||||
VectorThreshold float64 `json:"vector_threshold"`
|
||||
RerankModelID string `json:"rerank_model_id"`
|
||||
RerankTopK int `json:"rerank_top_k"`
|
||||
RerankThreshold float64 `json:"reranking_threshold"` // Reranking threshold
|
||||
SummaryModelID string `json:"summary_model_id"`
|
||||
SummaryParameters *SummaryConfig `json:"summary_parameters"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
MaxRounds int `json:"max_rounds"`
|
||||
EnableRewrite bool `json:"enable_rewrite"`
|
||||
FallbackStrategy string `json:"fallback_strategy"`
|
||||
FallbackResponse string `json:"fallback_response"`
|
||||
EmbeddingTopK int `json:"embedding_top_k"`
|
||||
KeywordThreshold float64 `json:"keyword_threshold"`
|
||||
VectorThreshold float64 `json:"vector_threshold"`
|
||||
RerankModelID string `json:"rerank_model_id"`
|
||||
RerankTopK int `json:"rerank_top_k"`
|
||||
RerankThreshold float64 `json:"rerank_threshold"` // Reranking threshold
|
||||
SummaryModelID string `json:"summary_model_id"`
|
||||
SummaryParameters *SummaryConfig `json:"summary_parameters"`
|
||||
AgentConfig *SessionAgentConfig `json:"agent_config"` // Agent configuration (optional)
|
||||
ContextConfig *ContextConfig `json:"context_config"` // Context management configuration (optional)
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// SessionResponse session response
|
||||
|
|
@ -184,6 +204,11 @@ type GenerateTitleResponse struct {
|
|||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
// StopSessionRequest stop generation payload.
|
||||
type StopSessionRequest struct {
|
||||
MessageID string `json:"message_id"`
|
||||
}
|
||||
|
||||
// GenerateTitle generates a session title
|
||||
func (c *Client) GenerateTitle(ctx context.Context, sessionID string, request *GenerateTitleRequest) (string, error) {
|
||||
path := fmt.Sprintf("/api/v1/sessions/%s/generate_title", sessionID)
|
||||
|
|
@ -222,7 +247,12 @@ type StreamResponse struct {
|
|||
}
|
||||
|
||||
// KnowledgeQAStream knowledge Q&A streaming API
|
||||
func (c *Client) KnowledgeQAStream(ctx context.Context, sessionID string, query string, callback func(*StreamResponse) error) error {
|
||||
func (c *Client) KnowledgeQAStream(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
query string,
|
||||
callback func(*StreamResponse) error,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-chat/%s", sessionID)
|
||||
fmt.Printf("Starting KnowledgeQAStream request, session ID: %s, query: %s\n", sessionID, query)
|
||||
|
||||
|
|
@ -301,7 +331,12 @@ func (c *Client) KnowledgeQAStream(ctx context.Context, sessionID string, query
|
|||
}
|
||||
|
||||
// ContinueStream continues to receive an active stream for a session
|
||||
func (c *Client) ContinueStream(ctx context.Context, sessionID string, messageID string, callback func(*StreamResponse) error) error {
|
||||
func (c *Client) ContinueStream(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
messageID string,
|
||||
callback func(*StreamResponse) error,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/sessions/continue-stream/%s", sessionID)
|
||||
|
||||
queryParams := url.Values{}
|
||||
|
|
@ -361,6 +396,31 @@ func (c *Client) ContinueStream(ctx context.Context, sessionID string, messageID
|
|||
return nil
|
||||
}
|
||||
|
||||
// StopSession stops the generation for a specific assistant message under a session.
|
||||
func (c *Client) StopSession(ctx context.Context, sessionID string, messageID string) error {
|
||||
if strings.TrimSpace(sessionID) == "" {
|
||||
return fmt.Errorf("sessionID cannot be empty")
|
||||
}
|
||||
if strings.TrimSpace(messageID) == "" {
|
||||
return fmt.Errorf("messageID cannot be empty")
|
||||
}
|
||||
|
||||
path := fmt.Sprintf("/api/v1/sessions/%s/stop", sessionID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, &StopSessionRequest{
|
||||
MessageID: messageID,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
||||
// SearchKnowledgeRequest knowledge search request
|
||||
type SearchKnowledgeRequest struct {
|
||||
Query string `json:"query"` // Query content
|
||||
|
|
|
|||
|
|
@ -0,0 +1,157 @@
|
|||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Tag represents a knowledge base tag.
|
||||
type Tag struct {
|
||||
ID string `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Name string `json:"name"`
|
||||
Color string `json:"color"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TagWithStats represents tag information along with usage statistics.
|
||||
type TagWithStats struct {
|
||||
Tag
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
ChunkCount int64 `json:"chunk_count"`
|
||||
}
|
||||
|
||||
// CreateTagPayload is used to create a new tag.
|
||||
type CreateTagPayload struct {
|
||||
Name string `json:"name"`
|
||||
Color string `json:"color,omitempty"`
|
||||
SortOrder int `json:"sort_order,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateTagPayload is used to update an existing tag.
|
||||
type UpdateTagPayload struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Color *string `json:"color,omitempty"`
|
||||
SortOrder *int `json:"sort_order,omitempty"`
|
||||
}
|
||||
|
||||
// TagsPage contains paginated tag results.
|
||||
type TagsPage struct {
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Tags []TagWithStats `json:"data"`
|
||||
}
|
||||
|
||||
// TagsResponse wraps the paginated tags response.
|
||||
type TagsResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data *TagsPage `json:"data"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// TagResponse wraps a single tag response.
|
||||
type TagResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data *Tag `json:"data"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
type tagSimpleResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// ListTags returns paginated tags under a knowledge base.
|
||||
func (c *Client) ListTags(ctx context.Context,
|
||||
knowledgeBaseID string, page, pageSize int, keyword string,
|
||||
) (*TagsPage, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/tags", knowledgeBaseID)
|
||||
query := url.Values{}
|
||||
if page > 0 {
|
||||
query.Add("page", strconv.Itoa(page))
|
||||
}
|
||||
if pageSize > 0 {
|
||||
query.Add("page_size", strconv.Itoa(pageSize))
|
||||
}
|
||||
if keyword != "" {
|
||||
query.Add("keyword", keyword)
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response TagsResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.Data == nil {
|
||||
return &TagsPage{}, nil
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// CreateTag creates a new tag under a knowledge base.
|
||||
func (c *Client) CreateTag(ctx context.Context,
|
||||
knowledgeBaseID string, payload *CreateTagPayload,
|
||||
) (*Tag, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/tags", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, payload, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response TagResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// UpdateTag updates an existing tag.
|
||||
func (c *Client) UpdateTag(ctx context.Context,
|
||||
knowledgeBaseID, tagID string, payload *UpdateTagPayload,
|
||||
) (*Tag, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/tags/%s", knowledgeBaseID, tagID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPut, path, payload, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response TagResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
// DeleteTag deletes a tag. Set force to true to delete even if the tag is referenced.
|
||||
func (c *Client) DeleteTag(ctx context.Context,
|
||||
knowledgeBaseID, tagID string, force bool,
|
||||
) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/tags/%s", knowledgeBaseID, tagID)
|
||||
query := url.Values{}
|
||||
if force {
|
||||
query.Add("force", "true")
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodDelete, path, nil, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var response tagSimpleResponse
|
||||
return parseResponse(resp, &response)
|
||||
}
|
||||
|
|
@ -24,23 +24,27 @@ type RetrieverEngineParams struct {
|
|||
|
||||
// Tenant represents tenant information in the system
|
||||
type Tenant struct {
|
||||
ID uint `yaml:"id" json:"id" gorm:"primaryKey"`
|
||||
ID uint64 `yaml:"id" json:"id" gorm:"primaryKey"`
|
||||
// Tenant name
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
// Tenant description
|
||||
Description string `yaml:"description" json:"description"`
|
||||
Description string `yaml:"description" json:"description"`
|
||||
// API key for authentication
|
||||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
// Tenant status (active, inactive)
|
||||
Status string `yaml:"status" json:"status" gorm:"default:'active'"`
|
||||
Status string `yaml:"status" json:"status" gorm:"default:'active'"`
|
||||
// Configured retrieval engines
|
||||
RetrieverEngines RetrieverEngines `yaml:"retriever_engines" json:"retriever_engines" gorm:"type:json"`
|
||||
// Business/department information
|
||||
Business string `yaml:"business" json:"business"`
|
||||
Business string `yaml:"business" json:"business"`
|
||||
// Storage quota (Bytes), default is 10GB
|
||||
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
|
||||
// Storage used (Bytes)
|
||||
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
|
||||
// Creation timestamp
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
// Last update timestamp
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TenantResponse represents the API response structure for tenant operations
|
||||
|
|
@ -73,7 +77,7 @@ func (c *Client) CreateTenant(ctx context.Context, tenant *Tenant) (*Tenant, err
|
|||
}
|
||||
|
||||
// GetTenant retrieves a tenant by ID
|
||||
func (c *Client) GetTenant(ctx context.Context, tenantID uint) (*Tenant, error) {
|
||||
func (c *Client) GetTenant(ctx context.Context, tenantID uint64) (*Tenant, error) {
|
||||
path := fmt.Sprintf("/api/v1/tenants/%d", tenantID)
|
||||
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
|
||||
if err != nil {
|
||||
|
|
@ -105,7 +109,7 @@ func (c *Client) UpdateTenant(ctx context.Context, tenant *Tenant) (*Tenant, err
|
|||
}
|
||||
|
||||
// DeleteTenant removes a tenant by ID
|
||||
func (c *Client) DeleteTenant(ctx context.Context, tenantID uint) error {
|
||||
func (c *Client) DeleteTenant(ctx context.Context, tenantID uint64) error {
|
||||
path := fmt.Sprintf("/api/v1/tenants/%d", tenantID)
|
||||
resp, err := c.doRequest(ctx, http.MethodDelete, path, nil, nil)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ conversation:
|
|||
## 用户当前的问题是:
|
||||
{{.Query}}
|
||||
enable_rewrite: true
|
||||
enable_query_expansion: true
|
||||
enable_rerank: true
|
||||
rewrite_prompt_system: |
|
||||
你是一个专注于指代消解和省略补全的智能助手,你的任务是根据历史对话上下文,清晰识别用户问题中的代词并替换为明确的主语,同时补全省略的关键信息。
|
||||
|
|
@ -205,26 +206,16 @@ conversation:
|
|||
</think>
|
||||
NO_MATCH
|
||||
prompt: |
|
||||
这是用户和助手之间的对话。当用户提出问题时,助手会基于特定的信息进行解答。助手首先在心中思考推理过程,然后向用户提供答案。
|
||||
推理过程用 <think> </think> 标签包围,答案直接输出在think标签后面,即:
|
||||
<think>
|
||||
这里是推理过程
|
||||
</think>
|
||||
这里是答案
|
||||
你是一个专业的智能信息检索助手,名为WeKnora。你犹如专业的高级秘书,依据检索到的信息回答用户问题,不能利用任何先验知识。
|
||||
当用户提出问题时,助手会基于特定的信息进行解答。助手首先在心中思考推理过程,然后向用户提供答案。
|
||||
context_template: |
|
||||
你是一个专业的智能信息检索助手,名为小微,犹如专业的高级秘书,依据检索到的信息回答用户问题。
|
||||
当用户提出问题时,助手只能基于给定的信息进行解答,不能利用任何先验知识。
|
||||
|
||||
## 回答问题规则
|
||||
- 仅根据检索到的信息中的事实进行回复,不得运用任何先验知识,保持回应的客观性和准确性。
|
||||
- 复杂问题和答案的按Markdown分结构展示,总述部分不需要拆分
|
||||
- 如果是比较简单的答案,不需要把最终答案拆分的过于细碎
|
||||
- 结果中使用的图片地址必须来自于检索到的信息,不得虚构
|
||||
- 检查结果中的文字和图片是否来自于检索到的信息,如果扩展了不在检索到的信息中的内容,必须进行修改,直到得到最终答案
|
||||
- 如果用户问题无法回答,只输出NO_MATCH即可,即:
|
||||
<think>
|
||||
</think>
|
||||
NO_MATCH
|
||||
- 如果用户问题无法回答,必须如实告知用户,并给出合理的建议。
|
||||
|
||||
## 输出限制
|
||||
- 以Markdown图文格式输出你的最终结果
|
||||
|
|
@ -527,6 +518,34 @@ conversation:
|
|||
}
|
||||
]
|
||||
|
||||
generate_questions_prompt: |
|
||||
你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
|
||||
|
||||
{{.Context}}
|
||||
## 主要内容(请基于此内容生成问题)
|
||||
文档名称:{{.DocName}}
|
||||
文档内容:
|
||||
{{.Content}}
|
||||
|
||||
## 核心要求
|
||||
- 生成的问题必须与【主要内容】直接相关
|
||||
- 问题中禁止使用任何代词或指代词(如"它"、"这个"、"该文档"、"本文"、"文中"、"其"等),必须用具体名称替代
|
||||
- 问题必须是完整独立的,脱离上下文也能被理解
|
||||
- 问题应该是用户在实际场景中可能会提出的自然问题
|
||||
- 问题应该多样化,覆盖内容的不同方面
|
||||
- 每个问题应该简洁明了,长度控制在30字以内
|
||||
- 生成的问题数量为 {{.QuestionCount}} 个
|
||||
|
||||
## 问题类型建议
|
||||
- 定义类:什么是...?...是什么?
|
||||
- 原因类:为什么...?...的原因是什么?
|
||||
- 方法类:如何...?怎样...?
|
||||
- 比较类:...和...有什么区别?
|
||||
- 应用类:...可以用于什么场景?
|
||||
|
||||
## 输出格式
|
||||
直接输出问题列表,每行一个问题,不要有序号或其他前缀。
|
||||
|
||||
# 知识库配置
|
||||
knowledge_base:
|
||||
chunk_size: 512
|
||||
|
|
@ -599,4 +618,31 @@ extract:
|
|||
with_tag: |
|
||||
请随机生成一段文本,要求内容与 %s 等相关,字数在 [50-200] 之间,并且尽量包含一些与这些标签相关的专业术语或典型元素,使文本更具针对性和相关性。
|
||||
with_no_tag: |
|
||||
请随机生成一段文本,内容请自由发挥,字数在 [50-200] 之间。
|
||||
请随机生成一段文本,内容请自由发挥,字数在 [50-200] 之间。
|
||||
|
||||
# WebSearch 配置
|
||||
web_search:
|
||||
# 可用搜索引擎列表
|
||||
providers:
|
||||
- id: "duckduckgo"
|
||||
name: "DuckDuckGo"
|
||||
free: true
|
||||
requires_api_key: false
|
||||
description: "DuckDuckGo API"
|
||||
|
||||
|
||||
# 默认配置
|
||||
default:
|
||||
provider: "duckduckgo"
|
||||
max_results: 5
|
||||
include_date: true
|
||||
compression_method: "none"
|
||||
blacklist: []
|
||||
|
||||
# 全局超时设置
|
||||
timeout: 10
|
||||
|
||||
# 租户配置
|
||||
tenant:
|
||||
# 是否启用跨租户访问功能(内网环境可开启)
|
||||
enable_cross_tenant_access: false
|
||||
|
|
|
|||
|
|
@ -0,0 +1,146 @@
|
|||
# 开发环境配置 - 只启动基础设施服务,app 和 frontend 在本地运行
|
||||
services:
|
||||
# 只启动依赖的基础设施服务
|
||||
postgres:
|
||||
image: paradedb/paradedb:v0.18.9-pg17
|
||||
container_name: WeKnora-postgres-dev
|
||||
ports:
|
||||
- "${DB_PORT:-5432}:5432"
|
||||
environment:
|
||||
- POSTGRES_USER=${DB_USER}
|
||||
- POSTGRES_PASSWORD=${DB_PASSWORD}
|
||||
- POSTGRES_DB=${DB_NAME}
|
||||
volumes:
|
||||
- postgres-data-dev:/var/lib/postgresql/data
|
||||
- ./migrations/paradedb/00-init-db.sql:/docker-entrypoint-initdb.d/00-init-db.sql
|
||||
- ./migrations/paradedb/01-migrate-to-paradedb.sql:/docker-entrypoint-initdb.d/01-migrate-to-paradedb.sql
|
||||
networks:
|
||||
- WeKnora-network-dev
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
|
||||
interval: 10s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 1m
|
||||
|
||||
redis:
|
||||
image: redis:7.0-alpine
|
||||
container_name: WeKnora-redis-dev
|
||||
ports:
|
||||
- "${REDIS_PORT:-6379}:6379"
|
||||
volumes:
|
||||
- redis_data_dev:/data
|
||||
command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD}
|
||||
restart: always
|
||||
networks:
|
||||
- WeKnora-network-dev
|
||||
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
container_name: WeKnora-minio-dev
|
||||
ports:
|
||||
- "${MINIO_PORT:-9000}:9000"
|
||||
- "${MINIO_CONSOLE_PORT:-9001}:9001"
|
||||
environment:
|
||||
- MINIO_ROOT_USER=${MINIO_ACCESS_KEY_ID:-minioadmin}
|
||||
- MINIO_ROOT_PASSWORD=${MINIO_SECRET_ACCESS_KEY:-minioadmin}
|
||||
command: server --console-address ":9001" /data
|
||||
volumes:
|
||||
- minio_data_dev:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||
interval: 30s
|
||||
timeout: 20s
|
||||
retries: 3
|
||||
networks:
|
||||
- WeKnora-network-dev
|
||||
|
||||
neo4j:
|
||||
image: neo4j:latest
|
||||
container_name: WeKnora-neo4j-dev
|
||||
volumes:
|
||||
- neo4j-data-dev:/data
|
||||
environment:
|
||||
- NEO4J_AUTH=${NEO4J_USERNAME:-neo4j}/${NEO4J_PASSWORD:-password}
|
||||
- NEO4J_apoc_export_file_enabled=true
|
||||
- NEO4J_apoc_import_file_enabled=true
|
||||
- NEO4J_apoc_import_file_use__neo4j__config=true
|
||||
- NEO4JLABS_PLUGINS=["apoc"]
|
||||
ports:
|
||||
- "7474:7474"
|
||||
- "7687:7687"
|
||||
restart: always
|
||||
networks:
|
||||
- WeKnora-network-dev
|
||||
|
||||
docreader:
|
||||
image: wechatopenai/weknora-docreader:main
|
||||
container_name: WeKnora-docreader-dev
|
||||
ports:
|
||||
- "${DOCREADER_PORT:-50051}:50051"
|
||||
environment:
|
||||
- COS_SECRET_ID=${COS_SECRET_ID:-}
|
||||
- COS_SECRET_KEY=${COS_SECRET_KEY:-}
|
||||
- COS_REGION=${COS_REGION:-}
|
||||
- COS_BUCKET_NAME=${COS_BUCKET_NAME:-}
|
||||
- COS_APP_ID=${COS_APP_ID:-}
|
||||
- COS_PATH_PREFIX=${COS_PATH_PREFIX:-}
|
||||
- COS_ENABLE_OLD_DOMAIN=${COS_ENABLE_OLD_DOMAIN:-}
|
||||
- VLM_MODEL_BASE_URL=${VLM_MODEL_BASE_URL:-}
|
||||
- VLM_MODEL_NAME=${VLM_MODEL_NAME:-}
|
||||
- VLM_MODEL_API_KEY=${VLM_MODEL_API_KEY:-}
|
||||
- STORAGE_TYPE=${STORAGE_TYPE:-}
|
||||
- MINIO_PUBLIC_ENDPOINT=http://localhost:${MINIO_PORT:-9000}
|
||||
- MINIO_ENDPOINT=minio:9000
|
||||
- MINIO_ACCESS_KEY_ID=${MINIO_ACCESS_KEY_ID:-minioadmin}
|
||||
- MINIO_SECRET_ACCESS_KEY=${MINIO_SECRET_ACCESS_KEY:-minioadmin}
|
||||
- MINIO_BUCKET_NAME=${MINIO_BUCKET_NAME:-}
|
||||
- MINIO_USE_SSL=${MINIO_USE_SSL:-}
|
||||
- WEB_PROXY=${WEB_PROXY:-}
|
||||
healthcheck:
|
||||
test: ["CMD", "grpc_health_probe", "-addr=:50051"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
networks:
|
||||
- WeKnora-network-dev
|
||||
restart: unless-stopped
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
jaeger:
|
||||
image: jaegertracing/all-in-one:latest
|
||||
container_name: WeKnora-jaeger-dev
|
||||
ports:
|
||||
- "6831:6831/udp"
|
||||
- "6832:6832/udp"
|
||||
- "5778:5778"
|
||||
- "16686:16686"
|
||||
- "4317:4317"
|
||||
- "4318:4318"
|
||||
- "14250:14250"
|
||||
- "14268:14268"
|
||||
- "9411:9411"
|
||||
environment:
|
||||
- COLLECTOR_OTLP_ENABLED=true
|
||||
- COLLECTOR_ZIPKIN_HOST_PORT=:9411
|
||||
volumes:
|
||||
- jaeger_data_dev:/var/lib/jaeger
|
||||
networks:
|
||||
- WeKnora-network-dev
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
WeKnora-network-dev:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres-data-dev:
|
||||
redis_data_dev:
|
||||
minio_data_dev:
|
||||
neo4j-data-dev:
|
||||
jaeger_data_dev:
|
||||
|
||||
|
|
@ -76,6 +76,7 @@ services:
|
|||
- NEO4J_PASSWORD=${NEO4J_PASSWORD:-password}
|
||||
- TENANT_AES_KEY=${TENANT_AES_KEY:-}
|
||||
- CONCURRENCY_POOL_SIZE=${CONCURRENCY_POOL_SIZE:-5}
|
||||
- JWT_SECRET=${JWT_SECRET:-}
|
||||
- INIT_LLM_MODEL_NAME=${INIT_LLM_MODEL_NAME:-}
|
||||
- INIT_LLM_MODEL_BASE_URL=${INIT_LLM_MODEL_BASE_URL:-}
|
||||
- INIT_LLM_MODEL_API_KEY=${INIT_LLM_MODEL_API_KEY:-}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ WORKDIR /app
|
|||
ARG GOPRIVATE_ARG
|
||||
ARG GOPROXY_ARG
|
||||
ARG GOSUMDB_ARG=off
|
||||
ARG APK_MIRROR_ARG="mirrors.tencent.com"
|
||||
|
||||
# 设置Go环境变量
|
||||
ENV GOPRIVATE=${GOPRIVATE_ARG}
|
||||
|
|
@ -14,7 +15,9 @@ ENV GOPROXY=${GOPROXY_ARG}
|
|||
ENV GOSUMDB=${GOSUMDB_ARG}
|
||||
|
||||
# Install dependencies
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories && \
|
||||
RUN if [ -n "$APK_MIRROR_ARG" ]; then \
|
||||
sed -i "s@dl-cdn.alpinelinux.org@${APK_MIRROR_ARG}@g" /etc/apk/repositories; \
|
||||
fi && \
|
||||
apk add --no-cache git build-base
|
||||
|
||||
# Install migrate tool
|
||||
|
|
@ -46,14 +49,22 @@ FROM alpine:3.17
|
|||
|
||||
WORKDIR /app
|
||||
|
||||
# Install runtime dependencies
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories && \
|
||||
ARG APK_MIRROR_ARG="mirrors.tencent.com"
|
||||
|
||||
RUN if [ -n "$APK_MIRROR_ARG" ]; then \
|
||||
sed -i "s@dl-cdn.alpinelinux.org@${APK_MIRROR_ARG}@g" /etc/apk/repositories; \
|
||||
fi && \
|
||||
apk update && apk upgrade && \
|
||||
apk add --no-cache build-base postgresql-client mysql-client ca-certificates tzdata sed curl bash vim wget
|
||||
apk add --no-cache build-base postgresql-client mysql-client ca-certificates tzdata sed curl bash vim wget \
|
||||
nodejs npm python3 py3-pip python3-dev libffi-dev openssl-dev cargo && \
|
||||
python3 -m pip install --upgrade pip setuptools wheel && \
|
||||
# 使用官方安装脚本安装 uvx
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
||||
ln -sf /root/.cargo/bin/uvx /usr/local/bin/uvx
|
||||
|
||||
# Create a non-root user and switch to it
|
||||
RUN mkdir -p /data/files && \
|
||||
adduser -D -g '' appuser && \
|
||||
id -u appuser >/dev/null 2>&1 || adduser -D -g '' appuser && \
|
||||
chown -R appuser:appuser /app /data/files
|
||||
|
||||
# Copy migrate tool from builder stage
|
||||
|
|
|
|||
|
|
@ -1,32 +0,0 @@
|
|||
version: "3.8"
|
||||
|
||||
services:
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
container_name: WeKnora-minio
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
volumes:
|
||||
- minio-data:/data
|
||||
environment:
|
||||
- MINIO_ROOT_USER=${MINIO_ACCESS_KEY_ID}
|
||||
- MINIO_ROOT_PASSWORD=${MINIO_SECRET_ACCESS_KEY}
|
||||
command: server --console-address ":9001" /data
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||
interval: 30s
|
||||
timeout: 20s
|
||||
retries: 3
|
||||
networks:
|
||||
- WeKnora-network
|
||||
|
||||
volumes:
|
||||
minio-data:
|
||||
|
||||
networks:
|
||||
WeKnora-network:
|
||||
external: true
|
||||
|
|
@ -15,7 +15,14 @@ from docreader.models.read_config import ChunkingConfig
|
|||
from docreader.parser import Parser
|
||||
from docreader.parser.ocr_engine import OCREngine
|
||||
from docreader.proto import docreader_pb2_grpc
|
||||
from docreader.proto.docreader_pb2 import Chunk, Image, ReadResponse
|
||||
from docreader.proto.docreader_pb2 import (
|
||||
Chunk,
|
||||
Image,
|
||||
ReadConfig,
|
||||
ReadFromFileRequest,
|
||||
ReadFromURLRequest,
|
||||
ReadResponse,
|
||||
)
|
||||
from docreader.utils.request import init_logging_request_id, request_id_context
|
||||
|
||||
# Surrogate range U+D800..U+DFFF are invalid Unicode scalar values
|
||||
|
|
@ -57,12 +64,75 @@ MAX_MESSAGE_LENGTH = 50 * 1024 * 1024
|
|||
parser = Parser()
|
||||
|
||||
|
||||
def create_chunking_config(read_config: ReadConfig):
|
||||
"""Create ChunkingConfig from ReadConfig request.
|
||||
|
||||
Args:
|
||||
read_config: The read_config from the gRPC request
|
||||
|
||||
Returns:
|
||||
ChunkingConfig: Configured chunking configuration object
|
||||
"""
|
||||
# Extract chunking parameters
|
||||
chunk_size = read_config.chunk_size or 512
|
||||
chunk_overlap = read_config.chunk_overlap or 50
|
||||
# Convert protobuf RepeatedScalarFieldContainer to list for type compatibility
|
||||
separators = (
|
||||
list(read_config.separators) if read_config.separators else ["\n\n", "\n", "。"]
|
||||
)
|
||||
enable_multimodal = read_config.enable_multimodal or False
|
||||
|
||||
logger.info(
|
||||
f"Using chunking config: size={chunk_size}, "
|
||||
f"overlap={chunk_overlap}, multimodal={enable_multimodal}"
|
||||
)
|
||||
|
||||
# Extract storage config
|
||||
sc = read_config.storage_config
|
||||
storage_config = {
|
||||
"provider": "minio" if sc.provider == 2 else "cos",
|
||||
"region": sc.region,
|
||||
"bucket_name": sc.bucket_name,
|
||||
"access_key_id": sc.access_key_id,
|
||||
"secret_access_key": sc.secret_access_key,
|
||||
"app_id": sc.app_id,
|
||||
"path_prefix": sc.path_prefix,
|
||||
}
|
||||
logger.info(
|
||||
f"Using Storage config: provider={storage_config.get('provider')}, "
|
||||
f"bucket={storage_config['bucket_name']}"
|
||||
)
|
||||
|
||||
# Extract VLM config
|
||||
vlm_config = {
|
||||
"model_name": read_config.vlm_config.model_name,
|
||||
"base_url": read_config.vlm_config.base_url,
|
||||
"api_key": read_config.vlm_config.api_key or "",
|
||||
"interface_type": read_config.vlm_config.interface_type or "openai",
|
||||
}
|
||||
logger.info(
|
||||
f"Using VLM config: model={vlm_config['model_name']}, "
|
||||
f"base_url={vlm_config['base_url']}, "
|
||||
f"interface_type={vlm_config['interface_type']}"
|
||||
)
|
||||
|
||||
# Create and return ChunkingConfig
|
||||
return ChunkingConfig(
|
||||
chunk_size=chunk_size,
|
||||
chunk_overlap=chunk_overlap,
|
||||
separators=separators,
|
||||
enable_multimodal=enable_multimodal,
|
||||
storage_config=storage_config,
|
||||
vlm_config=vlm_config,
|
||||
)
|
||||
|
||||
|
||||
class DocReaderServicer(docreader_pb2_grpc.DocReaderServicer):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.parser = Parser()
|
||||
|
||||
def ReadFromFile(self, request, context):
|
||||
def ReadFromFile(self, request: ReadFromFileRequest, context):
|
||||
# Get or generate request ID
|
||||
request_id = (
|
||||
request.request_id
|
||||
|
|
@ -83,57 +153,7 @@ class DocReaderServicer(docreader_pb2_grpc.DocReaderServicer):
|
|||
logger.info(f"File content size: {len(request.file_content)} bytes")
|
||||
|
||||
# Create chunking config
|
||||
chunk_size = request.read_config.chunk_size or 512
|
||||
chunk_overlap = request.read_config.chunk_overlap or 50
|
||||
separators = request.read_config.separators or ["\n\n", "\n", "。"]
|
||||
enable_multimodal = request.read_config.enable_multimodal or False
|
||||
|
||||
logger.info(
|
||||
f"Using chunking config: size={chunk_size}, "
|
||||
f"overlap={chunk_overlap}, multimodal={enable_multimodal}"
|
||||
)
|
||||
|
||||
# Get Storage and VLM config from request
|
||||
storage_config = None
|
||||
vlm_config = None
|
||||
|
||||
sc = request.read_config.storage_config
|
||||
# Keep parser-side key name as cos_config for backward compatibility
|
||||
storage_config = {
|
||||
"provider": "minio" if sc.provider == 2 else "cos",
|
||||
"region": sc.region,
|
||||
"bucket_name": sc.bucket_name,
|
||||
"access_key_id": sc.access_key_id,
|
||||
"secret_access_key": sc.secret_access_key,
|
||||
"app_id": sc.app_id,
|
||||
"path_prefix": sc.path_prefix,
|
||||
}
|
||||
logger.info(
|
||||
f"Using Storage config: provider={storage_config.get('provider')}, "
|
||||
f"bucket={storage_config['bucket_name']}"
|
||||
)
|
||||
|
||||
vlm_config = {
|
||||
"model_name": request.read_config.vlm_config.model_name,
|
||||
"base_url": request.read_config.vlm_config.base_url,
|
||||
"api_key": request.read_config.vlm_config.api_key or "",
|
||||
"interface_type": request.read_config.vlm_config.interface_type
|
||||
or "openai",
|
||||
}
|
||||
logger.info(
|
||||
f"Using VLM config: model={vlm_config['model_name']}, "
|
||||
f"base_url={vlm_config['base_url']}, "
|
||||
f"interface_type={vlm_config['interface_type']}"
|
||||
)
|
||||
|
||||
chunking_config = ChunkingConfig(
|
||||
chunk_size=chunk_size,
|
||||
chunk_overlap=chunk_overlap,
|
||||
separators=separators,
|
||||
enable_multimodal=enable_multimodal,
|
||||
storage_config=storage_config,
|
||||
vlm_config=vlm_config,
|
||||
)
|
||||
chunking_config = create_chunking_config(request.read_config)
|
||||
|
||||
# Parse file
|
||||
logger.info("Starting file parsing process")
|
||||
|
|
@ -170,7 +190,7 @@ class DocReaderServicer(docreader_pb2_grpc.DocReaderServicer):
|
|||
context.set_details(str(e))
|
||||
return ReadResponse(error=str(e))
|
||||
|
||||
def ReadFromURL(self, request, context):
|
||||
def ReadFromURL(self, request: ReadFromURLRequest, context):
|
||||
# Get or generate request ID
|
||||
request_id = (
|
||||
request.request_id
|
||||
|
|
@ -184,56 +204,7 @@ class DocReaderServicer(docreader_pb2_grpc.DocReaderServicer):
|
|||
logger.info(f"Received ReadFromURL request for URL: {request.url}")
|
||||
|
||||
# Create chunking config
|
||||
chunk_size = request.read_config.chunk_size or 512
|
||||
chunk_overlap = request.read_config.chunk_overlap or 50
|
||||
separators = request.read_config.separators or ["\n\n", "\n", "。"]
|
||||
enable_multimodal = request.read_config.enable_multimodal or False
|
||||
|
||||
logger.info(
|
||||
f"Using chunking config: size={chunk_size}, "
|
||||
f"overlap={chunk_overlap}, multimodal={enable_multimodal}"
|
||||
)
|
||||
|
||||
# Get Storage and VLM config from request
|
||||
storage_config = None
|
||||
vlm_config = None
|
||||
|
||||
sc = request.read_config.storage_config
|
||||
storage_config = {
|
||||
"provider": "minio" if sc.provider == 2 else "cos",
|
||||
"region": sc.region,
|
||||
"bucket_name": sc.bucket_name,
|
||||
"access_key_id": sc.access_key_id,
|
||||
"secret_access_key": sc.secret_access_key,
|
||||
"app_id": sc.app_id,
|
||||
"path_prefix": sc.path_prefix,
|
||||
}
|
||||
logger.info(
|
||||
f"Using Storage config: provider={storage_config.get('provider')}, "
|
||||
f"bucket={storage_config['bucket_name']}"
|
||||
)
|
||||
|
||||
vlm_config = {
|
||||
"model_name": request.read_config.vlm_config.model_name,
|
||||
"base_url": request.read_config.vlm_config.base_url,
|
||||
"api_key": request.read_config.vlm_config.api_key or "",
|
||||
"interface_type": request.read_config.vlm_config.interface_type
|
||||
or "openai",
|
||||
}
|
||||
logger.info(
|
||||
f"Using VLM config: model={vlm_config['model_name']}, "
|
||||
f"base_url={vlm_config['base_url']}, "
|
||||
f"interface_type={vlm_config['interface_type']}"
|
||||
)
|
||||
|
||||
chunking_config = ChunkingConfig(
|
||||
chunk_size=chunk_size,
|
||||
chunk_overlap=chunk_overlap,
|
||||
separators=separators,
|
||||
enable_multimodal=enable_multimodal,
|
||||
storage_config=storage_config,
|
||||
vlm_config=vlm_config,
|
||||
)
|
||||
chunking_config = create_chunking_config(request.read_config)
|
||||
|
||||
# Parse URL
|
||||
logger.info("Starting URL parsing process")
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class ChunkingConfig:
|
|||
chunk_overlap: int = 50
|
||||
|
||||
# Text separators in order of priority
|
||||
separators: list = field(default_factory=lambda: ["\n\n", "\n", "。"])
|
||||
separators: list[str] = field(default_factory=lambda: ["\n\n", "\n", "。"])
|
||||
|
||||
# Whether to enable multimodal processing (text + images)
|
||||
enable_multimodal: bool = False
|
||||
|
|
|
|||
|
|
@ -181,17 +181,22 @@ class Caption:
|
|||
from parameters or environment variables.
|
||||
"""
|
||||
logger.info("Initializing Caption service")
|
||||
# Default prompt for image captioning in Chinese: "Briefly describe the main content of the image"
|
||||
self.prompt = """简单凝炼的描述图片的主要内容"""
|
||||
# API request timeout in seconds
|
||||
self.timeout = 30
|
||||
|
||||
# Use provided VLM config if available,
|
||||
# otherwise fall back to environment variables
|
||||
if vlm_config and vlm_config.get("base_url") and vlm_config.get("model_name"):
|
||||
# Build completion URL from provided base URL
|
||||
self.completion_url = vlm_config.get("base_url", "") + "/chat/completions"
|
||||
self.model = vlm_config.get("model_name", "")
|
||||
self.api_key = vlm_config.get("api_key", "")
|
||||
# Interface type: "ollama" or "openai" (default)
|
||||
self.interface_type = vlm_config.get("interface_type", "openai").lower()
|
||||
else:
|
||||
# Fall back to environment variables if config not provided
|
||||
base_url = os.getenv("VLM_MODEL_BASE_URL")
|
||||
model_name = os.getenv("VLM_MODEL_NAME")
|
||||
if not base_url or not model_name:
|
||||
|
|
@ -202,7 +207,7 @@ class Caption:
|
|||
self.api_key = os.getenv("VLM_MODEL_API_KEY", "")
|
||||
self.interface_type = os.getenv("VLM_INTERFACE_TYPE", "openai").lower()
|
||||
|
||||
# 验证接口类型
|
||||
# Validate interface type - must be either "ollama" or "openai"
|
||||
if self.interface_type not in ["ollama", "openai"]:
|
||||
logger.warning(
|
||||
f"Unknown interface type: {self.interface_type}, defaulting to openai"
|
||||
|
|
@ -227,7 +232,7 @@ class Caption:
|
|||
logger.info("Calling Caption API for image captioning")
|
||||
logger.info(f"Processing image data: {image_data[:50]}...")
|
||||
|
||||
# 根据接口类型选择调用方式
|
||||
# Route to appropriate API based on interface type
|
||||
if self.interface_type == "ollama":
|
||||
return self._call_ollama_api(image_data)
|
||||
else:
|
||||
|
|
@ -236,8 +241,10 @@ class Caption:
|
|||
def _call_ollama_api(self, image_base64: str) -> Optional[CaptionChatResp]:
|
||||
"""Call Ollama API for image captioning using base64 encoded image data."""
|
||||
|
||||
# Extract host URL by removing the chat completions endpoint
|
||||
host = self.completion_url.replace("/v1/chat/completions", "")
|
||||
|
||||
# Initialize Ollama client with host and timeout
|
||||
client = ollama.Client(
|
||||
host=host,
|
||||
timeout=self.timeout,
|
||||
|
|
@ -246,16 +253,17 @@ class Caption:
|
|||
try:
|
||||
logger.info(f"Calling Ollama API with model: {self.model}")
|
||||
|
||||
# 调用Ollama API,使用images参数传递base64编码的图片
|
||||
# Call Ollama API with base64 encoded image
|
||||
# Prompt: "Briefly describe the main content of the image"
|
||||
response = client.generate(
|
||||
model=self.model,
|
||||
prompt="简单凝炼的描述图片的主要内容",
|
||||
images=[image_base64], # image_base64是base64编码的图片数据
|
||||
options={"temperature": 0.1},
|
||||
images=[image_base64], # Pass base64 encoded image data
|
||||
options={"temperature": 0.1}, # Low temperature for more deterministic output
|
||||
stream=False,
|
||||
)
|
||||
|
||||
# 构造响应对象
|
||||
# Construct response object in standard format
|
||||
caption_resp = CaptionChatResp(
|
||||
id="ollama_response",
|
||||
created=int(time.time()),
|
||||
|
|
@ -277,6 +285,7 @@ class Caption:
|
|||
"""Call OpenAI-compatible API for image captioning."""
|
||||
logger.info(f"Calling OpenAI-compatible API with model: {self.model}")
|
||||
|
||||
# Construct user message with text prompt and base64 encoded image
|
||||
user_msg = UserMessage(
|
||||
role="user",
|
||||
content=[
|
||||
|
|
@ -290,20 +299,23 @@ class Caption:
|
|||
],
|
||||
)
|
||||
|
||||
# Build completion request with model parameters
|
||||
gpt_req = CompletionRequest(
|
||||
model=self.model,
|
||||
temperature=0.3,
|
||||
top_p=0.8,
|
||||
temperature=0.3, # Moderate randomness for balanced output
|
||||
top_p=0.8, # Nucleus sampling parameter
|
||||
messages=[user_msg],
|
||||
user="abc",
|
||||
)
|
||||
|
||||
# Set up HTTP headers for the API request
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
}
|
||||
# Add authorization header if API key is provided
|
||||
if self.api_key:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
|
||||
|
|
@ -311,12 +323,14 @@ class Caption:
|
|||
logger.info(
|
||||
f"Sending request to OpenAI-compatible API with model: {self.model}"
|
||||
)
|
||||
# Send POST request to the API endpoint
|
||||
response = requests.post(
|
||||
self.completion_url,
|
||||
data=json.dumps(gpt_req, default=lambda o: o.__dict__, indent=4),
|
||||
headers=headers,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
# Check for successful response
|
||||
if response.status_code != 200:
|
||||
logger.error(
|
||||
f"OpenAI API returned non-200 status code: {response.status_code}"
|
||||
|
|
@ -325,6 +339,7 @@ class Caption:
|
|||
|
||||
logger.info(f"Received from OpenAI with status: {response.status_code}")
|
||||
logger.info("Converting response to CaptionChatResp object")
|
||||
# Parse JSON response into structured object
|
||||
caption_resp = CaptionChatResp.from_json(response.json())
|
||||
|
||||
if caption_resp.usage:
|
||||
|
|
|
|||
|
|
@ -1,3 +1,11 @@
|
|||
"""
|
||||
Chain Parser Module
|
||||
|
||||
This module provides two chain-of-responsibility pattern implementations for document parsing:
|
||||
1. FirstParser: Tries multiple parsers sequentially until one succeeds
|
||||
2. PipelineParser: Chains parsers where each parser processes the output of the previous one
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Dict, List, Tuple, Type
|
||||
|
||||
|
|
@ -10,17 +18,43 @@ logger.setLevel(logging.INFO)
|
|||
|
||||
|
||||
class FirstParser(BaseParser):
|
||||
"""
|
||||
First-success parser that tries multiple parsers in sequence.
|
||||
|
||||
This parser attempts to parse content using each registered parser in order.
|
||||
It returns the result from the first parser that successfully produces a valid document.
|
||||
If all parsers fail, it returns an empty Document.
|
||||
|
||||
Usage:
|
||||
# Create a custom FirstParser with specific parser classes
|
||||
CustomParser = FirstParser.create(MarkdownParser, HTMLParser)
|
||||
parser = CustomParser()
|
||||
document = parser.parse_into_text(content_bytes)
|
||||
"""
|
||||
|
||||
# Tuple of parser classes to be instantiated
|
||||
_parser_cls: Tuple[Type["BaseParser"], ...] = ()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize FirstParser with configured parser classes."""
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Instantiate all parser classes into parser instances
|
||||
self._parsers: List[BaseParser] = []
|
||||
for parser_cls in self._parser_cls:
|
||||
parser = parser_cls(*args, **kwargs)
|
||||
self._parsers.append(parser)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse content using the first parser that succeeds.
|
||||
|
||||
Args:
|
||||
content: Raw bytes content to be parsed
|
||||
|
||||
Returns:
|
||||
Document: Parsed document from the first successful parser,
|
||||
or an empty Document if all parsers fail
|
||||
"""
|
||||
for p in self._parsers:
|
||||
logger.info(f"FirstParser: using parser {p.__class__.__name__}")
|
||||
document = p.parse_into_text(content)
|
||||
|
|
@ -31,41 +65,104 @@ class FirstParser(BaseParser):
|
|||
|
||||
@classmethod
|
||||
def create(cls, *parser_classes: Type["BaseParser"]) -> Type["FirstParser"]:
|
||||
"""Factory method to create a FirstParser subclass with specific parsers.
|
||||
|
||||
Args:
|
||||
*parser_classes: Variable number of BaseParser subclasses to try in order
|
||||
|
||||
Returns:
|
||||
Type[FirstParser]: A new FirstParser subclass configured with the given parsers
|
||||
|
||||
Example:
|
||||
CustomParser = FirstParser.create(MarkdownParser, HTMLParser)
|
||||
parser = CustomParser()
|
||||
"""
|
||||
# Generate a descriptive class name based on parser names
|
||||
names = "_".join([p.__name__ for p in parser_classes])
|
||||
# Dynamically create a new class with the parser configuration
|
||||
return type(f"FirstParser_{names}", (cls,), {"_parser_cls": parser_classes})
|
||||
|
||||
|
||||
class PipelineParser(BaseParser):
|
||||
"""
|
||||
Pipeline parser that chains multiple parsers sequentially.
|
||||
|
||||
This parser processes content through a series of parsers where each parser
|
||||
receives the output of the previous parser as input. Images from all parsers
|
||||
are accumulated and merged into the final document.
|
||||
|
||||
Usage:
|
||||
# Create a custom PipelineParser with specific parser classes
|
||||
CustomParser = PipelineParser.create(PreParser, MarkdownParser, PostParser)
|
||||
parser = CustomParser()
|
||||
document = parser.parse_into_text(content_bytes)
|
||||
"""
|
||||
|
||||
# Tuple of parser classes to be instantiated and chained
|
||||
_parser_cls: Tuple[Type["BaseParser"], ...] = ()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize PipelineParser with configured parser classes."""
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Instantiate all parser classes into parser instances
|
||||
self._parsers: List[BaseParser] = []
|
||||
for parser_cls in self._parser_cls:
|
||||
parser = parser_cls(*args, **kwargs)
|
||||
self._parsers.append(parser)
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse content through a pipeline of parsers.
|
||||
|
||||
Each parser in the pipeline processes the output of the previous parser.
|
||||
Images from all parsers are accumulated and merged into the final document.
|
||||
|
||||
Args:
|
||||
content: Raw bytes content to be parsed
|
||||
|
||||
Returns:
|
||||
Document: Final document after processing through all parsers,
|
||||
with accumulated images from all stages
|
||||
"""
|
||||
# Accumulate images from all parsers
|
||||
images: Dict[str, str] = {}
|
||||
document = Document()
|
||||
for p in self._parsers:
|
||||
logger.info(f"PipelineParser: using parser {p.__class__.__name__}")
|
||||
# Parse content with current parser
|
||||
document = p.parse_into_text(content)
|
||||
# Convert document content back to bytes for next parser
|
||||
content = endecode.encode_bytes(document.content)
|
||||
# Accumulate images from this parser
|
||||
images.update(document.images)
|
||||
# Merge all accumulated images into final document
|
||||
document.images.update(images)
|
||||
return document
|
||||
|
||||
@classmethod
|
||||
def create(cls, *parser_classes: Type["BaseParser"]) -> Type["PipelineParser"]:
|
||||
"""Factory method to create a PipelineParser subclass with specific parsers.
|
||||
|
||||
Args:
|
||||
*parser_classes: Variable number of BaseParser subclasses to chain in order
|
||||
|
||||
Returns:
|
||||
Type[PipelineParser]: A new PipelineParser subclass configured with the given parsers
|
||||
|
||||
Example:
|
||||
CustomParser = PipelineParser.create(PreprocessParser, MarkdownParser)
|
||||
parser = CustomParser()
|
||||
"""
|
||||
# Generate a descriptive class name based on parser names
|
||||
names = "_".join([p.__name__ for p in parser_classes])
|
||||
# Dynamically create a new class with the parser configuration
|
||||
return type(f"PipelineParser_{names}", (cls,), {"_parser_cls": parser_classes})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from docreader.parser.markdown_parser import MarkdownParser
|
||||
|
||||
cls = FirstParser.create(MarkdownParser)
|
||||
parser = cls()
|
||||
print(parser.parse_into_text(b"aaa"))
|
||||
# Example: Create and use a FirstParser with MarkdownParser
|
||||
FpCls = FirstParser.create(MarkdownParser)
|
||||
lparser = FpCls()
|
||||
print(lparser.parse_into_text(b"aaa"))
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
"""
|
||||
CSV Parser Module
|
||||
|
||||
This module provides a parser for CSV (Comma-Separated Values) files.
|
||||
It converts CSV data into a Document with structured chunks, where each row
|
||||
becomes a separate chunk with key-value pairs.
|
||||
"""
|
||||
import logging
|
||||
from io import BytesIO
|
||||
from typing import List
|
||||
|
|
@ -11,23 +18,64 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class CSVParser(BaseParser):
|
||||
"""
|
||||
Parser for CSV files that converts tabular data into structured text.
|
||||
|
||||
This parser reads CSV content and transforms each row into a formatted string
|
||||
with column-value pairs. Each row is stored as a separate Chunk in the Document,
|
||||
allowing for granular access to individual records.
|
||||
|
||||
The output format for each row is:
|
||||
"column1: value1, column2: value2, column3: value3\n"
|
||||
|
||||
Usage:
|
||||
parser = CSVParser()
|
||||
with open("data.csv", "rb") as f:
|
||||
document = parser.parse_into_text(f.read())
|
||||
"""
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse CSV content into a Document with structured chunks.
|
||||
|
||||
Each row in the CSV is converted into a formatted string and stored as
|
||||
a separate Chunk. The chunks maintain sequential order and track their
|
||||
position in the overall document.
|
||||
|
||||
Args:
|
||||
content: Raw bytes content of the CSV file
|
||||
|
||||
Returns:
|
||||
Document: A Document object containing:
|
||||
- content: Full text with all rows concatenated
|
||||
- chunks: List of Chunk objects, one per CSV row
|
||||
|
||||
Note:
|
||||
Bad lines in the CSV are automatically skipped using pandas'
|
||||
on_bad_lines="skip" parameter.
|
||||
"""
|
||||
chunks: List[Chunk] = []
|
||||
text: List[str] = []
|
||||
start, end = 0, 0
|
||||
|
||||
# Read CSV content into a pandas DataFrame, skipping malformed lines
|
||||
df = pd.read_csv(BytesIO(content), on_bad_lines="skip")
|
||||
|
||||
# Process each row in the DataFrame
|
||||
for i, (idx, row) in enumerate(df.iterrows()):
|
||||
# Format row as "column: value" pairs separated by commas
|
||||
content_row = (
|
||||
",".join(
|
||||
f"{col.strip()}: {str(row[col]).strip()}" for col in df.columns
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
# Update end position for this chunk
|
||||
end += len(content_row)
|
||||
text.append(content_row)
|
||||
|
||||
# Create a chunk for this row with position tracking
|
||||
chunks.append(Chunk(content=content_row, seq=i, start=start, end=end))
|
||||
# Update start position for next chunk
|
||||
start = end
|
||||
|
||||
return Document(
|
||||
|
|
@ -37,6 +85,7 @@ class CSVParser(BaseParser):
|
|||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage: Parse a CSV file and display its content
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
your_file = "/path/to/your/file.csv"
|
||||
|
|
@ -44,7 +93,9 @@ if __name__ == "__main__":
|
|||
with open(your_file, "rb") as f:
|
||||
content = f.read()
|
||||
document = parser.parse_into_text(content)
|
||||
# Display full document content
|
||||
logger.error(document.content)
|
||||
|
||||
# Display individual chunks (rows)
|
||||
for chunk in document.chunks:
|
||||
logger.error(chunk.content)
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
"""
|
||||
Excel Parser Module
|
||||
|
||||
This module provides functionality to parse Excel files (.xlsx, .xls) into
|
||||
structured Document objects with text content and chunks. It supports multiple
|
||||
sheets and handles various Excel formats using pandas.
|
||||
"""
|
||||
import logging
|
||||
from io import BytesIO
|
||||
from typing import List
|
||||
|
|
@ -11,44 +18,102 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class ExcelParser(BaseParser):
|
||||
"""Parser for Excel files (.xlsx, .xls).
|
||||
|
||||
This parser extracts text content from Excel files by processing all sheets
|
||||
and converting each row into a structured text format. Each row becomes a
|
||||
separate chunk with key-value pairs.
|
||||
|
||||
Features:
|
||||
- Supports multiple sheets in a single Excel file
|
||||
- Automatically removes completely empty rows
|
||||
- Converts each row to "column: value" format
|
||||
- Creates individual chunks for each row for better granularity
|
||||
|
||||
Example:
|
||||
>>> parser = ExcelParser()
|
||||
>>> with open("data.xlsx", "rb") as f:
|
||||
... content = f.read()
|
||||
... document = parser.parse_into_text(content)
|
||||
>>> print(document.content)
|
||||
Name: John,Age: 30,City: NYC
|
||||
Name: Jane,Age: 25,City: LA
|
||||
"""
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse Excel file bytes into a Document object.
|
||||
|
||||
Args:
|
||||
content: Raw bytes of the Excel file
|
||||
|
||||
Returns:
|
||||
Document: Parsed document containing:
|
||||
- content: Full text with all rows from all sheets
|
||||
- chunks: List of Chunk objects, one per row
|
||||
|
||||
Note:
|
||||
- Empty rows (all NaN values) are automatically skipped
|
||||
- Each row is formatted as: "col1: val1,col2: val2,..."
|
||||
- Chunks maintain sequential ordering across all sheets
|
||||
"""
|
||||
chunks: List[Chunk] = []
|
||||
text: List[str] = []
|
||||
start, end = 0, 0
|
||||
|
||||
# Load Excel file from bytes into pandas ExcelFile object
|
||||
excel_file = pd.ExcelFile(BytesIO(content))
|
||||
|
||||
# Process each sheet in the Excel file
|
||||
for excel_sheet_name in excel_file.sheet_names:
|
||||
# Parse the sheet into a DataFrame
|
||||
df = excel_file.parse(sheet_name=excel_sheet_name)
|
||||
# Remove rows where all values are NaN (completely empty rows)
|
||||
df.dropna(how="all", inplace=True)
|
||||
|
||||
# Process each row in the DataFrame
|
||||
for _, row in df.iterrows():
|
||||
page_content = []
|
||||
# Build key-value pairs for non-null values
|
||||
for k, v in row.items():
|
||||
if pd.notna(v):
|
||||
if pd.notna(v): # Skip NaN/null values
|
||||
page_content.append(f"{k}: {v}")
|
||||
|
||||
# Skip rows with no valid content
|
||||
if not page_content:
|
||||
continue
|
||||
|
||||
# Format row as comma-separated key-value pairs
|
||||
content_row = ",".join(page_content) + "\n"
|
||||
end += len(content_row)
|
||||
text.append(content_row)
|
||||
|
||||
# Create a chunk for this row with position tracking
|
||||
chunks.append(
|
||||
Chunk(content=content_row, seq=len(chunks), start=start, end=end)
|
||||
)
|
||||
start = end
|
||||
|
||||
# Combine all text and return as Document
|
||||
return Document(content="".join(text), chunks=chunks)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage: Parse an Excel file and display results
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Specify the path to your Excel file
|
||||
your_file = "/path/to/your/file.xlsx"
|
||||
parser = ExcelParser()
|
||||
|
||||
# Read and parse the Excel file
|
||||
with open(your_file, "rb") as f:
|
||||
content = f.read()
|
||||
document = parser.parse_into_text(content)
|
||||
|
||||
# Display the full document content
|
||||
logger.error(document.content)
|
||||
|
||||
# Display the first chunk as an example
|
||||
for chunk in document.chunks:
|
||||
logger.error(chunk.content)
|
||||
break
|
||||
break # Only show the first chunk
|
||||
|
|
|
|||
|
|
@ -1,3 +1,15 @@
|
|||
"""
|
||||
Markdown Parser Module
|
||||
|
||||
This module provides comprehensive Markdown parsing functionality including:
|
||||
- Table formatting and standardization
|
||||
- Base64 image extraction and conversion
|
||||
- Image path replacement and URL generation
|
||||
- Pipeline-based parsing with multiple stages
|
||||
|
||||
The parser uses a pipeline approach to process Markdown content through
|
||||
multiple stages: table formatting -> image processing.
|
||||
"""
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
|
|
@ -15,37 +27,76 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class MarkdownTableUtil:
|
||||
"""Utility class for formatting Markdown tables.
|
||||
|
||||
This class standardizes Markdown table formatting by:
|
||||
- Normalizing column alignment markers (e.g., :---, :---:, ---:)
|
||||
- Adding consistent spacing around pipes (|)
|
||||
- Preserving indentation levels
|
||||
- Handling both header rows and data rows
|
||||
|
||||
Example:
|
||||
Input: |姓名|年龄|城市|
|
||||
|:---|---:|:---:|
|
||||
|张三|25|北京|
|
||||
|
||||
Output: | 姓名 | 年龄 | 城市 |
|
||||
| :--- | ---: | :---: |
|
||||
| 张三 | 25 | 北京 |
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Pattern to match alignment row (e.g., |:---|---:|:---:|)
|
||||
self.align_pattern = re.compile(
|
||||
r"^([\t ]*)\|[\t ]*[:-]+(?:[\t ]*\|[\t ]*[:-]+)*[\t ]*\|[\t ]*$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
# Pattern to match regular table rows (header or data)
|
||||
self.line_pattern = re.compile(
|
||||
r"^([\t ]*)\|[\t ]*[^|\r\n]*(?:[\t ]*\|[^|\r\n]*)*\|[\t ]*$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
def format_table(self, content: str) -> str:
|
||||
"""Format all Markdown tables in the content.
|
||||
|
||||
Args:
|
||||
content: Raw Markdown text containing tables
|
||||
|
||||
Returns:
|
||||
Formatted Markdown text with standardized table formatting
|
||||
"""
|
||||
|
||||
def process_align(match: Match[str]) -> str:
|
||||
"""Process alignment row to standardize format."""
|
||||
# Split by | and remove empty strings
|
||||
columns = [col.strip() for col in match.group(0).split("|") if col.strip()]
|
||||
|
||||
processed = []
|
||||
for col in columns:
|
||||
# Preserve left alignment marker (:---)
|
||||
left_colon = ":" if col.startswith(":") else ""
|
||||
# Preserve right alignment marker (---:)
|
||||
right_colon = ":" if col.endswith(":") else ""
|
||||
processed.append(left_colon + "---" + right_colon)
|
||||
|
||||
# Preserve original indentation
|
||||
prefix = match.group(1)
|
||||
return prefix + "| " + " | ".join(processed) + " |"
|
||||
|
||||
def process_line(match: Match[str]) -> str:
|
||||
"""Process regular table row to standardize format."""
|
||||
# Split by | and remove empty strings
|
||||
columns = [col.strip() for col in match.group(0).split("|") if col.strip()]
|
||||
|
||||
# Preserve original indentation
|
||||
prefix = match.group(1)
|
||||
return prefix + "| " + " | ".join(columns) + " |"
|
||||
|
||||
formatted_content = content
|
||||
# First format regular rows (header and data)
|
||||
formatted_content = self.line_pattern.sub(process_line, formatted_content)
|
||||
# Then format alignment rows (must be done after to avoid conflicts)
|
||||
formatted_content = self.align_pattern.sub(process_align, formatted_content)
|
||||
|
||||
return formatted_content
|
||||
|
|
@ -73,22 +124,64 @@ class MarkdownTableUtil:
|
|||
|
||||
|
||||
class MarkdownTableFormatter(BaseParser):
|
||||
"""Parser for formatting Markdown tables.
|
||||
|
||||
This parser standardizes the formatting of all Markdown tables in the
|
||||
document to ensure consistent spacing and alignment markers.
|
||||
|
||||
Example:
|
||||
>>> formatter = MarkdownTableFormatter()
|
||||
>>> content = b"|Name|Age|\n|---|---|\n|John|30|"
|
||||
>>> doc = formatter.parse_into_text(content)
|
||||
>>> print(doc.content)
|
||||
| Name | Age |
|
||||
| --- | --- |
|
||||
| John | 30 |
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.table_helper = MarkdownTableUtil()
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse and format Markdown tables.
|
||||
|
||||
Args:
|
||||
content: Raw Markdown content as bytes
|
||||
|
||||
Returns:
|
||||
Document with formatted table content
|
||||
"""
|
||||
# Decode bytes to string with automatic encoding detection
|
||||
text = endecode.decode_bytes(content)
|
||||
# Format all tables in the content
|
||||
text = self.table_helper.format_table(text)
|
||||
return Document(content=text)
|
||||
|
||||
|
||||
class MarkdownImageUtil:
|
||||
"""Utility class for handling images in Markdown.
|
||||
|
||||
This class provides functionality to:
|
||||
- Extract base64-encoded images from Markdown
|
||||
- Extract image paths from Markdown
|
||||
- Replace image paths with new URLs
|
||||
- Convert base64 images to binary format
|
||||
|
||||
Supported formats:
|
||||
- Base64 embedded images: 
|
||||
- Regular image links: 
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Pattern to match base64 embedded images
|
||||
# Captures: (1) alt text, (2) image format, (3) base64 data
|
||||
self.b64_pattern = re.compile(
|
||||
r"!\[([^\]]*)\]\(data:image/(\w+)\+?\w*;base64,([^\)]+)\)"
|
||||
)
|
||||
# Pattern to match regular image syntax
|
||||
self.image_pattern = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
|
||||
# Pattern for replacing image paths
|
||||
self.replace_pattern = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
|
||||
|
||||
def extract_image(
|
||||
|
|
@ -97,23 +190,41 @@ class MarkdownImageUtil:
|
|||
path_prefix: Optional[str] = None,
|
||||
replace: bool = True,
|
||||
) -> Tuple[str, List[str]]:
|
||||
"""Extract base64 encoded images from Markdown content"""
|
||||
|
||||
# image_path => base64 bytes
|
||||
"""Extract image paths from Markdown content.
|
||||
|
||||
Args:
|
||||
content: Markdown text containing images
|
||||
path_prefix: Optional prefix to add to image paths
|
||||
replace: Whether to replace image syntax in content
|
||||
|
||||
Returns:
|
||||
Tuple of (processed_text, list_of_image_paths)
|
||||
|
||||
Example:
|
||||
>>> util = MarkdownImageUtil()
|
||||
>>> text, images = util.extract_image("")
|
||||
>>> print(images)
|
||||
['img/logo.png']
|
||||
"""
|
||||
# List to store extracted image paths
|
||||
images: List[str] = []
|
||||
|
||||
def repl(match: Match[str]) -> str:
|
||||
title = match.group(1)
|
||||
image_path = match.group(2)
|
||||
"""Replacement function for each image match."""
|
||||
title = match.group(1) # Alt text
|
||||
image_path = match.group(2) # Image path
|
||||
|
||||
# Add prefix if specified
|
||||
if path_prefix:
|
||||
image_path = f"{path_prefix}/{image_path}"
|
||||
|
||||
images.append(image_path)
|
||||
|
||||
# Keep original if replace is False
|
||||
if not replace:
|
||||
return match.group(0)
|
||||
|
||||
# Replace image path with URL
|
||||
# Replace image path with potentially prefixed path
|
||||
return f""
|
||||
|
||||
text = self.image_pattern.sub(repl, content)
|
||||
|
|
@ -126,30 +237,55 @@ class MarkdownImageUtil:
|
|||
path_prefix: Optional[str] = None,
|
||||
replace: bool = True,
|
||||
) -> Tuple[str, Dict[str, bytes]]:
|
||||
"""Extract base64 encoded images from Markdown content"""
|
||||
|
||||
# image_path => base64 bytes
|
||||
"""Extract and decode base64 embedded images from Markdown.
|
||||
|
||||
This method finds all base64-encoded images in the Markdown content,
|
||||
decodes them to binary format, generates unique filenames, and
|
||||
optionally replaces them with file path references.
|
||||
|
||||
Args:
|
||||
content: Markdown text containing base64 images
|
||||
path_prefix: Optional directory prefix for generated paths
|
||||
replace: Whether to replace base64 syntax with file paths
|
||||
|
||||
Returns:
|
||||
Tuple of (processed_text, dict_of_path_to_bytes)
|
||||
|
||||
Example:
|
||||
>>> util = MarkdownImageUtil()
|
||||
>>> text = ""
|
||||
>>> new_text, images = util.extract_base64(text, "images")
|
||||
>>> print(new_text)
|
||||

|
||||
>>> print(len(images))
|
||||
1
|
||||
"""
|
||||
# Dictionary mapping generated file paths to binary image data
|
||||
images: Dict[str, bytes] = {}
|
||||
|
||||
def repl(match: Match[str]) -> str:
|
||||
title = match.group(1)
|
||||
img_ext = match.group(2)
|
||||
img_b64 = match.group(3)
|
||||
"""Replacement function for each base64 image match."""
|
||||
title = match.group(1) # Alt text
|
||||
img_ext = match.group(2) # Image format (png, jpg, etc.)
|
||||
img_b64 = match.group(3) # Base64 encoded data
|
||||
|
||||
# Decode base64 string to bytes
|
||||
image_byte = endecode.encode_image(img_b64, errors="ignore")
|
||||
if not image_byte:
|
||||
logger.error(f"Failed to decode base64 image skip it: {img_b64}")
|
||||
return title
|
||||
return title # Return just the alt text if decode fails
|
||||
|
||||
# Generate unique filename with original extension
|
||||
image_path = f"{uuid.uuid4()}.{img_ext}"
|
||||
if path_prefix:
|
||||
image_path = f"{path_prefix}/{image_path}"
|
||||
images[image_path] = image_byte
|
||||
|
||||
# Keep original base64 if replace is False
|
||||
if not replace:
|
||||
return match.group(0)
|
||||
|
||||
# Replace image path with URL
|
||||
# Replace base64 data with file path reference
|
||||
return f""
|
||||
|
||||
text = self.b64_pattern.sub(repl, content)
|
||||
|
|
@ -157,15 +293,40 @@ class MarkdownImageUtil:
|
|||
return text, images
|
||||
|
||||
def replace_path(self, content: str, images: Dict[str, str]) -> str:
|
||||
"""Replace image paths in Markdown with new URLs.
|
||||
|
||||
This method is typically used to replace local file paths with
|
||||
uploaded URLs after images have been stored.
|
||||
|
||||
Args:
|
||||
content: Markdown text with image references
|
||||
images: Mapping of old paths to new URLs
|
||||
|
||||
Returns:
|
||||
Markdown text with updated image URLs
|
||||
|
||||
Example:
|
||||
>>> util = MarkdownImageUtil()
|
||||
>>> content = ""
|
||||
>>> mapping = {"temp/img.png": "https://cdn.com/img.png"}
|
||||
>>> result = util.replace_path(content, mapping)
|
||||
>>> print(result)
|
||||

|
||||
"""
|
||||
# Track which paths were actually replaced
|
||||
content_replace: set = set()
|
||||
|
||||
def repl(match: Match[str]) -> str:
|
||||
title = match.group(1)
|
||||
image_path = match.group(2)
|
||||
"""Replacement function for each image match."""
|
||||
title = match.group(1) # Alt text
|
||||
image_path = match.group(2) # Current image path
|
||||
|
||||
# Only replace if path exists in mapping
|
||||
if image_path not in images:
|
||||
return match.group(0)
|
||||
return match.group(0) # Keep original
|
||||
|
||||
content_replace.add(image_path)
|
||||
# Get new URL from mapping
|
||||
image_path = images[image_path]
|
||||
return f""
|
||||
|
||||
|
|
@ -186,43 +347,94 @@ class MarkdownImageUtil:
|
|||
|
||||
|
||||
class MarkdownImageBase64(BaseParser):
|
||||
"""Parser for extracting and uploading base64 images from Markdown.
|
||||
|
||||
This parser:
|
||||
1. Extracts base64-encoded images from Markdown content
|
||||
2. Uploads the decoded images to storage
|
||||
3. Replaces base64 data with uploaded URLs
|
||||
4. Returns a Document with clean Markdown and image mappings
|
||||
|
||||
Requires:
|
||||
- self.storage: Storage backend for uploading images
|
||||
|
||||
Example:
|
||||
>>> parser = MarkdownImageBase64(storage=my_storage)
|
||||
>>> content = b""
|
||||
>>> doc = parser.parse_into_text(content)
|
||||
>>> print(doc.content)
|
||||

|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.image_helper = MarkdownImageUtil()
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse Markdown and process base64 images.
|
||||
|
||||
Args:
|
||||
content: Raw Markdown content as bytes
|
||||
|
||||
Returns:
|
||||
Document with:
|
||||
- content: Markdown with base64 replaced by URLs
|
||||
- images: Dict mapping URLs to base64 strings
|
||||
"""
|
||||
# Convert byte content to string using universal decoding method
|
||||
text = endecode.decode_bytes(content)
|
||||
# Extract base64 images and replace with temporary paths
|
||||
text, img_b64 = self.image_helper.extract_base64(text, path_prefix="images")
|
||||
|
||||
# Final image mapping: URL -> base64 string (for Document)
|
||||
images: Dict[str, str] = {}
|
||||
# Temporary mapping: temp_path -> uploaded_URL (for replacement)
|
||||
image_replace: Dict[str, str] = {}
|
||||
|
||||
logger.debug(f"Uploading {len(img_b64)} images from markdown")
|
||||
# Upload each extracted image to storage
|
||||
for ipath, b64_bytes in img_b64.items():
|
||||
# Get file extension for proper MIME type
|
||||
ext = os.path.splitext(ipath)[1].lower()
|
||||
# Upload binary data and get back URL
|
||||
image_url = self.storage.upload_bytes(b64_bytes, ext)
|
||||
|
||||
# Map temp path to uploaded URL for replacement
|
||||
image_replace[ipath] = image_url
|
||||
# Store base64 string in final images dict
|
||||
images[image_url] = base64.b64encode(b64_bytes).decode()
|
||||
|
||||
# Replace temporary paths with actual uploaded URLs
|
||||
text = self.image_helper.replace_path(text, image_replace)
|
||||
return Document(content=text, images=images)
|
||||
|
||||
|
||||
class MarkdownParser(PipelineParser):
|
||||
"""Complete Markdown parser using pipeline approach.
|
||||
|
||||
This parser processes Markdown content through multiple stages:
|
||||
1. MarkdownTableFormatter: Standardizes table formatting
|
||||
2. MarkdownImageBase64: Extracts and uploads base64 images
|
||||
|
||||
The pipeline ensures that content flows through each parser in sequence,
|
||||
with each stage's output becoming the next stage's input.
|
||||
"""
|
||||
_parser_cls = (MarkdownTableFormatter, MarkdownImageBase64)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage and testing
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Test the complete MarkdownParser pipeline
|
||||
your_content = "testtest"
|
||||
parser = MarkdownParser()
|
||||
|
||||
# Parse content and display results
|
||||
document = parser.parse_into_text(your_content.encode())
|
||||
logger.info(document.content)
|
||||
logger.info(f"Images: {len(document.images)}, name: {document.images.keys()}")
|
||||
|
||||
# Run individual utility tests
|
||||
MarkdownImageUtil._self_test()
|
||||
MarkdownTableUtil._self_test()
|
||||
|
|
|
|||
|
|
@ -16,20 +16,47 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class StdMinerUParser(BaseParser):
|
||||
"""
|
||||
Standard MinerU Parser for document parsing.
|
||||
|
||||
This parser uses MinerU API to parse documents (especially PDFs) into markdown format,
|
||||
with support for tables, formulas, and images extraction.
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
enable_markdownify: bool = True,
|
||||
mineru_endpoint: str = "",
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize MinerU parser.
|
||||
|
||||
Args:
|
||||
enable_markdownify: Whether to convert HTML tables to markdown format
|
||||
mineru_endpoint: MinerU API endpoint URL
|
||||
**kwargs: Additional arguments passed to BaseParser
|
||||
"""
|
||||
super().__init__(**kwargs)
|
||||
# Get MinerU endpoint from environment variable or parameter
|
||||
self.minerU = os.getenv("MINERU_ENDPOINT", mineru_endpoint)
|
||||
self.enable_markdownify = enable_markdownify
|
||||
# Helper for processing markdown images
|
||||
self.image_helper = MarkdownImageUtil()
|
||||
# Pattern to match base64 encoded images
|
||||
self.base64_pattern = re.compile(r"data:image/(\w+);base64,(.*)")
|
||||
# Check if MinerU API is available
|
||||
self.enable = self.ping()
|
||||
|
||||
def ping(self, timeout: int = 5) -> bool:
|
||||
"""
|
||||
Check if MinerU API is available.
|
||||
|
||||
Args:
|
||||
timeout: Request timeout in seconds
|
||||
|
||||
Returns:
|
||||
True if API is available, False otherwise
|
||||
"""
|
||||
try:
|
||||
response = requests.get(
|
||||
self.minerU + "/docs", timeout=timeout, allow_redirects=True
|
||||
|
|
@ -40,6 +67,15 @@ class StdMinerUParser(BaseParser):
|
|||
return False
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""
|
||||
Parse document content into text using MinerU API.
|
||||
|
||||
Args:
|
||||
content: Raw document content in bytes
|
||||
|
||||
Returns:
|
||||
Document object containing parsed text and images
|
||||
"""
|
||||
if not self.enable:
|
||||
logger.debug("MinerU API is not enabled")
|
||||
return Document()
|
||||
|
|
@ -48,22 +84,23 @@ class StdMinerUParser(BaseParser):
|
|||
md_content: str = ""
|
||||
images_b64: Dict[str, str] = {}
|
||||
try:
|
||||
# Call MinerU API to parse document
|
||||
response = requests.post(
|
||||
url=self.minerU + "/file_parse",
|
||||
data={
|
||||
"return_md": True,
|
||||
"return_images": True,
|
||||
"lang_list": ["ch", "en"],
|
||||
"table_enable": True,
|
||||
"formula_enable": True,
|
||||
"parse_method": "auto",
|
||||
"start_page_id": 0,
|
||||
"end_page_id": 99999,
|
||||
"backend": "pipeline",
|
||||
"response_format_zip": False,
|
||||
"return_middle_json": False,
|
||||
"return_model_output": False,
|
||||
"return_content_list": False,
|
||||
"return_md": True, # Return markdown content
|
||||
"return_images": True, # Return extracted images
|
||||
"lang_list": ["ch", "en"], # Support Chinese and English
|
||||
"table_enable": True, # Enable table parsing
|
||||
"formula_enable": True, # Enable formula parsing
|
||||
"parse_method": "auto", # Auto detect parsing method
|
||||
"start_page_id": 0, # Start from first page
|
||||
"end_page_id": 99999, # Parse all pages
|
||||
"backend": "pipeline", # Use pipeline backend
|
||||
"response_format_zip": False, # Return JSON instead of ZIP
|
||||
"return_middle_json": False, # Don't return intermediate JSON
|
||||
"return_model_output": False, # Don't return model output
|
||||
"return_content_list": False, # Don't return content list
|
||||
},
|
||||
files={"files": content},
|
||||
timeout=1000,
|
||||
|
|
@ -76,38 +113,47 @@ class StdMinerUParser(BaseParser):
|
|||
logger.error(f"MinerU parsing failed: {e}", exc_info=True)
|
||||
return Document()
|
||||
|
||||
# convert table(HTML) in markdown to markdown table
|
||||
# Convert HTML tables in markdown to markdown table format
|
||||
if self.enable_markdownify:
|
||||
logger.debug("Converting HTML to Markdown")
|
||||
md_content = markdownify.markdownify(md_content)
|
||||
|
||||
images = {}
|
||||
image_replace = {}
|
||||
# image in images_bs64 may not be used in md_content
|
||||
# such as: table ...
|
||||
# so we need to filter them
|
||||
# Filter images that are actually used in markdown content
|
||||
# Some images in images_b64 may not be referenced in md_content
|
||||
# (e.g., images embedded in tables), so we need to filter them
|
||||
for ipath, b64_str in images_b64.items():
|
||||
# Skip images that are not referenced in markdown content
|
||||
if f"images/{ipath}" not in md_content:
|
||||
logger.debug(f"Image {ipath} not used in markdown")
|
||||
continue
|
||||
# Parse base64 image data
|
||||
match = self.base64_pattern.match(b64_str)
|
||||
if match:
|
||||
# Extract image format (e.g., png, jpg)
|
||||
file_ext = match.group(1)
|
||||
# Extract base64 encoded data
|
||||
b64_str = match.group(2)
|
||||
|
||||
# Decode base64 string to bytes
|
||||
image_bytes = endecode.encode_image(b64_str, errors="ignore")
|
||||
if not image_bytes:
|
||||
logger.error("Failed to decode base64 image skip it")
|
||||
continue
|
||||
|
||||
# Upload image to storage and get URL
|
||||
image_url = self.storage.upload_bytes(
|
||||
image_bytes, file_ext=f".{file_ext}"
|
||||
)
|
||||
|
||||
# Store image mapping for later use
|
||||
images[image_url] = b64_str
|
||||
# Prepare replacement mapping for markdown content
|
||||
image_replace[f"images/{ipath}"] = image_url
|
||||
|
||||
logger.info(f"Replaced {len(image_replace)} images in markdown")
|
||||
# Replace image paths in markdown with uploaded URLs
|
||||
text = self.image_helper.replace_path(md_content, image_replace)
|
||||
|
||||
logger.info(
|
||||
|
|
@ -117,15 +163,27 @@ class StdMinerUParser(BaseParser):
|
|||
|
||||
|
||||
class MinerUParser(PipelineParser):
|
||||
"""
|
||||
MinerU Parser with pipeline processing.
|
||||
|
||||
This parser combines StdMinerUParser for document parsing and
|
||||
MarkdownTableFormatter for table formatting in a pipeline.
|
||||
"""
|
||||
_parser_cls = (StdMinerUParser, MarkdownTableFormatter)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage for testing
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Configure your file path and MinerU endpoint
|
||||
your_file = "/path/to/your/file.pdf"
|
||||
your_mineru = "http://host.docker.internal:9987"
|
||||
|
||||
# Create parser instance
|
||||
parser = MinerUParser(mineru_endpoint=your_mineru)
|
||||
|
||||
# Parse PDF file
|
||||
with open(your_file, "rb") as f:
|
||||
content = f.read()
|
||||
document = parser.parse_into_text(content)
|
||||
|
|
|
|||
|
|
@ -52,8 +52,10 @@ class PaddleOCRBackend(OCRBackend):
|
|||
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
||||
paddle.device.set_device("cpu")
|
||||
|
||||
# Try to detect if CPU supports AVX instruction set
|
||||
# 尝试检测CPU是否支持AVX指令集
|
||||
try:
|
||||
# Detect if CPU supports AVX
|
||||
# 检测CPU是否支持AVX
|
||||
if platform.system() == "Linux":
|
||||
try:
|
||||
|
|
@ -69,6 +71,7 @@ class PaddleOCRBackend(OCRBackend):
|
|||
"CPU does not support AVX instructions, "
|
||||
"using compatibility mode"
|
||||
)
|
||||
# Further restrict instruction set usage
|
||||
# 进一步限制指令集使用
|
||||
os.environ["FLAGS_use_avx2"] = "0"
|
||||
os.environ["FLAGS_use_avx"] = "1"
|
||||
|
|
@ -96,9 +99,9 @@ class PaddleOCRBackend(OCRBackend):
|
|||
"use_gpu": False,
|
||||
"text_det_limit_type": "max",
|
||||
"text_det_limit_side_len": 960,
|
||||
"use_doc_orientation_classify": True, # 启用文档方向分类
|
||||
"use_doc_orientation_classify": True, # Enable document orientation classification / 启用文档方向分类
|
||||
"use_doc_unwarping": False,
|
||||
"use_textline_orientation": True, # 启用文本行方向检测
|
||||
"use_textline_orientation": True, # Enable text line orientation detection / 启用文本行方向检测
|
||||
"text_recognition_model_name": "PP-OCRv4_server_rec",
|
||||
"text_detection_model_name": "PP-OCRv4_server_det",
|
||||
"text_det_thresh": 0.3,
|
||||
|
|
@ -174,13 +177,13 @@ class PaddleOCRBackend(OCRBackend):
|
|||
if image.mode != "RGB":
|
||||
image = image.convert("RGB")
|
||||
|
||||
# Convert to numpy array if needed
|
||||
# Convert to numpy array for PaddleOCR processing
|
||||
image_array = np.array(image)
|
||||
|
||||
# Perform OCR
|
||||
# Perform OCR recognition
|
||||
ocr_result = self.ocr.ocr(image_array, cls=False)
|
||||
|
||||
# Extract text
|
||||
# Extract and concatenate text from OCR results
|
||||
ocr_text = ""
|
||||
if ocr_result and ocr_result[0]:
|
||||
text = [
|
||||
|
|
@ -209,6 +212,7 @@ class NanonetsOCRBackend(OCRBackend):
|
|||
base_url: Base URL for OpenAI API
|
||||
model: Model name
|
||||
"""
|
||||
# Load configuration from environment variables
|
||||
base_url = os.getenv("OCR_API_BASE_URL", "http://localhost:8000/v1")
|
||||
api_key = os.getenv("OCR_API_KEY", "123")
|
||||
timeout = 30
|
||||
|
|
@ -218,6 +222,7 @@ class NanonetsOCRBackend(OCRBackend):
|
|||
logger.info(f"Nanonets OCR engine initialized with model: {self.model}")
|
||||
self.temperature = 0.0
|
||||
self.max_tokens = 15000
|
||||
# Prompt for OCR text extraction with specific formatting requirements
|
||||
self.prompt = """## 任务说明
|
||||
|
||||
请从上传的文档中提取文字内容,严格按自然阅读顺序(从上到下,从左到右)输出,并遵循以下格式规范。
|
||||
|
|
@ -258,12 +263,12 @@ class NanonetsOCRBackend(OCRBackend):
|
|||
return ""
|
||||
|
||||
try:
|
||||
# Encode image to base64
|
||||
# Encode image to base64 format for API transmission
|
||||
img_base64 = endecode.decode_image(image)
|
||||
if not img_base64:
|
||||
return ""
|
||||
|
||||
# Call Nanonets OCR API
|
||||
# Call Nanonets OCR API using OpenAI-compatible format
|
||||
logger.info(f"Calling Nanonets OCR API with model: {self.model}")
|
||||
response = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
|
|
@ -294,13 +299,14 @@ class NanonetsOCRBackend(OCRBackend):
|
|||
|
||||
|
||||
class OCREngine:
|
||||
"""OCR Engine factory class"""
|
||||
"""OCR Engine factory class for managing different OCR backend instances"""
|
||||
|
||||
# Singleton pattern: cache instances for each backend type
|
||||
_instance: Dict[str, OCRBackend] = {}
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls, backend_type: str) -> OCRBackend:
|
||||
"""Get OCR engine instance
|
||||
"""Get OCR engine instance using factory pattern
|
||||
|
||||
Args:
|
||||
backend_type: OCR backend type, one of: "paddle", "nanonets"
|
||||
|
|
@ -310,6 +316,7 @@ class OCREngine:
|
|||
OCR engine instance or None if initialization fails
|
||||
"""
|
||||
backend_type = backend_type.lower()
|
||||
# Return cached instance if already initialized
|
||||
if cls._instance.get(backend_type):
|
||||
return cls._instance[backend_type]
|
||||
|
||||
|
|
|
|||
|
|
@ -24,13 +24,15 @@ class Parser:
|
|||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Initialize all parser types
|
||||
# Initialize all parser types - maps file extensions to their corresponding parser classes
|
||||
self.parsers: Dict[str, Type[BaseParser]] = {
|
||||
# Document formats
|
||||
"docx": Docx2Parser,
|
||||
"doc": DocParser,
|
||||
"pdf": PDFParser,
|
||||
"md": MarkdownParser,
|
||||
"txt": TextParser,
|
||||
# Image formats - all use the same ImageParser
|
||||
"jpg": ImageParser,
|
||||
"jpeg": ImageParser,
|
||||
"png": ImageParser,
|
||||
|
|
@ -38,7 +40,9 @@ class Parser:
|
|||
"bmp": ImageParser,
|
||||
"tiff": ImageParser,
|
||||
"webp": ImageParser,
|
||||
# Alternative markdown extension
|
||||
"markdown": MarkdownParser,
|
||||
# Spreadsheet formats
|
||||
"csv": CSVParser,
|
||||
"xlsx": ExcelParser,
|
||||
"xls": ExcelParser,
|
||||
|
|
@ -59,8 +63,10 @@ class Parser:
|
|||
Returns:
|
||||
Parser class for the file type, or None if unsupported
|
||||
"""
|
||||
# Look up parser by file type (case-insensitive)
|
||||
parser = self.parsers.get(file_type.lower())
|
||||
if not parser:
|
||||
# Raise error if file type is not supported
|
||||
raise ValueError(f"Unsupported file type: {file_type}")
|
||||
return parser
|
||||
|
||||
|
|
@ -90,31 +96,34 @@ class Parser:
|
|||
f"multimodal={config.enable_multimodal}"
|
||||
)
|
||||
|
||||
# Get appropriate parser for file type
|
||||
# Get appropriate parser class for the file type
|
||||
cls = self.get_parser(file_type)
|
||||
|
||||
# Parse file content
|
||||
# Create parser instance with configuration
|
||||
logger.info(f"Creating parser instance for {file_type} file")
|
||||
parser = cls(
|
||||
file_name=file_name,
|
||||
file_type=file_type,
|
||||
chunk_size=config.chunk_size,
|
||||
chunk_overlap=config.chunk_overlap,
|
||||
separators=config.separators,
|
||||
enable_multimodal=config.enable_multimodal,
|
||||
max_image_size=1920, # Limit image size to 1920px
|
||||
max_concurrent_tasks=5, # Limit concurrent tasks to 5
|
||||
chunking_config=config, # Pass the entire chunking config
|
||||
chunk_size=config.chunk_size, # Size of each text chunk
|
||||
chunk_overlap=config.chunk_overlap, # Overlap between consecutive chunks
|
||||
separators=config.separators, # Text separators for chunking
|
||||
enable_multimodal=config.enable_multimodal, # Enable image/multimodal processing
|
||||
max_image_size=1920, # Limit image size to 1920px for performance
|
||||
max_concurrent_tasks=5, # Limit concurrent tasks to 5 to avoid resource exhaustion
|
||||
chunking_config=config, # Pass the entire chunking config for advanced options
|
||||
)
|
||||
|
||||
logger.info(f"Starting to parse file content, size: {len(content)} bytes")
|
||||
# Execute the parsing process
|
||||
result = parser.parse(content)
|
||||
|
||||
# Validate parsing results and log warnings if needed
|
||||
if not result.content:
|
||||
logger.warning(f"Parser returned empty content for file: {file_name}")
|
||||
elif not result.chunks:
|
||||
logger.warning(f"Parser returned empty chunks for file: {file_name}")
|
||||
elif result.chunks[0]:
|
||||
# Log first chunk size for debugging
|
||||
logger.info(f"First chunk content length: {len(result.chunks[0].content)}")
|
||||
logger.info(f"Parsed file {file_name}, with {len(result.chunks)} chunks")
|
||||
return result
|
||||
|
|
@ -137,27 +146,30 @@ class Parser:
|
|||
f"overlap={config.chunk_overlap}, multimodal={config.enable_multimodal}"
|
||||
)
|
||||
|
||||
# Create web parser instance
|
||||
# Create web parser instance with configuration
|
||||
logger.info("Creating WebParser instance")
|
||||
parser = WebParser(
|
||||
title=title,
|
||||
chunk_size=config.chunk_size,
|
||||
chunk_overlap=config.chunk_overlap,
|
||||
separators=config.separators,
|
||||
enable_multimodal=config.enable_multimodal,
|
||||
max_image_size=1920, # Limit image size
|
||||
max_concurrent_tasks=5, # Limit concurrent tasks
|
||||
chunking_config=config,
|
||||
title=title, # Webpage title for metadata
|
||||
chunk_size=config.chunk_size, # Size of each text chunk
|
||||
chunk_overlap=config.chunk_overlap, # Overlap between consecutive chunks
|
||||
separators=config.separators, # Text separators for chunking
|
||||
enable_multimodal=config.enable_multimodal, # Enable image/multimodal processing
|
||||
max_image_size=1920, # Limit image size to 1920px for performance
|
||||
max_concurrent_tasks=5, # Limit concurrent tasks to avoid resource exhaustion
|
||||
chunking_config=config, # Pass the entire chunking config
|
||||
)
|
||||
|
||||
logger.info("Starting to parse URL content")
|
||||
# Parse URL content (encode URL string to bytes as required by parser interface)
|
||||
result = parser.parse(url.encode())
|
||||
|
||||
# Validate parsing results and log warnings if needed
|
||||
if not result.content:
|
||||
logger.warning(f"Parser returned empty content for url: {url}")
|
||||
elif not result.chunks:
|
||||
logger.warning(f"Parser returned empty chunks for url: {url}")
|
||||
elif result.chunks[0]:
|
||||
# Log first chunk size for debugging
|
||||
logger.info(f"First chunk content length: {len(result.chunks[0].content)}")
|
||||
logger.info(f"Parsed url {url}, with {len(result.chunks)} chunks")
|
||||
return result
|
||||
|
|
|
|||
|
|
@ -4,4 +4,13 @@ from docreader.parser.mineru_parser import MinerUParser
|
|||
|
||||
|
||||
class PDFParser(FirstParser):
|
||||
"""PDF Parser using chain of responsibility pattern
|
||||
|
||||
Attempts to parse PDF files using multiple parser backends in order:
|
||||
1. MinerUParser - Primary parser for PDF documents
|
||||
2. MarkitdownParser - Fallback parser if MinerU fails
|
||||
|
||||
The first successful parser result will be returned.
|
||||
"""
|
||||
# Parser classes to try in order (chain of responsibility pattern)
|
||||
_parser_cls = (MinerUParser, MarkitdownParser)
|
||||
|
|
|
|||
|
|
@ -244,8 +244,18 @@ class MinioStorage(Storage):
|
|||
found = client.bucket_exists(bucket_name)
|
||||
if not found:
|
||||
client.make_bucket(bucket_name)
|
||||
# Set public read policy for the bucket
|
||||
policy = (
|
||||
'{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetBucketLocation","s3:ListBucket"],"Resource":["arn:aws:s3:::%s"]},{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}'
|
||||
'{'
|
||||
'"Version":"2012-10-17",'
|
||||
'"Statement":['
|
||||
'{"Effect":"Allow","Principal":{"AWS":["*"]},'
|
||||
'"Action":["s3:GetBucketLocation","s3:ListBucket"],'
|
||||
'"Resource":["arn:aws:s3:::%s"]},'
|
||||
'{"Effect":"Allow","Principal":{"AWS":["*"]},'
|
||||
'"Action":["s3:GetObject"],'
|
||||
'"Resource":["arn:aws:s3:::%s/*"]}'
|
||||
']}'
|
||||
% (bucket_name, bucket_name)
|
||||
)
|
||||
client.set_bucket_policy(bucket_name, policy)
|
||||
|
|
|
|||
|
|
@ -15,19 +15,40 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class StdWebParser(BaseParser):
|
||||
"""Web page parser"""
|
||||
"""Standard web page parser using Playwright and Trafilatura.
|
||||
|
||||
This parser scrapes web pages using Playwright's WebKit browser and extracts
|
||||
clean content using Trafilatura library. It supports proxy configuration and
|
||||
converts HTML content to markdown format.
|
||||
"""
|
||||
|
||||
def __init__(self, title: str, **kwargs):
|
||||
"""Initialize the web parser.
|
||||
|
||||
Args:
|
||||
title: Title of the web page to be used as file name
|
||||
**kwargs: Additional arguments passed to BaseParser
|
||||
"""
|
||||
self.title = title
|
||||
# Get proxy configuration from environment variable if available
|
||||
self.proxy = os.environ.get("WEB_PROXY", "")
|
||||
super().__init__(file_name=title, **kwargs)
|
||||
logger.info(f"Initialized WebParser with title: {title}")
|
||||
|
||||
async def scrape(self, url: str) -> str:
|
||||
"""Scrape web page content using Playwright.
|
||||
|
||||
Args:
|
||||
url: The URL of the web page to scrape
|
||||
|
||||
Returns:
|
||||
HTML content of the web page as string, empty string on error
|
||||
"""
|
||||
logger.info(f"Starting web page scraping for URL: {url}")
|
||||
try:
|
||||
async with async_playwright() as p:
|
||||
kwargs = {}
|
||||
# Configure proxy if available
|
||||
if self.proxy:
|
||||
kwargs["proxy"] = {"server": self.proxy}
|
||||
logger.info("Launching WebKit browser")
|
||||
|
|
@ -36,6 +57,7 @@ class StdWebParser(BaseParser):
|
|||
|
||||
logger.info(f"Navigating to URL: {url}")
|
||||
try:
|
||||
# Navigate to URL with 30 second timeout
|
||||
await page.goto(url, timeout=30000)
|
||||
logger.info("Initial page load complete")
|
||||
except Exception as e:
|
||||
|
|
@ -44,35 +66,40 @@ class StdWebParser(BaseParser):
|
|||
return ""
|
||||
|
||||
logger.info("Retrieving page HTML content")
|
||||
# Get the full HTML content of the page
|
||||
content = await page.content()
|
||||
logger.info(f"Retrieved {len(content)} bytes of HTML content")
|
||||
|
||||
await browser.close()
|
||||
logger.info("Browser closed")
|
||||
|
||||
# Parse HTML content with BeautifulSoup
|
||||
# Return raw HTML content for further processing
|
||||
logger.info("Parsing HTML with BeautifulSoup")
|
||||
logger.info("Successfully parsed HTML content")
|
||||
return content
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to scrape web page: {str(e)}")
|
||||
# Return empty BeautifulSoup object on error
|
||||
# Return empty string on error
|
||||
return ""
|
||||
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse web page
|
||||
"""Parse web page content into a Document object.
|
||||
|
||||
Args:
|
||||
content: Web page content
|
||||
content: URL encoded as bytes
|
||||
|
||||
Returns:
|
||||
Parse result
|
||||
Document object containing the parsed markdown content
|
||||
"""
|
||||
# Decode bytes to get the URL string
|
||||
url = endecode.decode_bytes(content)
|
||||
|
||||
logger.info(f"Scraping web page: {url}")
|
||||
# Run async scraping in sync context
|
||||
chtml = asyncio.run(self.scrape(url))
|
||||
# Extract clean content from HTML using Trafilatura
|
||||
# Convert to markdown format with metadata, images, tables, and links
|
||||
md_text = extract(
|
||||
chtml,
|
||||
output_format="markdown",
|
||||
|
|
@ -80,7 +107,7 @@ class StdWebParser(BaseParser):
|
|||
include_images=True,
|
||||
include_tables=True,
|
||||
include_links=True,
|
||||
deduplicate=True,
|
||||
deduplicate=True, # Remove duplicate content
|
||||
)
|
||||
if not md_text:
|
||||
logger.error("Failed to parse web page")
|
||||
|
|
@ -89,16 +116,27 @@ class StdWebParser(BaseParser):
|
|||
|
||||
|
||||
class WebParser(PipelineParser):
|
||||
"""Web parser using pipeline pattern.
|
||||
|
||||
This parser chains StdWebParser (for web scraping and HTML to markdown conversion)
|
||||
with MarkdownParser (for markdown processing). The pipeline processes content
|
||||
sequentially through both parsers.
|
||||
"""
|
||||
# Parser classes to be executed in sequence
|
||||
_parser_cls = (StdWebParser, MarkdownParser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Configure logging for debugging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# Example URL to scrape
|
||||
url = "https://cloud.tencent.com/document/product/457/6759"
|
||||
|
||||
# Create parser instance and parse the web page
|
||||
parser = WebParser(title="")
|
||||
cc = parser.parse_into_text(url.encode())
|
||||
# Save the parsed markdown content to file
|
||||
with open("./tencent.md", "w") as f:
|
||||
f.write(cc.content)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,11 @@
|
|||
"""Token splitter."""
|
||||
"""Token splitter.
|
||||
|
||||
This module provides text splitting functionality with support for:
|
||||
- Configurable chunk size and overlap
|
||||
- Protected regex patterns (e.g., math formulas, images, links, tables)
|
||||
- Header tracking for context preservation
|
||||
- Smart merging with overlap handling
|
||||
"""
|
||||
|
||||
import itertools
|
||||
import logging
|
||||
|
|
@ -12,8 +19,9 @@ from docreader.splitter.header_hook import (
|
|||
)
|
||||
from docreader.utils.split import split_by_char, split_by_sep
|
||||
|
||||
DEFAULT_CHUNK_OVERLAP = 100
|
||||
DEFAULT_CHUNK_SIZE = 512
|
||||
# Default configuration for text chunking
|
||||
DEFAULT_CHUNK_OVERLAP = 100 # Number of tokens to overlap between chunks
|
||||
DEFAULT_CHUNK_SIZE = 512 # Maximum size of each chunk in tokens
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
|
@ -21,6 +29,15 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class TextSplitter(BaseModel, Generic[T]):
|
||||
"""Text splitter with support for protected patterns and header tracking.
|
||||
|
||||
This class splits text into chunks while:
|
||||
- Respecting chunk size and overlap constraints
|
||||
- Preserving protected patterns (formulas, tables, code blocks)
|
||||
- Tracking headers for context preservation
|
||||
- Maintaining text integrity with smart merging
|
||||
"""
|
||||
|
||||
chunk_size: int = Field(description="The token chunk size for each chunk.")
|
||||
chunk_overlap: int = Field(
|
||||
description="The token overlap of each chunk when splitting."
|
||||
|
|
@ -31,14 +48,18 @@ class TextSplitter(BaseModel, Generic[T]):
|
|||
|
||||
# Try to keep the matched characters as a whole.
|
||||
# If it's too long, the content will be further segmented.
|
||||
# 尝试将匹配的字符作为整体保留,如果太长则进一步分段
|
||||
protected_regex: List[str] = Field(
|
||||
description="Protected regex for splitting into words"
|
||||
)
|
||||
len_function: Callable[[str], int] = Field(description="The length function.")
|
||||
# Header tracking Hook related attributes
|
||||
# 标题跟踪钩子相关属性
|
||||
header_hook: HeaderTracker = Field(default_factory=HeaderTracker, exclude=True)
|
||||
|
||||
# Compiled regex patterns for protected content
|
||||
_protected_fns: List[Pattern] = PrivateAttr()
|
||||
# Split functions for different separators
|
||||
_split_fns: List[Callable] = PrivateAttr()
|
||||
|
||||
def __init__(
|
||||
|
|
@ -47,22 +68,33 @@ class TextSplitter(BaseModel, Generic[T]):
|
|||
chunk_overlap: int = DEFAULT_CHUNK_OVERLAP,
|
||||
separators: List[str] = ["\n", "。", " "],
|
||||
protected_regex: List[str] = [
|
||||
# math formula
|
||||
# math formula - LaTeX style formulas enclosed in $$
|
||||
r"\$\$[\s\S]*?\$\$",
|
||||
# image
|
||||
# image - Markdown image syntax 
|
||||
r"!\[.*?\]\(.*?\)",
|
||||
# link
|
||||
# link - Markdown link syntax [text](url)
|
||||
r"\[.*?\]\(.*?\)",
|
||||
# table header
|
||||
# table header - Markdown table header with separator line
|
||||
r"(?:\|[^|\n]*)+\|[\r\n]+\s*(?:\|\s*:?-{3,}:?\s*)+\|[\r\n]+",
|
||||
# table body
|
||||
# table body - Markdown table rows
|
||||
r"(?:\|[^|\n]*)+\|[\r\n]+",
|
||||
# code header
|
||||
# code header - Code block start with language identifier
|
||||
r"```(?:\w+)[\r\n]+[^\r\n]*",
|
||||
],
|
||||
length_function: Callable[[str], int] = lambda x: len(x),
|
||||
):
|
||||
"""Initialize with parameters."""
|
||||
"""Initialize with parameters.
|
||||
|
||||
Args:
|
||||
chunk_size: Maximum size of each chunk
|
||||
chunk_overlap: Number of tokens to overlap between chunks
|
||||
separators: List of separators to use for splitting (in priority order)
|
||||
protected_regex: Regex patterns for content that should be kept intact
|
||||
length_function: Function to calculate text length (default: character count)
|
||||
|
||||
Raises:
|
||||
ValueError: If chunk_overlap is larger than chunk_size
|
||||
"""
|
||||
if chunk_overlap > chunk_size:
|
||||
raise ValueError(
|
||||
f"Got a larger chunk overlap ({chunk_overlap}) than chunk size "
|
||||
|
|
@ -76,75 +108,120 @@ class TextSplitter(BaseModel, Generic[T]):
|
|||
protected_regex=protected_regex,
|
||||
len_function=length_function,
|
||||
)
|
||||
# Compile all protected regex patterns for efficient matching
|
||||
self._protected_fns = [re.compile(reg) for reg in protected_regex]
|
||||
# Create split functions: one for each separator, plus character-level splitting as fallback
|
||||
self._split_fns = [split_by_sep(sep) for sep in separators] + [split_by_char()]
|
||||
|
||||
def split_text(self, text: str) -> List[Tuple[int, int, str]]:
|
||||
"""Split text into chunks."""
|
||||
"""Split text into chunks with overlap and protected pattern handling.
|
||||
|
||||
Args:
|
||||
text: The input text to split
|
||||
|
||||
Returns:
|
||||
List of tuples (start_pos, end_pos, chunk_text) representing each chunk
|
||||
"""
|
||||
if text == "":
|
||||
return []
|
||||
|
||||
# Step 1: Split text by separators recursively
|
||||
splits = self._split(text)
|
||||
# Step 2: Extract protected content positions
|
||||
protect = self._split_protected(text)
|
||||
# Step 3: Merge splits with protected content to ensure integrity
|
||||
splits = self._join(splits, protect)
|
||||
|
||||
# Verify that joining all splits reconstructs the original text
|
||||
assert "".join(splits) == text
|
||||
|
||||
# Step 4: Merge splits into final chunks with overlap
|
||||
chunks = self._merge(splits)
|
||||
return chunks
|
||||
|
||||
def _split(self, text: str) -> List[str]:
|
||||
"""Break text into splits that are smaller than chunk size.
|
||||
|
||||
This method recursively splits text using separators in priority order.
|
||||
It tries each separator until it finds one that can split the text,
|
||||
then recursively processes any splits that are still too large.
|
||||
|
||||
NOTE: the splits contain the separators.
|
||||
|
||||
Args:
|
||||
text: The text to split
|
||||
|
||||
Returns:
|
||||
List of text splits, each smaller than chunk_size
|
||||
"""
|
||||
# If text is already small enough, return as-is
|
||||
if self.len_function(text) <= self.chunk_size:
|
||||
return [text]
|
||||
|
||||
# Try each split function in order until one successfully splits the text
|
||||
splits = []
|
||||
for split_fn in self._split_fns:
|
||||
splits = split_fn(text)
|
||||
if len(splits) > 1:
|
||||
break
|
||||
|
||||
# Process each split: keep if small enough, otherwise recursively split further
|
||||
new_splits = []
|
||||
for split in splits:
|
||||
split_len = self.len_function(split)
|
||||
if split_len <= self.chunk_size:
|
||||
new_splits.append(split)
|
||||
else:
|
||||
# recursively split
|
||||
# Recursively split oversized chunks
|
||||
new_splits.extend(self._split(split))
|
||||
return new_splits
|
||||
|
||||
def _merge(self, splits: List[str]) -> List[Tuple[int, int, str]]:
|
||||
"""Merge splits into chunks.
|
||||
"""Merge splits into chunks with overlap and header tracking.
|
||||
|
||||
The high-level idea is to keep adding splits to a chunk until we
|
||||
exceed the chunk size, then we start a new chunk with overlap.
|
||||
|
||||
When we start a new chunk, we pop off the first element of the previous
|
||||
chunk until the total length is less than the chunk size.
|
||||
|
||||
Headers are tracked and prepended to chunks for context preservation.
|
||||
|
||||
Args:
|
||||
splits: List of text splits to merge
|
||||
|
||||
Returns:
|
||||
List of tuples (start_pos, end_pos, chunk_text) representing merged chunks
|
||||
"""
|
||||
# Final list of chunks with their positions
|
||||
chunks: List[Tuple[int, int, str]] = []
|
||||
|
||||
# Current chunk being built: list of (start, end, text) tuples
|
||||
cur_chunk: List[Tuple[int, int, str]] = []
|
||||
|
||||
# Track current headers and chunk length
|
||||
cur_headers, cur_len = "", 0
|
||||
# Track position in original text
|
||||
cur_start, cur_end = 0, 0
|
||||
|
||||
for split in splits:
|
||||
# Calculate position of current split in original text
|
||||
cur_end = cur_start + len(split)
|
||||
split_len = self.len_function(split)
|
||||
|
||||
# Warn if a single split exceeds chunk size (shouldn't happen after _split)
|
||||
if split_len > self.chunk_size:
|
||||
logger.error(
|
||||
f"Got a split of size {split_len}, ",
|
||||
f"larger than chunk size {self.chunk_size}.",
|
||||
)
|
||||
|
||||
# Update header tracking with current split
|
||||
self.header_hook.update(split)
|
||||
cur_headers = self.header_hook.get_headers()
|
||||
cur_headers_len = self.len_function(cur_headers)
|
||||
|
||||
# If headers are too large, skip them to avoid oversized chunks
|
||||
if cur_headers_len > self.chunk_size:
|
||||
logger.error(
|
||||
f"Got headers of size {cur_headers_len}, ",
|
||||
|
|
@ -152,51 +229,53 @@ class TextSplitter(BaseModel, Generic[T]):
|
|||
)
|
||||
cur_headers, cur_headers_len = "", 0
|
||||
|
||||
# if we exceed the chunk size after adding the new split, then
|
||||
# we need to end the current chunk and start a new one
|
||||
# Check if adding this split would exceed chunk size
|
||||
# If so, finalize current chunk and start a new one with overlap
|
||||
if cur_len + split_len + cur_headers_len > self.chunk_size:
|
||||
# end the previous chunk
|
||||
# Finalize the previous chunk if it has content
|
||||
if len(cur_chunk) > 0:
|
||||
chunks.append(
|
||||
(
|
||||
cur_chunk[0][0],
|
||||
cur_chunk[-1][1],
|
||||
"".join([c[2] for c in cur_chunk]),
|
||||
cur_chunk[0][0], # Start position of first element
|
||||
cur_chunk[-1][1], # End position of last element
|
||||
"".join([c[2] for c in cur_chunk]), # Concatenated text
|
||||
)
|
||||
)
|
||||
|
||||
# start a new chunk with overlap
|
||||
# keep popping off the first element of the previous chunk until:
|
||||
# Start a new chunk with overlap from previous chunk
|
||||
# Keep popping off the first element of the previous chunk until:
|
||||
# 1. the current chunk length is less than chunk overlap
|
||||
# 2. the total length is less than chunk size
|
||||
while cur_chunk and (
|
||||
cur_len > self.chunk_overlap
|
||||
or cur_len + split_len + cur_headers_len > self.chunk_size
|
||||
):
|
||||
# pop off the first element
|
||||
# Remove the first element to reduce overlap
|
||||
first_chunk = cur_chunk.pop(0)
|
||||
cur_len -= self.len_function(first_chunk[2])
|
||||
|
||||
# Prepend headers to new chunk if:
|
||||
# 1. Headers exist
|
||||
# 2. Headers + split fit in chunk size
|
||||
# 3. Headers are not already in the split
|
||||
if (
|
||||
cur_headers
|
||||
and split_len + cur_headers_len < self.chunk_size
|
||||
and cur_headers not in split
|
||||
):
|
||||
cur_chunk.insert(
|
||||
0,
|
||||
(
|
||||
cur_chunk[0][0] if cur_chunk else cur_start,
|
||||
cur_chunk[0][1] if cur_chunk else cur_end,
|
||||
cur_headers,
|
||||
),
|
||||
)
|
||||
next_start = cur_chunk[0][0] if cur_chunk else cur_start
|
||||
header_start = max(0, next_start - cur_headers_len)
|
||||
header_end = cur_end
|
||||
|
||||
cur_chunk.insert(0, (header_start, header_end, cur_headers))
|
||||
cur_len += cur_headers_len
|
||||
|
||||
# Add current split to the chunk
|
||||
cur_chunk.append((cur_start, cur_end, split))
|
||||
cur_len += split_len
|
||||
cur_start = cur_end
|
||||
|
||||
# handle the last chunk
|
||||
# Handle the last chunk (there should always be at least one)
|
||||
assert cur_chunk
|
||||
chunks.append(
|
||||
(
|
||||
|
|
@ -209,29 +288,44 @@ class TextSplitter(BaseModel, Generic[T]):
|
|||
return chunks
|
||||
|
||||
def _split_protected(self, text: str) -> List[Tuple[int, str]]:
|
||||
"""Extract protected content from text based on regex patterns.
|
||||
|
||||
Args:
|
||||
text: The input text to scan for protected patterns
|
||||
|
||||
Returns:
|
||||
List of tuples (start_position, protected_text) for each protected match
|
||||
"""
|
||||
# Find all matches for all protected patterns
|
||||
matches = [
|
||||
(match.start(), match.end())
|
||||
for pattern in self._protected_fns
|
||||
for match in pattern.finditer(text)
|
||||
]
|
||||
# Sort by start position (ascending), then by length (descending) to handle overlaps
|
||||
matches.sort(key=lambda x: (x[0], -x[1]))
|
||||
|
||||
res = []
|
||||
|
||||
def fold(initial: int, current: Tuple[int, int]) -> int:
|
||||
"""Accumulator function to filter overlapping matches."""
|
||||
# Only process if match starts after previous match ended
|
||||
if current[0] >= initial:
|
||||
# Only keep protected content if it fits within chunk size
|
||||
if current[1] - current[0] < self.chunk_size:
|
||||
res.append((current[0], text[current[0] : current[1]]))
|
||||
else:
|
||||
logger.warning(f"Protected text ignore: {current}")
|
||||
# Return the end position of the furthest match so far
|
||||
return max(initial, current[1])
|
||||
|
||||
# filter overlapping matches
|
||||
# Filter overlapping matches using accumulate
|
||||
list(itertools.accumulate(matches, fold, initial=-1))
|
||||
return res
|
||||
|
||||
def _join(self, splits: List[str], protect: List[Tuple[int, str]]) -> List[str]:
|
||||
"""
|
||||
"""Merge splits with protected content to ensure protected patterns remain intact.
|
||||
|
||||
Merges and splits elements in splits array based on protected substrings.
|
||||
|
||||
The function processes the input splits to ensure all protected substrings
|
||||
|
|
@ -243,45 +337,63 @@ class TextSplitter(BaseModel, Generic[T]):
|
|||
Key behaviors:
|
||||
1. Preserves the complete structure of each protected substring
|
||||
2. Separates protected substrings from any adjacent non-protected content
|
||||
3. Maintains the original sequence of all content except for necessary
|
||||
3. Maintains the original sequence of all content
|
||||
4. Handles cases where protected substrings are partially concatenated
|
||||
|
||||
Args:
|
||||
splits: List of text splits from _split()
|
||||
protect: List of (position, text) tuples for protected content
|
||||
|
||||
Returns:
|
||||
List of text splits with protected content properly isolated
|
||||
"""
|
||||
j = 0
|
||||
point, start = 0, 0
|
||||
res = []
|
||||
j = 0 # Index for protected content list
|
||||
point, start = 0, 0 # Track current position in original text
|
||||
res = [] # Result list of merged splits
|
||||
|
||||
for split in splits:
|
||||
# Calculate end position of current split
|
||||
end = start + len(split)
|
||||
|
||||
# Get the portion of split starting from current point
|
||||
cur = split[point - start :]
|
||||
|
||||
# Process all protected content that overlaps with current split
|
||||
while j < len(protect):
|
||||
p_start, p_content = protect[j]
|
||||
p_end = p_start + len(p_content)
|
||||
|
||||
# If protected content is beyond current split, move to next split
|
||||
if end <= p_start:
|
||||
break
|
||||
|
||||
# Add content before protected section
|
||||
if point < p_start:
|
||||
local_end = p_start - point
|
||||
res.append(cur[:local_end])
|
||||
cur = cur[local_end:]
|
||||
point = p_start
|
||||
|
||||
# Add the protected content as a single unit
|
||||
res.append(p_content)
|
||||
j += 1
|
||||
|
||||
# Skip content that's part of the protected section
|
||||
if point < p_end:
|
||||
local_start = p_end - point
|
||||
cur = cur[local_start:]
|
||||
point = p_end
|
||||
|
||||
# If no more content in current split, break
|
||||
if not cur:
|
||||
break
|
||||
|
||||
# Add any remaining content from current split
|
||||
if cur:
|
||||
res.append(cur)
|
||||
point = end
|
||||
|
||||
# Move to next split
|
||||
start = end
|
||||
return res
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,13 @@
|
|||
"""
|
||||
Encoding and Decoding Utilities Module
|
||||
|
||||
This module provides utilities for encoding and decoding various data types,
|
||||
with a focus on image and text data conversion:
|
||||
- Image encoding/decoding (base64)
|
||||
- Text encoding/decoding (multiple character sets)
|
||||
- Bytes conversion utilities
|
||||
"""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import io
|
||||
|
|
@ -11,31 +21,52 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
def decode_image(image: Union[str, bytes, Image.Image, np.ndarray]) -> str:
|
||||
"""Convert image to base64 encoded string
|
||||
"""Convert image to base64 encoded string.
|
||||
|
||||
This function handles multiple image input formats and converts them
|
||||
to a base64 encoded string representation, which is useful for embedding
|
||||
images in JSON, HTML, or other text-based formats.
|
||||
|
||||
Args:
|
||||
image: Image file path, bytes, PIL Image object, or numpy array
|
||||
image: Image in one of the following formats:
|
||||
- str: File path to an image file
|
||||
- bytes: Raw image bytes data
|
||||
- Image.Image: PIL/Pillow Image object
|
||||
- np.ndarray: NumPy array representing image data
|
||||
|
||||
Returns:
|
||||
Base64 encoded image string, or empty string if conversion fails
|
||||
str: Base64 encoded string representation of the image
|
||||
|
||||
Raises:
|
||||
ValueError: If the image type is not supported
|
||||
|
||||
Example:
|
||||
>>> # From file path
|
||||
>>> base64_str = decode_image("/path/to/image.png")
|
||||
>>> # From PIL Image
|
||||
>>> from PIL import Image
|
||||
>>> img = Image.open("photo.jpg")
|
||||
>>> base64_str = decode_image(img)
|
||||
"""
|
||||
if isinstance(image, str):
|
||||
# It's a file path
|
||||
# Handle file path: read file and encode to base64
|
||||
with open(image, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode()
|
||||
|
||||
elif isinstance(image, bytes):
|
||||
# It's bytes data
|
||||
# Handle raw bytes: directly encode to base64
|
||||
return base64.b64encode(image).decode()
|
||||
|
||||
elif isinstance(image, Image.Image):
|
||||
# It's a PIL Image
|
||||
# Handle PIL Image: save to buffer then encode
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format=image.format)
|
||||
# Use original format if available, otherwise default to PNG
|
||||
img_format = image.format if image.format else "PNG"
|
||||
image.save(buffer, format=img_format)
|
||||
return base64.b64encode(buffer.getvalue()).decode()
|
||||
|
||||
elif isinstance(image, np.ndarray):
|
||||
# It's a numpy array
|
||||
# Handle numpy array: convert to PIL Image, then encode as PNG
|
||||
pil_image = Image.fromarray(image)
|
||||
buffer = io.BytesIO()
|
||||
pil_image.save(buffer, format="PNG")
|
||||
|
|
@ -45,19 +76,35 @@ def decode_image(image: Union[str, bytes, Image.Image, np.ndarray]) -> str:
|
|||
|
||||
|
||||
def encode_image(image: str, errors="strict") -> bytes:
|
||||
"""
|
||||
Decode image bytes using base64.
|
||||
"""Decode a base64 encoded image string back to bytes.
|
||||
|
||||
errors
|
||||
The error handling scheme to use for the handling of decoding errors.
|
||||
The default is 'strict' meaning that decoding errors raise a
|
||||
UnicodeDecodeError. Other possible values are 'ignore' and '????'
|
||||
as well as any other name registered with codecs.register_error that
|
||||
can handle UnicodeDecodeErrors.
|
||||
This function converts a base64 encoded string representation of an image
|
||||
back into its original binary bytes format.
|
||||
|
||||
Args:
|
||||
image: Base64 encoded string representation of an image
|
||||
errors: Error handling scheme for decoding errors:
|
||||
- 'strict' (default): Raise binascii.Error on decoding errors
|
||||
- 'ignore': Return empty bytes on decoding errors
|
||||
- Any other name registered with codecs.register_error
|
||||
|
||||
Returns:
|
||||
bytes: Decoded image bytes, or empty bytes if errors='ignore' and decoding fails
|
||||
|
||||
Raises:
|
||||
binascii.Error: If decoding fails and errors='strict'
|
||||
|
||||
Example:
|
||||
>>> base64_str = "iVBORw0KGgoAAAANSUhEUgAAAAUA..."
|
||||
>>> image_bytes = encode_image(base64_str)
|
||||
>>> # With error handling
|
||||
>>> image_bytes = encode_image(base64_str, errors="ignore")
|
||||
"""
|
||||
try:
|
||||
# Attempt to decode the base64 string to bytes
|
||||
image_bytes = base64.b64decode(image)
|
||||
except binascii.Error as e:
|
||||
# Handle decoding errors based on the errors parameter
|
||||
if errors == "ignore":
|
||||
return b""
|
||||
else:
|
||||
|
|
@ -66,6 +113,20 @@ def encode_image(image: str, errors="strict") -> bytes:
|
|||
|
||||
|
||||
def encode_bytes(content: str) -> bytes:
|
||||
"""Convert a string to bytes using UTF-8 encoding.
|
||||
|
||||
Args:
|
||||
content: String to be encoded
|
||||
|
||||
Returns:
|
||||
bytes: UTF-8 encoded bytes representation of the string
|
||||
|
||||
Example:
|
||||
>>> text = "Hello, 世界"
|
||||
>>> encoded = encode_bytes(text)
|
||||
>>> type(encoded)
|
||||
<class 'bytes'>
|
||||
"""
|
||||
return content.encode()
|
||||
|
||||
|
||||
|
|
@ -81,15 +142,53 @@ def decode_bytes(
|
|||
"latin-1",
|
||||
],
|
||||
) -> str:
|
||||
# Try decoding with each encoding format
|
||||
"""Decode bytes to string with automatic encoding detection.
|
||||
|
||||
This function attempts to decode bytes using multiple encoding formats
|
||||
in order of priority. It's particularly useful for handling text files
|
||||
with unknown or mixed encodings, especially for Chinese text.
|
||||
|
||||
The function tries encodings in the provided order and returns the first
|
||||
successful decode. If all encodings fail, it falls back to latin-1 with
|
||||
error replacement to ensure a result is always returned.
|
||||
|
||||
Args:
|
||||
content: Bytes content to be decoded
|
||||
encodings: List of encoding formats to try, in order of priority.
|
||||
Default includes common encodings for Chinese and Western text:
|
||||
- utf-8: Universal encoding (tried first)
|
||||
- gb18030, gb2312, gbk: Chinese encodings (Simplified)
|
||||
- big5: Chinese encoding (Traditional)
|
||||
- ascii, latin-1: Western encodings
|
||||
|
||||
Returns:
|
||||
str: Decoded string content
|
||||
|
||||
Note:
|
||||
- If all encodings fail, latin-1 with error='replace' is used as fallback
|
||||
- The fallback may result in character replacement (<EFBFBD>) for invalid bytes
|
||||
- A warning is logged when fallback encoding is used
|
||||
|
||||
Example:
|
||||
>>> # Decode with default encodings
|
||||
>>> text = decode_bytes(b"\\xe4\\xb8\\xad\\xe6\\x96\\x87") # UTF-8 Chinese
|
||||
>>> print(text)
|
||||
中文
|
||||
>>> # Decode with custom encodings
|
||||
>>> text = decode_bytes(content, encodings=["utf-8", "gbk"])
|
||||
"""
|
||||
# Try decoding with each encoding format in order
|
||||
for encoding in encodings:
|
||||
try:
|
||||
text = content.decode(encoding)
|
||||
logger.debug(f"Decode content with {encoding}: {len(text)} characters")
|
||||
return text
|
||||
except UnicodeDecodeError:
|
||||
# This encoding didn't work, try the next one
|
||||
continue
|
||||
|
||||
# Fallback: use latin-1 with error replacement if all encodings fail
|
||||
# latin-1 can decode any byte sequence, but may produce incorrect characters
|
||||
text = content.decode(encoding="latin-1", errors="replace")
|
||||
logger.warning(
|
||||
"Unable to determine correct encoding, using latin-1 as fallback. "
|
||||
|
|
@ -99,5 +198,7 @@ def decode_bytes(
|
|||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example: Test encode_image with error handling
|
||||
# This demonstrates decoding a base64 string with 'ignore' error mode
|
||||
img = "testtest"
|
||||
encode_image(img, errors="ignore")
|
||||
|
|
|
|||
|
|
@ -3,14 +3,37 @@ from typing import Callable, List
|
|||
|
||||
|
||||
def split_text_keep_separator(text: str, separator: str) -> List[str]:
|
||||
"""Split text with separator and keep the separator at the end of each split."""
|
||||
"""Split text with separator and keep the separator at the end of each split.
|
||||
|
||||
Args:
|
||||
text: The input text to split
|
||||
separator: The separator string to split by
|
||||
|
||||
Returns:
|
||||
List of text chunks with separator preserved at the start of each chunk (except first)
|
||||
|
||||
Example:
|
||||
>>> split_text_keep_separator("Hello\nWorld\nTest", "\n")
|
||||
["Hello", "\nWorld", "\nTest"]
|
||||
"""
|
||||
# Split text by separator
|
||||
parts = text.split(separator)
|
||||
# Add separator back to the beginning of each part (except the first one)
|
||||
result = [separator + s if i > 0 else s for i, s in enumerate(parts)]
|
||||
# Filter out empty strings
|
||||
return [s for s in result if s]
|
||||
|
||||
|
||||
def split_by_sep(sep: str, keep_sep: bool = True) -> Callable[[str], List[str]]:
|
||||
"""Split text by separator."""
|
||||
"""Create a function that splits text by a given separator.
|
||||
|
||||
Args:
|
||||
sep: The separator string to split by
|
||||
keep_sep: If True, keep the separator in the result; if False, discard it
|
||||
|
||||
Returns:
|
||||
A callable function that takes text and returns a list of split strings
|
||||
"""
|
||||
if keep_sep:
|
||||
return lambda text: split_text_keep_separator(text, sep)
|
||||
else:
|
||||
|
|
@ -18,17 +41,40 @@ def split_by_sep(sep: str, keep_sep: bool = True) -> Callable[[str], List[str]]:
|
|||
|
||||
|
||||
def split_by_char() -> Callable[[str], List[str]]:
|
||||
"""Split text by character."""
|
||||
"""Create a function that splits text into individual characters.
|
||||
|
||||
Returns:
|
||||
A callable function that takes text and returns a list of characters
|
||||
"""
|
||||
return lambda text: list(text)
|
||||
|
||||
|
||||
def split_by_regex(regex: str) -> Callable[[str], List[str]]:
|
||||
"""Split text by regex."""
|
||||
"""Create a function that splits text by a regex pattern.
|
||||
|
||||
Args:
|
||||
regex: The regular expression pattern to split by
|
||||
|
||||
Returns:
|
||||
A callable function that takes text and returns a list of split strings
|
||||
The regex pattern is captured, so the separators are included in the result
|
||||
"""
|
||||
# Compile regex with capturing group to keep separators in result
|
||||
pattern = re.compile(f"({regex})")
|
||||
# Split by pattern and filter out None/empty values
|
||||
return lambda text: list(filter(None, pattern.split(text)))
|
||||
|
||||
|
||||
def match_by_regex(regex: str) -> Callable[[str], bool]:
|
||||
"""Split text by regex."""
|
||||
"""Create a function that checks if text matches a regex pattern.
|
||||
|
||||
Args:
|
||||
regex: The regular expression pattern to match against
|
||||
|
||||
Returns:
|
||||
A callable function that takes text and returns True if it matches the pattern
|
||||
"""
|
||||
# Compile the regex pattern for efficient reuse
|
||||
pattern = re.compile(regex)
|
||||
# Return a function that checks if text matches the pattern from the start
|
||||
return lambda text: bool(pattern.match(text))
|
||||
|
|
|
|||
598
docs/API.md
|
|
@ -13,6 +13,8 @@
|
|||
- [知识管理 API](#知识管理api)
|
||||
- [模型管理 API](#模型管理api)
|
||||
- [分块管理 API](#分块管理api)
|
||||
- [标签管理 API](#标签管理api)
|
||||
- [FAQ管理 API](#faq管理api)
|
||||
- [会话管理 API](#会话管理api)
|
||||
- [聊天功能 API](#聊天功能api)
|
||||
- [消息管理 API](#消息管理api)
|
||||
|
|
@ -72,10 +74,12 @@ WeKnora API 按功能分为以下几类:
|
|||
3. **知识管理**:上传、检索和管理知识内容
|
||||
4. **模型管理**:配置和管理各种AI模型
|
||||
5. **分块管理**:管理知识的分块内容
|
||||
6. **会话管理**:创建和管理对话会话
|
||||
7. **聊天功能**:基于知识库进行问答
|
||||
8. **消息管理**:获取和管理对话消息
|
||||
9. **评估功能**:评估模型性能
|
||||
6. **标签管理**:管理知识库的标签分类
|
||||
7. **FAQ管理**:管理FAQ问答对
|
||||
8. **会话管理**:创建和管理对话会话
|
||||
9. **聊天功能**:基于知识库进行问答
|
||||
10. **消息管理**:获取和管理对话消息
|
||||
11. **评估功能**:评估模型性能
|
||||
|
||||
## API 详细说明
|
||||
|
||||
|
|
@ -335,6 +339,7 @@ curl --location 'http://localhost:8080/api/v1/tenants' \
|
|||
| PUT | `/knowledge-bases/:id` | 更新知识库 |
|
||||
| DELETE | `/knowledge-bases/:id` | 删除知识库 |
|
||||
| POST | `/knowledge-bases/copy` | 拷贝知识库 |
|
||||
| GET | `/knowledge-bases/:id/hybrid-search` | 混合搜索(向量+关键词) |
|
||||
|
||||
#### POST `/knowledge-bases` - 创建知识库
|
||||
|
||||
|
|
@ -361,12 +366,9 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
|
|||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e",
|
||||
"vlm_config": {
|
||||
"model_name": "qwen2.5vl:3b",
|
||||
"interface_type": "ollama",
|
||||
"base_url": "",
|
||||
"api_key": ""
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
|
|
@ -402,12 +404,9 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
|
|||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e",
|
||||
"vlm_config": {
|
||||
"model_name": "qwen2.5vl:3b",
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"interface_type": "ollama"
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
|
|
@ -465,12 +464,9 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
|
|||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e",
|
||||
"vlm_config": {
|
||||
"model_name": "qwen2.5vl:3b",
|
||||
"base_url": "http://host.docker.internal:11435/v1",
|
||||
"api_key": "",
|
||||
"interface_type": "ollama"
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
|
|
@ -528,12 +524,9 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001' \
|
|||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e",
|
||||
"vlm_config": {
|
||||
"model_name": "qwen2.5vl:3b",
|
||||
"base_url": "http://host.docker.internal:11435/v1",
|
||||
"api_key": "",
|
||||
"interface_type": "ollama"
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
|
|
@ -613,12 +606,9 @@ curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/b582
|
|||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e",
|
||||
"vlm_config": {
|
||||
"model_name": "qwen2.5vl:3b",
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"interface_type": "ollama"
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
|
|
@ -655,6 +645,59 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/b
|
|||
}
|
||||
```
|
||||
|
||||
#### GET `/knowledge-bases/:id/hybrid-search` - 混合搜索
|
||||
|
||||
执行向量搜索和关键词搜索的混合检索。
|
||||
|
||||
**注意**:此接口使用 GET 方法但需要 JSON 请求体。
|
||||
|
||||
**请求参数**:
|
||||
- `query_text`: 搜索查询文本(必填)
|
||||
- `vector_threshold`: 向量相似度阈值(0-1,可选)
|
||||
- `keyword_threshold`: 关键词匹配阈值(可选)
|
||||
- `match_count`: 返回结果数量(可选)
|
||||
- `disable_keywords_match`: 是否禁用关键词匹配(可选)
|
||||
- `disable_vector_match`: 是否禁用向量匹配(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request GET 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/hybrid-search' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query_text": "如何使用知识库",
|
||||
"vector_threshold": 0.5,
|
||||
"match_count": 10
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "chunk-00000001",
|
||||
"content": "知识库是用于存储和检索知识的系统...",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"chunk_index": 0,
|
||||
"knowledge_title": "知识库使用指南",
|
||||
"start_at": 0,
|
||||
"end_at": 500,
|
||||
"seq": 1,
|
||||
"score": 0.95,
|
||||
"chunk_type": "text",
|
||||
"image_info": "",
|
||||
"metadata": {},
|
||||
"knowledge_filename": "guide.pdf",
|
||||
"knowledge_source": "file"
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
<div align="right"><a href="#weknora-api-文档">返回顶部 ↑</a></div>
|
||||
|
||||
### 知识管理API
|
||||
|
|
@ -663,16 +706,25 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/b
|
|||
| ------ | ------------------------------------- | ------------------------ |
|
||||
| POST | `/knowledge-bases/:id/knowledge/file` | 从文件创建知识 |
|
||||
| POST | `/knowledge-bases/:id/knowledge/url` | 从 URL 创建知识 |
|
||||
| POST | `/knowledge-bases/:id/knowledge/manual` | 创建手工 Markdown 知识 |
|
||||
| GET | `/knowledge-bases/:id/knowledge` | 获取知识库下的知识列表 |
|
||||
| GET | `/knowledge/:id` | 获取知识详情 |
|
||||
| DELETE | `/knowledge/:id` | 删除知识 |
|
||||
| GET | `/knowledge/:id/download` | 下载知识文件 |
|
||||
| PUT | `/knowledge/:id` | 更新知识 |
|
||||
| PUT | `/knowledge/manual/:id` | 更新手工 Markdown 知识 |
|
||||
| PUT | `/knowledge/image/:id/:chunk_id` | 更新图像分块信息 |
|
||||
| PUT | `/knowledge/tags` | 批量更新知识标签 |
|
||||
| GET | `/knowledge/batch` | 批量获取知识 |
|
||||
|
||||
#### POST `/knowledge-bases/:id/knowledge/file` - 从文件创建知识
|
||||
|
||||
**表单参数**:
|
||||
- `file`: 上传的文件(必填)
|
||||
- `metadata`: JSON 格式的元数据(可选)
|
||||
- `enable_multimodel`: 是否启用多模态处理(可选,true/false)
|
||||
- `fileName`: 自定义文件名,用于文件夹上传时保留路径(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
|
|
@ -761,12 +813,17 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowle
|
|||
}
|
||||
```
|
||||
|
||||
#### GET `/knowledge-bases/:id/knowledge?page=&page_size` - 获取知识库下的知识列表
|
||||
#### GET `/knowledge-bases/:id/knowledge` - 获取知识库下的知识列表
|
||||
|
||||
**查询参数**:
|
||||
- `page`: 页码(默认 1)
|
||||
- `page_size`: 每页条数(默认 20)
|
||||
- `tag_id`: 按标签ID筛选(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowledge?page_size=1&page=1' \
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowledge?page_size=1&page=1&tag_id=tag-00000001' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
|
@ -1254,12 +1311,14 @@ curl --location 'http://localhost:8080/api/v1/chunks/4c4e7c1a-09cf-485b-a7b5-24b
|
|||
"data": [
|
||||
{
|
||||
"id": "df10b37d-cd05-4b14-ba8a-e1bd0eb3bbd7",
|
||||
"tenant_id": 0,
|
||||
"tenant_id": 1,
|
||||
"knowledge_id": "4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "",
|
||||
"content": "彗星xxxx",
|
||||
"chunk_index": 0,
|
||||
"is_enabled": true,
|
||||
"status": 2,
|
||||
"start_at": 0,
|
||||
"end_at": 964,
|
||||
"pre_chunk_id": "",
|
||||
|
|
@ -1268,9 +1327,11 @@ curl --location 'http://localhost:8080/api/v1/chunks/4c4e7c1a-09cf-485b-a7b5-24b
|
|||
"parent_chunk_id": "",
|
||||
"relation_chunks": null,
|
||||
"indirect_relation_chunks": null,
|
||||
"metadata": null,
|
||||
"content_hash": "",
|
||||
"image_info": "",
|
||||
"created_at": "0001-01-01T00:00:00Z",
|
||||
"updated_at": "0001-01-01T00:00:00Z",
|
||||
"created_at": "2025-08-12T11:52:36.168632+08:00",
|
||||
"updated_at": "2025-08-12T11:52:53.376871+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
|
|
@ -1321,6 +1382,468 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/chunks/4c4e7c1a-0
|
|||
|
||||
<div align="right"><a href="#weknora-api-文档">返回顶部 ↑</a></div>
|
||||
|
||||
### 标签管理API
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ------------------------------------- | ------------------------ |
|
||||
| GET | `/knowledge-bases/:id/tags` | 获取知识库标签列表 |
|
||||
| POST | `/knowledge-bases/:id/tags` | 创建标签 |
|
||||
| PUT | `/knowledge-bases/:id/tags/:tag_id` | 更新标签 |
|
||||
| DELETE | `/knowledge-bases/:id/tags/:tag_id` | 删除标签 |
|
||||
|
||||
#### GET `/knowledge-bases/:id/tags` - 获取知识库标签列表
|
||||
|
||||
**查询参数**:
|
||||
- `page`: 页码(默认 1)
|
||||
- `page_size`: 每页条数(默认 20)
|
||||
- `keyword`: 标签名称关键字搜索(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags?page=1&page_size=10' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"total": 2,
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"data": [
|
||||
{
|
||||
"id": "tag-00000001",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "技术文档",
|
||||
"color": "#1890ff",
|
||||
"sort_order": 1,
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00",
|
||||
"knowledge_count": 5,
|
||||
"chunk_count": 120
|
||||
},
|
||||
{
|
||||
"id": "tag-00000002",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "常见问题",
|
||||
"color": "#52c41a",
|
||||
"sort_order": 2,
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00",
|
||||
"knowledge_count": 3,
|
||||
"chunk_count": 45
|
||||
}
|
||||
]
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### POST `/knowledge-bases/:id/tags` - 创建标签
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"name": "产品手册",
|
||||
"color": "#faad14",
|
||||
"sort_order": 3
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "tag-00000003",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "产品手册",
|
||||
"color": "#faad14",
|
||||
"sort_order": 3,
|
||||
"created_at": "2025-08-12T11:00:00+08:00",
|
||||
"updated_at": "2025-08-12T11:00:00+08:00"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### PUT `/knowledge-bases/:id/tags/:tag_id` - 更新标签
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags/tag-00000003' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"name": "产品手册更新",
|
||||
"color": "#ff4d4f"
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "tag-00000003",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "产品手册更新",
|
||||
"color": "#ff4d4f",
|
||||
"sort_order": 3,
|
||||
"created_at": "2025-08-12T11:00:00+08:00",
|
||||
"updated_at": "2025-08-12T11:30:00+08:00"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### DELETE `/knowledge-bases/:id/tags/:tag_id` - 删除标签
|
||||
|
||||
**查询参数**:
|
||||
- `force`: 设置为 `true` 时强制删除(即使标签被引用)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags/tag-00000003?force=true' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
<div align="right"><a href="#weknora-api-文档">返回顶部 ↑</a></div>
|
||||
|
||||
### FAQ管理API
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ------------------------------------------- | ------------------------ |
|
||||
| GET | `/knowledge-bases/:id/faq/entries` | 获取FAQ条目列表 |
|
||||
| POST | `/knowledge-bases/:id/faq/entries` | 批量导入FAQ条目 |
|
||||
| POST | `/knowledge-bases/:id/faq/entry` | 创建单个FAQ条目 |
|
||||
| PUT | `/knowledge-bases/:id/faq/entries/:entry_id`| 更新单个FAQ条目 |
|
||||
| PUT | `/knowledge-bases/:id/faq/entries/status` | 批量更新FAQ启用状态 |
|
||||
| PUT | `/knowledge-bases/:id/faq/entries/tags` | 批量更新FAQ标签 |
|
||||
| DELETE | `/knowledge-bases/:id/faq/entries` | 批量删除FAQ条目 |
|
||||
| POST | `/knowledge-bases/:id/faq/search` | 混合搜索FAQ |
|
||||
|
||||
#### GET `/knowledge-bases/:id/faq/entries` - 获取FAQ条目列表
|
||||
|
||||
**查询参数**:
|
||||
- `page`: 页码(默认 1)
|
||||
- `page_size`: 每页条数(默认 20)
|
||||
- `tag_id`: 按标签ID筛选(可选)
|
||||
- `keyword`: 关键字搜索(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries?page=1&page_size=10' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"total": 100,
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"data": [
|
||||
{
|
||||
"id": "faq-00000001",
|
||||
"chunk_id": "chunk-00000001",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true,
|
||||
"standard_question": "如何重置密码?",
|
||||
"similar_questions": ["忘记密码怎么办", "密码找回"],
|
||||
"negative_questions": ["如何修改用户名"],
|
||||
"answers": ["您可以通过点击登录页面的'忘记密码'链接来重置密码。"],
|
||||
"index_mode": "hybrid",
|
||||
"chunk_type": "faq",
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### POST `/knowledge-bases/:id/faq/entries` - 批量导入FAQ条目
|
||||
|
||||
**请求参数**:
|
||||
- `mode`: 导入模式,`append`(追加)或 `replace`(替换)
|
||||
- `entries`: FAQ条目数组
|
||||
- `knowledge_id`: 关联的知识ID(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"mode": "append",
|
||||
"entries": [
|
||||
{
|
||||
"standard_question": "如何联系客服?",
|
||||
"similar_questions": ["客服电话", "在线客服"],
|
||||
"answers": ["您可以通过拨打400-xxx-xxxx联系我们的客服。"],
|
||||
"tag_id": "tag-00000001"
|
||||
},
|
||||
{
|
||||
"standard_question": "退款政策是什么?",
|
||||
"answers": ["我们提供7天无理由退款服务。"]
|
||||
}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"task_id": "task-00000001"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
注:批量导入为异步操作,返回任务ID用于追踪进度。
|
||||
|
||||
#### POST `/knowledge-bases/:id/faq/entry` - 创建单个FAQ条目
|
||||
|
||||
同步创建单个FAQ条目,适用于单条录入场景。会自动检查标准问和相似问是否与已有FAQ重复。
|
||||
|
||||
**请求参数**:
|
||||
- `standard_question`: 标准问(必填)
|
||||
- `similar_questions`: 相似问数组(可选)
|
||||
- `negative_questions`: 反例问题数组(可选)
|
||||
- `answers`: 答案数组(必填)
|
||||
- `tag_id`: 标签ID(可选)
|
||||
- `is_enabled`: 是否启用(可选,默认true)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entry' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"standard_question": "如何联系客服?",
|
||||
"similar_questions": ["客服电话", "在线客服"],
|
||||
"answers": ["您可以通过拨打400-xxx-xxxx联系我们的客服。"],
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "faq-00000001",
|
||||
"chunk_id": "chunk-00000001",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true,
|
||||
"standard_question": "如何联系客服?",
|
||||
"similar_questions": ["客服电话", "在线客服"],
|
||||
"negative_questions": [],
|
||||
"answers": ["您可以通过拨打400-xxx-xxxx联系我们的客服。"],
|
||||
"index_mode": "hybrid",
|
||||
"chunk_type": "faq",
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
**错误响应**(标准问或相似问重复时):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "BAD_REQUEST",
|
||||
"message": "标准问与已有FAQ重复"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### PUT `/knowledge-bases/:id/faq/entries/:entry_id` - 更新单个FAQ条目
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries/faq-00000001' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"standard_question": "如何重置账户密码?",
|
||||
"similar_questions": ["忘记密码怎么办", "密码找回", "重置密码"],
|
||||
"answers": ["您可以通过以下步骤重置密码:1. 点击登录页面的"忘记密码" 2. 输入注册邮箱 3. 查收重置邮件"],
|
||||
"is_enabled": true
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### PUT `/knowledge-bases/:id/faq/entries/status` - 批量更新FAQ启用状态
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries/status' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"updates": {
|
||||
"faq-00000001": true,
|
||||
"faq-00000002": false,
|
||||
"faq-00000003": true
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### PUT `/knowledge-bases/:id/faq/entries/tags` - 批量更新FAQ标签
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries/tags' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"updates": {
|
||||
"faq-00000001": "tag-00000001",
|
||||
"faq-00000002": "tag-00000002",
|
||||
"faq-00000003": null
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
注:设置为 `null` 可清除标签关联。
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### DELETE `/knowledge-bases/:id/faq/entries` - 批量删除FAQ条目
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"ids": ["faq-00000001", "faq-00000002"]
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
#### POST `/knowledge-bases/:id/faq/search` - 混合搜索FAQ
|
||||
|
||||
**请求参数**:
|
||||
- `query_text`: 搜索查询文本
|
||||
- `vector_threshold`: 向量相似度阈值(0-1)
|
||||
- `match_count`: 返回结果数量(最大200)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/search' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query_text": "如何重置密码",
|
||||
"vector_threshold": 0.5,
|
||||
"match_count": 10
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "faq-00000001",
|
||||
"chunk_id": "chunk-00000001",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true,
|
||||
"standard_question": "如何重置密码?",
|
||||
"similar_questions": ["忘记密码怎么办", "密码找回"],
|
||||
"answers": ["您可以通过点击登录页面的'忘记密码'链接来重置密码。"],
|
||||
"chunk_type": "faq",
|
||||
"score": 0.95,
|
||||
"match_type": "vector",
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00"
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
<div align="right"><a href="#weknora-api-文档">返回顶部 ↑</a></div>
|
||||
|
||||
### 会话管理API
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
|
|
@ -1409,6 +1932,8 @@ curl --location 'http://localhost:8080/api/v1/sessions' \
|
|||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"agent_config": null,
|
||||
"context_config": null,
|
||||
"created_at": "2025-08-12T12:26:19.611616669+08:00",
|
||||
"updated_at": "2025-08-12T12:26:19.611616919+08:00",
|
||||
"deleted_at": null
|
||||
|
|
@ -1462,6 +1987,8 @@ curl --location 'http://localhost:8080/api/v1/sessions/ceb9babb-1e30-41d7-817d-f
|
|||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"agent_config": null,
|
||||
"context_config": null,
|
||||
"created_at": "2025-08-12T10:24:38.308596+08:00",
|
||||
"updated_at": "2025-08-12T10:25:41.317761+08:00",
|
||||
"deleted_at": null
|
||||
|
|
@ -1803,6 +2330,7 @@ curl --location --request GET 'http://localhost:8080/api/v1/messages/ceb9babb-1e
|
|||
"knowledge_source": ""
|
||||
}
|
||||
],
|
||||
"agent_steps": [],
|
||||
"is_completed": true,
|
||||
"created_at": "2025-08-12T10:24:38.370548+08:00",
|
||||
"updated_at": "2025-08-12T10:25:40.416382+08:00",
|
||||
|
|
@ -1815,6 +2343,7 @@ curl --location --request GET 'http://localhost:8080/api/v1/messages/ceb9babb-1e
|
|||
"content": "彗尾的形状",
|
||||
"role": "user",
|
||||
"knowledge_references": [],
|
||||
"agent_steps": [],
|
||||
"is_completed": true,
|
||||
"created_at": "2025-08-12T14:30:39.732246+08:00",
|
||||
"updated_at": "2025-08-12T14:30:39.733277+08:00",
|
||||
|
|
@ -1870,6 +2399,7 @@ curl --location --request GET 'http://localhost:8080/api/v1/messages/ceb9babb-1e
|
|||
"knowledge_source": ""
|
||||
}
|
||||
],
|
||||
"agent_steps": [],
|
||||
"is_completed": true,
|
||||
"created_at": "2025-08-12T14:30:39.735108+08:00",
|
||||
"updated_at": "2025-08-12T14:31:17.829926+08:00",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,173 @@
|
|||
# 内置模型管理指南
|
||||
|
||||
## 概述
|
||||
|
||||
内置模型是系统级别的模型配置,对所有租户可见,但敏感信息会被隐藏,且不可编辑或删除。内置模型通常用于提供系统默认的模型配置,确保所有租户都能使用统一的模型服务。
|
||||
|
||||
## 内置模型特性
|
||||
|
||||
- **所有租户可见**:内置模型对所有租户都可见,无需单独配置
|
||||
- **安全保护**:内置模型的敏感信息(API Key、Base URL)会被隐藏,无法查看详情
|
||||
- **只读保护**:内置模型不能被编辑或删除,只能设置为默认模型
|
||||
- **统一管理**:由系统管理员统一维护,确保配置一致性和安全性
|
||||
|
||||
## 如何添加内置模型
|
||||
|
||||
内置模型需要通过数据库直接插入。以下是添加内置模型的步骤:
|
||||
|
||||
### 1. 准备模型数据
|
||||
|
||||
首先,确保你已经有了要设置为内置模型的模型配置信息,包括:
|
||||
- 模型名称(name)
|
||||
- 模型类型(type):`KnowledgeQA`、`Embedding`、`Rerank` 或 `VLLM`
|
||||
- 模型来源(source):`local` 或 `remote`
|
||||
- 模型参数(parameters):包括 base_url、api_key 等
|
||||
- 租户ID(tenant_id):建议使用小于10000的租户ID,避免冲突
|
||||
|
||||
### 2. 执行 SQL 插入语句
|
||||
|
||||
使用以下 SQL 语句插入内置模型:
|
||||
|
||||
```sql
|
||||
-- 示例:插入一个 LLM 内置模型
|
||||
INSERT INTO models (
|
||||
id,
|
||||
tenant_id,
|
||||
name,
|
||||
type,
|
||||
source,
|
||||
description,
|
||||
parameters,
|
||||
is_default,
|
||||
status,
|
||||
is_builtin
|
||||
) VALUES (
|
||||
'builtin-llm-001', -- 使用固定ID,建议使用 builtin- 前缀
|
||||
10000, -- 租户ID(使用第一个租户)
|
||||
'GPT-4', -- 模型名称
|
||||
'KnowledgeQA', -- 模型类型
|
||||
'remote', -- 模型来源
|
||||
'内置 LLM 模型', -- 描述
|
||||
'{"base_url": "https://api.openai.com/v1", "api_key": "sk-xxx"}'::jsonb, -- 参数(JSON格式)
|
||||
false, -- 是否默认
|
||||
'active', -- 状态
|
||||
true -- 标记为内置模型
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- 示例:插入一个 Embedding 内置模型
|
||||
INSERT INTO models (
|
||||
id,
|
||||
tenant_id,
|
||||
name,
|
||||
type,
|
||||
source,
|
||||
description,
|
||||
parameters,
|
||||
is_default,
|
||||
status,
|
||||
is_builtin
|
||||
) VALUES (
|
||||
'builtin-embedding-001',
|
||||
10000,
|
||||
'text-embedding-ada-002',
|
||||
'Embedding',
|
||||
'remote',
|
||||
'内置 Embedding 模型',
|
||||
'{"base_url": "https://api.openai.com/v1", "api_key": "sk-xxx", "embedding_parameters": {"dimension": 1536, "truncate_prompt_tokens": 0}}'::jsonb,
|
||||
false,
|
||||
'active',
|
||||
true
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- 示例:插入一个 ReRank 内置模型
|
||||
INSERT INTO models (
|
||||
id,
|
||||
tenant_id,
|
||||
name,
|
||||
type,
|
||||
source,
|
||||
description,
|
||||
parameters,
|
||||
is_default,
|
||||
status,
|
||||
is_builtin
|
||||
) VALUES (
|
||||
'builtin-rerank-001',
|
||||
10000,
|
||||
'bge-reranker-base',
|
||||
'Rerank',
|
||||
'remote',
|
||||
'内置 ReRank 模型',
|
||||
'{"base_url": "https://api.example.com/v1", "api_key": "xxx"}'::jsonb,
|
||||
false,
|
||||
'active',
|
||||
true
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- 示例:插入一个 VLLM 内置模型
|
||||
INSERT INTO models (
|
||||
id,
|
||||
tenant_id,
|
||||
name,
|
||||
type,
|
||||
source,
|
||||
description,
|
||||
parameters,
|
||||
is_default,
|
||||
status,
|
||||
is_builtin
|
||||
) VALUES (
|
||||
'builtin-vllm-001',
|
||||
10000,
|
||||
'gpt-4-vision',
|
||||
'VLLM',
|
||||
'remote',
|
||||
'内置 VLLM 模型',
|
||||
'{"base_url": "https://api.openai.com/v1", "api_key": "sk-xxx"}'::jsonb,
|
||||
false,
|
||||
'active',
|
||||
true
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
```
|
||||
|
||||
### 3. 验证插入结果
|
||||
|
||||
执行以下 SQL 查询验证内置模型是否成功插入:
|
||||
|
||||
```sql
|
||||
SELECT id, name, type, is_builtin, status
|
||||
FROM models
|
||||
WHERE is_builtin = true
|
||||
ORDER BY type, created_at;
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **ID 命名规范**:建议使用 `builtin-{type}-{序号}` 的格式,例如 `builtin-llm-001`、`builtin-embedding-001`
|
||||
2. **租户ID**:内置模型可以属于任意租户,但建议使用第一个租户ID(通常是 10000)
|
||||
3. **参数格式**:`parameters` 字段必须是有效的 JSON 格式
|
||||
4. **幂等性**:使用 `ON CONFLICT (id) DO NOTHING` 确保重复执行不会报错
|
||||
5. **安全性**:内置模型的 API Key 和 Base URL 在前端会被自动隐藏,但数据库中的原始数据仍然存在,请妥善保管数据库访问权限
|
||||
|
||||
## 将现有模型设置为内置模型
|
||||
|
||||
如果你已经有一个模型,想将其设置为内置模型,可以使用 UPDATE 语句:
|
||||
|
||||
```sql
|
||||
UPDATE models
|
||||
SET is_builtin = true
|
||||
WHERE id = '模型ID' AND name = '模型名称';
|
||||
```
|
||||
|
||||
## 移除内置模型
|
||||
|
||||
如果需要移除内置模型标记(恢复为普通模型),执行:
|
||||
|
||||
```sql
|
||||
UPDATE models
|
||||
SET is_builtin = false
|
||||
WHERE id = '模型ID';
|
||||
```
|
||||
|
||||
注意:移除内置模型标记后,该模型将恢复为普通模型,可以被编辑和删除。
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
## MCP 功能使用说明
|
||||
|
||||
### 功能概述
|
||||
- MCP(Model Context Protocol)让 WeKnora 可以安全地连接外部工具或数据源,扩展 Agent 在推理时可调用的能力。
|
||||
- 在前端 `设置 > MCP 服务`(`frontend/src/views/settings/McpSettings.vue`)中集中管理所有服务,无需手动改配置文件。
|
||||
- 每个服务都包含名称、传输方式(SSE / HTTP Streamable / Stdio)、连接地址或命令、认证信息以及高级超时与重试策略。
|
||||
|
||||
### 入口与界面
|
||||
- 打开控制台左侧菜单 `设置 -> MCP 服务`,即可看到当前租户下的所有 MCP 服务列表。
|
||||
- 列表中可快速启停服务、查看描述,并通过右侧菜单执行“测试 / 编辑 / 删除”。
|
||||
- “添加服务”按钮会弹出 `McpServiceDialog`,用于创建或修改服务。
|
||||
|
||||
### 常用操作流程
|
||||
1. **新建服务**
|
||||
- 点击“添加服务”,填写名称与描述,选择传输方式。
|
||||
- SSE / HTTP Streamable 需提供可访问的服务 URL;Stdio 需配置 `uvx`/`npx` 命令与参数,可附加环境变量。
|
||||
- 根据需要填写 API Key、Bearer Token、超时与重试策略,保存后服务会出现在列表中。
|
||||
2. **启停服务**
|
||||
- 在列表开关中切换启用状态,系统会即时调用后端 `updateMCPService`,失败时会自动回滚状态并弹出提示。
|
||||
3. **连接测试**
|
||||
- 通过更多菜单选择“测试”,前端会调用 `/api/v1/mcp-services/{id}/test` 并弹出 `McpTestResult`。
|
||||
- 成功时会展示服务可用的工具清单(含输入 schema)和资源列表;失败时会显示错误信息,方便排查网络或鉴权问题。
|
||||
4. **编辑 / 删除**
|
||||
- “编辑”会带出原有配置,修改后保存即可。
|
||||
- “删除”需要在弹窗中确认,完成后列表自动刷新。
|
||||
|
||||
### 使用建议
|
||||
- **传输方式选择**:优先使用 SSE 获取流式体验;需要标准 HTTP Streamable 兼容时再切换;本地调试或离线环境适合使用 Stdio 并在同机启动 MCP Server。
|
||||
- **鉴权管理**:将 API Key / Token 保存在“认证配置”中,生产环境建议单独创建最小权限 Key,并定期轮换。
|
||||
- **重试策略**:对公网或第三方服务适当提高 `retry_count` 与 `retry_delay`,避免间歇性超时导致 Agent 中断
|
||||
|
|
@ -305,6 +305,17 @@ Reranker(重排器)是目前RAG领域中非常先进的技术,它们在工
|
|||
未知情况处理: 如果文档中没有足够的信息来回答问题,请告知“根据所掌握的资料,无法回答这个问题”
|
||||
引用要求:在回答时,如果引用了某个文档内容,请在句子末尾加上文档编号
|
||||
|
||||
---
|
||||
|
||||
## 手工知识在线编辑
|
||||
|
||||
平台的知识库页面新增“上传文档 / 在线编辑”双入口,支持直接在浏览器中撰写并维护 Markdown 知识:
|
||||
|
||||
- 草稿模式用于暂存内容,草稿不会参与检索。
|
||||
- 发布操作会自动触发向量化与索引构建。
|
||||
- 已发布的 Markdown 知识可再次打开编辑并重新发布。
|
||||
- 在对话页面的助手回答末尾提供“添加到知识库”工具,可一键带入当前问答到编辑器中确认后保存。
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
# WeKnora API 文档
|
||||
|
||||
## 目录
|
||||
|
||||
- [概述](#概述)
|
||||
- [基础信息](#基础信息)
|
||||
- [认证机制](#认证机制)
|
||||
- [错误处理](#错误处理)
|
||||
- [API 概览](#api-概览)
|
||||
|
||||
## 概述
|
||||
|
||||
WeKnora 提供了一系列 RESTful API,用于创建和管理知识库、检索知识,以及进行基于知识的问答。本文档详细描述了这些 API 的使用方式。
|
||||
|
||||
## 基础信息
|
||||
|
||||
- **基础 URL**: `/api/v1`
|
||||
- **响应格式**: JSON
|
||||
- **认证方式**: API Key
|
||||
|
||||
## 认证机制
|
||||
|
||||
所有 API 请求需要在 HTTP 请求头中包含 `X-API-Key` 进行身份认证:
|
||||
|
||||
```
|
||||
X-API-Key: your_api_key
|
||||
```
|
||||
|
||||
为便于问题追踪和调试,建议每个请求的 HTTP 请求头中添加 `X-Request-ID`:
|
||||
|
||||
```
|
||||
X-Request-ID: unique_request_id
|
||||
```
|
||||
|
||||
### 获取 API Key
|
||||
|
||||
在 web 页面完成账户注册后,请前往账户信息页面获取您的 API Key。
|
||||
|
||||
请妥善保管您的 API Key,避免泄露。API Key 代表您的账户身份,拥有完整的 API 访问权限。
|
||||
|
||||
## 错误处理
|
||||
|
||||
所有 API 使用标准的 HTTP 状态码表示请求状态,并返回统一的错误响应格式:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "错误代码",
|
||||
"message": "错误信息",
|
||||
"details": "错误详情"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API 概览
|
||||
|
||||
WeKnora API 按功能分为以下几类:
|
||||
|
||||
| 分类 | 描述 | 文档链接 |
|
||||
|------|------|----------|
|
||||
| 租户管理 | 创建和管理租户账户 | [tenant.md](./tenant.md) |
|
||||
| 知识库管理 | 创建、查询和管理知识库 | [knowledge-base.md](./knowledge-base.md) |
|
||||
| 知识管理 | 上传、检索和管理知识内容 | [knowledge.md](./knowledge.md) |
|
||||
| 模型管理 | 配置和管理各种AI模型 | [model.md](./model.md) |
|
||||
| 分块管理 | 管理知识的分块内容 | [chunk.md](./chunk.md) |
|
||||
| 标签管理 | 管理知识库的标签分类 | [tag.md](./tag.md) |
|
||||
| FAQ管理 | 管理FAQ问答对 | [faq.md](./faq.md) |
|
||||
| 会话管理 | 创建和管理对话会话 | [session.md](./session.md) |
|
||||
| 聊天功能 | 基于知识库和 Agent 进行问答 | [chat.md](./chat.md) |
|
||||
| 消息管理 | 获取和管理对话消息 | [message.md](./message.md) |
|
||||
| 评估功能 | 评估模型性能 | [evaluation.md](./evaluation.md) |
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
# 聊天功能 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ---- | ----------------------------- | ------------------------ |
|
||||
| POST | `/knowledge-chat/:session_id` | 基于知识库的问答 |
|
||||
| POST | `/agent-chat/:session_id` | 基于 Agent 的智能问答 |
|
||||
| POST | `/knowledge-search` | 基于知识库的搜索知识 |
|
||||
|
||||
## POST `/knowledge-chat/:session_id` - 基于知识库的问答
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-chat/ceb9babb-1e30-41d7-817d-fd584954304b' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query": "彗尾的形状"
|
||||
}'
|
||||
```
|
||||
|
||||
**响应格式**:
|
||||
服务器端事件流(Server-Sent Events,Content-Type: text/event-stream)
|
||||
|
||||
**响应**:
|
||||
|
||||
```
|
||||
event: message
|
||||
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"references","content":"","done":false,"knowledge_references":[{"id":"c8347bef-127f-4a22-b962-edf5a75386ec","content":"彗星xxx。","knowledge_id":"a6790b93-4700-4676-bd48-0d4804e1456b","chunk_index":0,"knowledge_title":"彗星.txt","start_at":0,"end_at":2760,"seq":0,"score":4.038836479187012,"match_type":3,"sub_chunk_id":["688821f0-40bf-428e-8cb6-541531ebeb76","c1e9903e-2b4d-4281-be15-0149288d45c2","7d955251-3f79-4fd5-a6aa-02f81e044091"],"metadata":{},"chunk_type":"text","parent_chunk_id":"","image_info":"","knowledge_filename":"彗星.txt","knowledge_source":""},{"id":"fa3aadee-cadb-4a84-9941-c839edc3e626","content":"# 文档名称\n彗星.txt\n\n# 摘要\n彗星是由冰和尘埃构成的太阳系小天体,接近太阳时会释放气体形成彗发和彗尾。其轨道周期差异大,来源包括柯伊伯带和奥尔特云。彗星与小行星的区别逐渐模糊,部分彗星已失去挥发物质,类似小行星。目前已知彗星数量众多,且存在系外彗星。彗星在古代被视为凶兆,现代研究揭示其复杂结构与起源。","knowledge_id":"a6790b93-4700-4676-bd48-0d4804e1456b","chunk_index":6,"knowledge_title":"彗星.txt","start_at":0,"end_at":0,"seq":6,"score":0.6131043121858466,"match_type":3,"sub_chunk_id":null,"metadata":{},"chunk_type":"summary","parent_chunk_id":"c8347bef-127f-4a22-b962-edf5a75386ec","image_info":"","knowledge_filename":"彗星.txt","knowledge_source":""}]}
|
||||
|
||||
event: message
|
||||
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"answer","content":"表现为","done":false,"knowledge_references":null}
|
||||
|
||||
event: message
|
||||
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"answer","content":"结构","done":false,"knowledge_references":null}
|
||||
|
||||
event: message
|
||||
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"answer","content":"。","done":false,"knowledge_references":null}
|
||||
|
||||
event: message
|
||||
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"answer","content":"","done":true,"knowledge_references":null}
|
||||
```
|
||||
|
||||
## POST `/agent-chat/:session_id` - 基于 Agent 的智能问答
|
||||
|
||||
Agent 模式支持更智能的问答,包括工具调用、网络搜索、多知识库检索等能力。
|
||||
|
||||
**请求参数**:
|
||||
- `query`: 查询文本(必填)
|
||||
- `knowledge_base_ids`: 知识库 ID 数组,可动态指定本次查询使用的知识库(可选)
|
||||
- `agent_enabled`: 是否启用 Agent 模式(可选,默认 false)
|
||||
- `web_search_enabled`: 是否启用网络搜索(可选,默认 false)
|
||||
- `summary_model_id`: 覆盖会话默认的摘要模型 ID(可选)
|
||||
- `mcp_service_ids`: MCP 服务白名单(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/agent-chat/ceb9babb-1e30-41d7-817d-fd584954304b' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query": "帮我查询今天的天气",
|
||||
"agent_enabled": true,
|
||||
"web_search_enabled": true,
|
||||
"knowledge_base_ids": ["kb-00000001"]
|
||||
}'
|
||||
```
|
||||
|
||||
**响应格式**:
|
||||
服务器端事件流(Server-Sent Events,Content-Type: text/event-stream)
|
||||
|
||||
**响应类型说明**:
|
||||
|
||||
| response_type | 描述 |
|
||||
|---------------|------|
|
||||
| `thinking` | Agent 思考过程 |
|
||||
| `tool_call` | 工具调用信息 |
|
||||
| `tool_result` | 工具调用结果 |
|
||||
| `references` | 知识库检索引用 |
|
||||
| `answer` | 最终回答内容 |
|
||||
| `reflection` | Agent 反思内容 |
|
||||
| `error` | 错误信息 |
|
||||
|
||||
**响应示例**:
|
||||
|
||||
```
|
||||
event: message
|
||||
data: {"id":"agent-001","response_type":"thinking","content":"用户想查询天气,我需要使用网络搜索工具...","done":false,"knowledge_references":null}
|
||||
|
||||
event: message
|
||||
data: {"id":"agent-001","response_type":"tool_call","content":"","done":false,"knowledge_references":null,"data":{"tool_name":"web_search","arguments":{"query":"今天天气"}}}
|
||||
|
||||
event: message
|
||||
data: {"id":"agent-001","response_type":"tool_result","content":"搜索结果:今天晴,气温25°C...","done":false,"knowledge_references":null}
|
||||
|
||||
event: message
|
||||
data: {"id":"agent-001","response_type":"answer","content":"根据查询结果,今天天气晴朗,气温约25°C。","done":false,"knowledge_references":null}
|
||||
|
||||
event: message
|
||||
data: {"id":"agent-001","response_type":"answer","content":"","done":true,"knowledge_references":null}
|
||||
```
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
# 分块管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | --------------------------- | ------------------------ |
|
||||
| GET | `/chunks/:knowledge_id` | 获取知识的分块列表 |
|
||||
| DELETE | `/chunks/:knowledge_id/:id` | 删除分块 |
|
||||
| DELETE | `/chunks/:knowledge_id` | 删除知识下的所有分块 |
|
||||
|
||||
## GET `/chunks/:knowledge_id?page=&page_size=` - 获取知识的分块列表
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/chunks/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5?page=1&page_size=1' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "df10b37d-cd05-4b14-ba8a-e1bd0eb3bbd7",
|
||||
"tenant_id": 1,
|
||||
"knowledge_id": "4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "",
|
||||
"content": "彗星xxxx",
|
||||
"chunk_index": 0,
|
||||
"is_enabled": true,
|
||||
"status": 2,
|
||||
"start_at": 0,
|
||||
"end_at": 964,
|
||||
"pre_chunk_id": "",
|
||||
"next_chunk_id": "",
|
||||
"chunk_type": "text",
|
||||
"parent_chunk_id": "",
|
||||
"relation_chunks": null,
|
||||
"indirect_relation_chunks": null,
|
||||
"metadata": null,
|
||||
"content_hash": "",
|
||||
"image_info": "",
|
||||
"created_at": "2025-08-12T11:52:36.168632+08:00",
|
||||
"updated_at": "2025-08-12T11:52:53.376871+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 1,
|
||||
"success": true,
|
||||
"total": 5
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/chunks/:knowledge_id/:id` - 删除分块
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/chunks/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5/df10b37d-cd05-4b14-ba8a-e1bd0eb3bbd7' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Chunk deleted",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/chunks/:knowledge_id` - 删除知识下的所有分块
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/chunks/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "All chunks under knowledge deleted",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
# 评估功能 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ---- | ------------- | --------------------- |
|
||||
| GET | `/evaluation` | 获取评估任务 |
|
||||
| POST | `/evaluation` | 创建评估任务 |
|
||||
|
||||
## GET `/evaluation` - 获取评估任务
|
||||
|
||||
**请求参数**:
|
||||
- `task_id`: 从 `POST /evaluation` 接口中获取到的任务 ID
|
||||
- `X-API-Key`: 用户 API Key
|
||||
|
||||
**请求**:
|
||||
|
||||
```bash
|
||||
curl --location 'http://localhost:8080/api/v1/evaluation?task_id=c34563ad-b09f-4858-b72e-e92beb80becb' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"task": {
|
||||
"id": "c34563ad-b09f-4858-b72e-e92beb80becb",
|
||||
"tenant_id": 1,
|
||||
"dataset_id": "default",
|
||||
"start_time": "2025-08-12T14:54:26.221804768+08:00",
|
||||
"status": 2,
|
||||
"total": 1,
|
||||
"finished": 1
|
||||
},
|
||||
"params": {
|
||||
"session_id": "",
|
||||
"knowledge_base_id": "2ef57434-8c8d-4442-b967-2f7fc578a2fc",
|
||||
"vector_threshold": 0.5,
|
||||
"keyword_threshold": 0.3,
|
||||
"embedding_top_k": 10,
|
||||
"vector_database": "",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"rerank_top_k": 5,
|
||||
"rerank_threshold": 0.7,
|
||||
"chat_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_config": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。",
|
||||
"context_template": "你是一个专业的智能信息检索助手",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"fallback_strategy": "",
|
||||
"fallback_response": "抱歉,我无法回答这个问题。"
|
||||
},
|
||||
"metric": {
|
||||
"retrieval_metrics": {
|
||||
"precision": 0,
|
||||
"recall": 0,
|
||||
"ndcg3": 0,
|
||||
"ndcg10": 0,
|
||||
"mrr": 0,
|
||||
"map": 0
|
||||
},
|
||||
"generation_metrics": {
|
||||
"bleu1": 0.037656734016532384,
|
||||
"bleu2": 0.04067392145167686,
|
||||
"bleu4": 0.048963321289052536,
|
||||
"rouge1": 0,
|
||||
"rouge2": 0,
|
||||
"rougel": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/evaluation` - 创建评估任务
|
||||
|
||||
**请求参数**:
|
||||
- `dataset_id`: 评估使用的数据集,暂时只支持官方测试数据集 `default`
|
||||
- `knowledge_base_id`: 评估使用的知识库
|
||||
- `chat_id`: 评估使用的对话模型
|
||||
- `rerank_id`: 评估使用的重排序模型
|
||||
|
||||
**请求**:
|
||||
|
||||
```bash
|
||||
curl --location 'http://localhost:8080/api/v1/evaluation' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"dataset_id": "default",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"chat_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_id": "b30171a1-787b-426e-a293-735cd5ac16c0"
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"task": {
|
||||
"id": "c34563ad-b09f-4858-b72e-e92beb80becb",
|
||||
"tenant_id": 1,
|
||||
"dataset_id": "default",
|
||||
"start_time": "2025-08-12T14:54:26.221804768+08:00",
|
||||
"status": 1
|
||||
},
|
||||
"params": {
|
||||
"session_id": "",
|
||||
"knowledge_base_id": "2ef57434-8c8d-4442-b967-2f7fc578a2fc",
|
||||
"vector_threshold": 0.5,
|
||||
"keyword_threshold": 0.3,
|
||||
"embedding_top_k": 10,
|
||||
"vector_database": "",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"rerank_top_k": 5,
|
||||
"rerank_threshold": 0.7,
|
||||
"chat_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_config": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。",
|
||||
"context_template": "你是一个专业的智能信息检索助手,xxx",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"fallback_strategy": "",
|
||||
"fallback_response": "抱歉,我无法回答这个问题。"
|
||||
}
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,310 @@
|
|||
# FAQ管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ------------------------------------------- | ------------------------ |
|
||||
| GET | `/knowledge-bases/:id/faq/entries` | 获取FAQ条目列表 |
|
||||
| POST | `/knowledge-bases/:id/faq/entries` | 批量导入FAQ条目 |
|
||||
| POST | `/knowledge-bases/:id/faq/entry` | 创建单个FAQ条目 |
|
||||
| PUT | `/knowledge-bases/:id/faq/entries/:entry_id`| 更新单个FAQ条目 |
|
||||
| PUT | `/knowledge-bases/:id/faq/entries/status` | 批量更新FAQ启用状态 |
|
||||
| PUT | `/knowledge-bases/:id/faq/entries/tags` | 批量更新FAQ标签 |
|
||||
| DELETE | `/knowledge-bases/:id/faq/entries` | 批量删除FAQ条目 |
|
||||
| POST | `/knowledge-bases/:id/faq/search` | 混合搜索FAQ |
|
||||
|
||||
## GET `/knowledge-bases/:id/faq/entries` - 获取FAQ条目列表
|
||||
|
||||
**查询参数**:
|
||||
- `page`: 页码(默认 1)
|
||||
- `page_size`: 每页条数(默认 20)
|
||||
- `tag_id`: 按标签ID筛选(可选)
|
||||
- `keyword`: 关键字搜索(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries?page=1&page_size=10' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"total": 100,
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"data": [
|
||||
{
|
||||
"id": "faq-00000001",
|
||||
"chunk_id": "chunk-00000001",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true,
|
||||
"standard_question": "如何重置密码?",
|
||||
"similar_questions": ["忘记密码怎么办", "密码找回"],
|
||||
"negative_questions": ["如何修改用户名"],
|
||||
"answers": ["您可以通过点击登录页面的'忘记密码'链接来重置密码。"],
|
||||
"index_mode": "hybrid",
|
||||
"chunk_type": "faq",
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/knowledge-bases/:id/faq/entries` - 批量导入FAQ条目
|
||||
|
||||
**请求参数**:
|
||||
- `mode`: 导入模式,`append`(追加)或 `replace`(替换)
|
||||
- `entries`: FAQ条目数组
|
||||
- `knowledge_id`: 关联的知识ID(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"mode": "append",
|
||||
"entries": [
|
||||
{
|
||||
"standard_question": "如何联系客服?",
|
||||
"similar_questions": ["客服电话", "在线客服"],
|
||||
"answers": ["您可以通过拨打400-xxx-xxxx联系我们的客服。"],
|
||||
"tag_id": "tag-00000001"
|
||||
},
|
||||
{
|
||||
"standard_question": "退款政策是什么?",
|
||||
"answers": ["我们提供7天无理由退款服务。"]
|
||||
}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"task_id": "task-00000001"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
注:批量导入为异步操作,返回任务ID用于追踪进度。
|
||||
|
||||
## POST `/knowledge-bases/:id/faq/entry` - 创建单个FAQ条目
|
||||
|
||||
同步创建单个FAQ条目,适用于单条录入场景。会自动检查标准问和相似问是否与已有FAQ重复。
|
||||
|
||||
**请求参数**:
|
||||
- `standard_question`: 标准问(必填)
|
||||
- `similar_questions`: 相似问数组(可选)
|
||||
- `negative_questions`: 反例问题数组(可选)
|
||||
- `answers`: 答案数组(必填)
|
||||
- `tag_id`: 标签ID(可选)
|
||||
- `is_enabled`: 是否启用(可选,默认true)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entry' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"standard_question": "如何联系客服?",
|
||||
"similar_questions": ["客服电话", "在线客服"],
|
||||
"answers": ["您可以通过拨打400-xxx-xxxx联系我们的客服。"],
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "faq-00000001",
|
||||
"chunk_id": "chunk-00000001",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true,
|
||||
"standard_question": "如何联系客服?",
|
||||
"similar_questions": ["客服电话", "在线客服"],
|
||||
"negative_questions": [],
|
||||
"answers": ["您可以通过拨打400-xxx-xxxx联系我们的客服。"],
|
||||
"index_mode": "hybrid",
|
||||
"chunk_type": "faq",
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
**错误响应**(标准问或相似问重复时):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "BAD_REQUEST",
|
||||
"message": "标准问与已有FAQ重复"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/knowledge-bases/:id/faq/entries/:entry_id` - 更新单个FAQ条目
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries/faq-00000001' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"standard_question": "如何重置账户密码?",
|
||||
"similar_questions": ["忘记密码怎么办", "密码找回", "重置密码"],
|
||||
"answers": ["您可以通过以下步骤重置密码:1. 点击登录页面的\"忘记密码\" 2. 输入注册邮箱 3. 查收重置邮件"],
|
||||
"is_enabled": true
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/knowledge-bases/:id/faq/entries/status` - 批量更新FAQ启用状态
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries/status' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"updates": {
|
||||
"faq-00000001": true,
|
||||
"faq-00000002": false,
|
||||
"faq-00000003": true
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/knowledge-bases/:id/faq/entries/tags` - 批量更新FAQ标签
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries/tags' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"updates": {
|
||||
"faq-00000001": "tag-00000001",
|
||||
"faq-00000002": "tag-00000002",
|
||||
"faq-00000003": null
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
注:设置为 `null` 可清除标签关联。
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/knowledge-bases/:id/faq/entries` - 批量删除FAQ条目
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/entries' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"ids": ["faq-00000001", "faq-00000002"]
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/knowledge-bases/:id/faq/search` - 混合搜索FAQ
|
||||
|
||||
**请求参数**:
|
||||
- `query_text`: 搜索查询文本
|
||||
- `vector_threshold`: 向量相似度阈值(0-1)
|
||||
- `match_count`: 返回结果数量(最大200)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/faq/search' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query_text": "如何重置密码",
|
||||
"vector_threshold": 0.5,
|
||||
"match_count": 10
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "faq-00000001",
|
||||
"chunk_id": "chunk-00000001",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"tag_id": "tag-00000001",
|
||||
"is_enabled": true,
|
||||
"standard_question": "如何重置密码?",
|
||||
"similar_questions": ["忘记密码怎么办", "密码找回"],
|
||||
"answers": ["您可以通过点击登录页面的'忘记密码'链接来重置密码。"],
|
||||
"chunk_type": "faq",
|
||||
"score": 0.95,
|
||||
"match_type": "vector",
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00"
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,370 @@
|
|||
# 知识库管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ------------------------------------ | ------------------------ |
|
||||
| POST | `/knowledge-bases` | 创建知识库 |
|
||||
| GET | `/knowledge-bases` | 获取知识库列表 |
|
||||
| GET | `/knowledge-bases/:id` | 获取知识库详情 |
|
||||
| PUT | `/knowledge-bases/:id` | 更新知识库 |
|
||||
| DELETE | `/knowledge-bases/:id` | 删除知识库 |
|
||||
| POST | `/knowledge-bases/copy` | 拷贝知识库 |
|
||||
| GET | `/knowledge-bases/:id/hybrid-search` | 混合搜索(向量+关键词) |
|
||||
|
||||
## POST `/knowledge-bases` - 创建知识库
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--data '{
|
||||
"name": "weknora",
|
||||
"description": "weknora description",
|
||||
"chunking_config": {
|
||||
"chunk_size": 1000,
|
||||
"chunk_overlap": 200,
|
||||
"separators": [
|
||||
"."
|
||||
],
|
||||
"enable_multimodal": true
|
||||
},
|
||||
"image_processing_config": {
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_config": {
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
"secret_key": "",
|
||||
"region": "",
|
||||
"bucket_name": "",
|
||||
"app_id": "",
|
||||
"path_prefix": ""
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "b5829e4a-3845-4624-a7fb-ea3b35e843b0",
|
||||
"name": "weknora",
|
||||
"description": "weknora description",
|
||||
"tenant_id": 1,
|
||||
"chunking_config": {
|
||||
"chunk_size": 1000,
|
||||
"chunk_overlap": 200,
|
||||
"separators": [
|
||||
"."
|
||||
],
|
||||
"enable_multimodal": true
|
||||
},
|
||||
"image_processing_config": {
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_config": {
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
"secret_key": "",
|
||||
"region": "",
|
||||
"bucket_name": "",
|
||||
"app_id": "",
|
||||
"path_prefix": ""
|
||||
},
|
||||
"created_at": "2025-08-12T11:30:09.206238645+08:00",
|
||||
"updated_at": "2025-08-12T11:30:09.206238854+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/knowledge-bases` - 获取知识库列表
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "kb-00000001",
|
||||
"name": "Default Knowledge Base",
|
||||
"description": "System Default Knowledge Base",
|
||||
"tenant_id": 1,
|
||||
"chunking_config": {
|
||||
"chunk_size": 1000,
|
||||
"chunk_overlap": 200,
|
||||
"separators": [
|
||||
"\n\n",
|
||||
"\n",
|
||||
"。",
|
||||
"!",
|
||||
"?",
|
||||
";",
|
||||
";"
|
||||
],
|
||||
"enable_multimodal": true
|
||||
},
|
||||
"image_processing_config": {
|
||||
"model_id": ""
|
||||
},
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_config": {
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
"secret_key": "",
|
||||
"region": "",
|
||||
"bucket_name": "",
|
||||
"app_id": "",
|
||||
"path_prefix": ""
|
||||
},
|
||||
"created_at": "2025-08-11T20:10:41.817794+08:00",
|
||||
"updated_at": "2025-08-12T11:23:00.593097+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/knowledge-bases/:id` - 获取知识库详情
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "kb-00000001",
|
||||
"name": "Default Knowledge Base",
|
||||
"description": "System Default Knowledge Base",
|
||||
"tenant_id": 1,
|
||||
"chunking_config": {
|
||||
"chunk_size": 1000,
|
||||
"chunk_overlap": 200,
|
||||
"separators": [
|
||||
"\n\n",
|
||||
"\n",
|
||||
"。",
|
||||
"!",
|
||||
"?",
|
||||
";",
|
||||
";"
|
||||
],
|
||||
"enable_multimodal": true
|
||||
},
|
||||
"image_processing_config": {
|
||||
"model_id": ""
|
||||
},
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_config": {
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
"secret_key": "",
|
||||
"region": "",
|
||||
"bucket_name": "",
|
||||
"app_id": "",
|
||||
"path_prefix": ""
|
||||
},
|
||||
"created_at": "2025-08-11T20:10:41.817794+08:00",
|
||||
"updated_at": "2025-08-12T11:23:00.593097+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/knowledge-bases/:id` - 更新知识库
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/b5829e4a-3845-4624-a7fb-ea3b35e843b0' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--data '{
|
||||
"name": "weknora new",
|
||||
"description": "weknora description new",
|
||||
"config": {
|
||||
"chunking_config": {
|
||||
"chunk_size": 1000,
|
||||
"chunk_overlap": 200,
|
||||
"separators": [
|
||||
"\n\n",
|
||||
"\n",
|
||||
"。",
|
||||
"!",
|
||||
"?",
|
||||
";",
|
||||
";"
|
||||
],
|
||||
"enable_multimodal": true
|
||||
},
|
||||
"image_processing_config": {
|
||||
"model_id": ""
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "b5829e4a-3845-4624-a7fb-ea3b35e843b0",
|
||||
"name": "weknora new",
|
||||
"description": "weknora description new",
|
||||
"tenant_id": 1,
|
||||
"chunking_config": {
|
||||
"chunk_size": 1000,
|
||||
"chunk_overlap": 200,
|
||||
"separators": [
|
||||
"\n\n",
|
||||
"\n",
|
||||
"。",
|
||||
"!",
|
||||
"?",
|
||||
";",
|
||||
";"
|
||||
],
|
||||
"enable_multimodal": true
|
||||
},
|
||||
"image_processing_config": {
|
||||
"model_id": ""
|
||||
},
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"rerank_model_id": "b30171a1-787b-426e-a293-735cd5ac16c0",
|
||||
"vlm_config": {
|
||||
"enabled": true,
|
||||
"model_id": "f2083ad7-63e3-486d-a610-e6c56e58d72e"
|
||||
},
|
||||
"cos_config": {
|
||||
"secret_id": "",
|
||||
"secret_key": "",
|
||||
"region": "",
|
||||
"bucket_name": "",
|
||||
"app_id": "",
|
||||
"path_prefix": ""
|
||||
},
|
||||
"created_at": "2025-08-12T11:30:09.206238+08:00",
|
||||
"updated_at": "2025-08-12T11:36:09.083577609+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/knowledge-bases/:id` - 删除知识库
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/b5829e4a-3845-4624-a7fb-ea3b35e843b0' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Knowledge base deleted successfully",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/knowledge-bases/:id/hybrid-search` - 混合搜索
|
||||
|
||||
执行向量搜索和关键词搜索的混合检索。
|
||||
|
||||
**注意**:此接口使用 GET 方法但需要 JSON 请求体。
|
||||
|
||||
**请求参数**:
|
||||
- `query_text`: 搜索查询文本(必填)
|
||||
- `vector_threshold`: 向量相似度阈值(0-1,可选)
|
||||
- `keyword_threshold`: 关键词匹配阈值(可选)
|
||||
- `match_count`: 返回结果数量(可选)
|
||||
- `disable_keywords_match`: 是否禁用关键词匹配(可选)
|
||||
- `disable_vector_match`: 是否禁用向量匹配(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request GET 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/hybrid-search' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query_text": "如何使用知识库",
|
||||
"vector_threshold": 0.5,
|
||||
"match_count": 10
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "chunk-00000001",
|
||||
"content": "知识库是用于存储和检索知识的系统...",
|
||||
"knowledge_id": "knowledge-00000001",
|
||||
"chunk_index": 0,
|
||||
"knowledge_title": "知识库使用指南",
|
||||
"start_at": 0,
|
||||
"end_at": 500,
|
||||
"seq": 1,
|
||||
"score": 0.95,
|
||||
"chunk_type": "text",
|
||||
"image_info": "",
|
||||
"metadata": {},
|
||||
"knowledge_filename": "guide.pdf",
|
||||
"knowledge_source": "file"
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,313 @@
|
|||
# 知识管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ------------------------------------- | ------------------------ |
|
||||
| POST | `/knowledge-bases/:id/knowledge/file` | 从文件创建知识 |
|
||||
| POST | `/knowledge-bases/:id/knowledge/url` | 从 URL 创建知识 |
|
||||
| POST | `/knowledge-bases/:id/knowledge/manual` | 创建手工 Markdown 知识 |
|
||||
| GET | `/knowledge-bases/:id/knowledge` | 获取知识库下的知识列表 |
|
||||
| GET | `/knowledge/:id` | 获取知识详情 |
|
||||
| DELETE | `/knowledge/:id` | 删除知识 |
|
||||
| GET | `/knowledge/:id/download` | 下载知识文件 |
|
||||
| PUT | `/knowledge/:id` | 更新知识 |
|
||||
| PUT | `/knowledge/manual/:id` | 更新手工 Markdown 知识 |
|
||||
| PUT | `/knowledge/image/:id/:chunk_id` | 更新图像分块信息 |
|
||||
| PUT | `/knowledge/tags` | 批量更新知识标签 |
|
||||
| GET | `/knowledge/batch` | 批量获取知识 |
|
||||
|
||||
## POST `/knowledge-bases/:id/knowledge/file` - 从文件创建知识
|
||||
|
||||
**表单参数**:
|
||||
- `file`: 上传的文件(必填)
|
||||
- `metadata`: JSON 格式的元数据(可选)
|
||||
- `enable_multimodel`: 是否启用多模态处理(可选,true/false)
|
||||
- `fileName`: 自定义文件名,用于文件夹上传时保留路径(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowledge/file' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--form 'file=@"/Users/xxxx/tests/彗星.txt"' \
|
||||
--form 'enable_multimodel="true"'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"type": "file",
|
||||
"title": "彗星.txt",
|
||||
"description": "",
|
||||
"source": "",
|
||||
"parse_status": "processing",
|
||||
"enable_status": "disabled",
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"file_name": "彗星.txt",
|
||||
"file_type": "txt",
|
||||
"file_size": 7710,
|
||||
"file_hash": "d69476ddbba45223a5e97e786539952c",
|
||||
"file_path": "data/files/1/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5/1754970756171067621.txt",
|
||||
"storage_size": 0,
|
||||
"metadata": null,
|
||||
"created_at": "2025-08-12T11:52:36.168632288+08:00",
|
||||
"updated_at": "2025-08-12T11:52:36.173612121+08:00",
|
||||
"processed_at": null,
|
||||
"error_message": "",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/knowledge-bases/:id/knowledge/url` - 从 URL 创建知识
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowledge/url' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"url":"https://github.com/Tencent/WeKnora",
|
||||
"enable_multimodel":true
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "9c8af585-ae15-44ce-8f73-45ad18394651",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"type": "url",
|
||||
"title": "",
|
||||
"description": "",
|
||||
"source": "https://github.com/Tencent/WeKnora",
|
||||
"parse_status": "processing",
|
||||
"enable_status": "disabled",
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"file_name": "",
|
||||
"file_type": "",
|
||||
"file_size": 0,
|
||||
"file_hash": "",
|
||||
"file_path": "",
|
||||
"storage_size": 0,
|
||||
"metadata": null,
|
||||
"created_at": "2025-08-12T11:55:05.709266776+08:00",
|
||||
"updated_at": "2025-08-12T11:55:05.712918234+08:00",
|
||||
"processed_at": null,
|
||||
"error_message": "",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/knowledge-bases/:id/knowledge` - 获取知识库下的知识列表
|
||||
|
||||
**查询参数**:
|
||||
- `page`: 页码(默认 1)
|
||||
- `page_size`: 每页条数(默认 20)
|
||||
- `tag_id`: 按标签ID筛选(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowledge?page_size=1&page=1&tag_id=tag-00000001' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "9c8af585-ae15-44ce-8f73-45ad18394651",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"type": "url",
|
||||
"title": "",
|
||||
"description": "",
|
||||
"source": "https://github.com/Tencent/WeKnora",
|
||||
"parse_status": "pending",
|
||||
"enable_status": "disabled",
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"file_name": "",
|
||||
"file_type": "",
|
||||
"file_size": 0,
|
||||
"file_hash": "",
|
||||
"file_path": "",
|
||||
"storage_size": 0,
|
||||
"metadata": null,
|
||||
"created_at": "2025-08-12T11:55:05.709266+08:00",
|
||||
"updated_at": "2025-08-12T11:55:05.709266+08:00",
|
||||
"processed_at": null,
|
||||
"error_message": "",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 1,
|
||||
"success": true,
|
||||
"total": 2
|
||||
}
|
||||
```
|
||||
|
||||
注:parse_status 包含 `pending/processing/failed/completed` 四种状态
|
||||
|
||||
## GET `/knowledge/:id` - 获取知识详情
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"type": "file",
|
||||
"title": "彗星.txt",
|
||||
"description": "彗星是由冰和尘埃构成的太阳系小天体,接近太阳时会形成彗发和彗尾。其轨道周期差异大,来源包括柯伊伯带和奥尔特云。彗星与小行星的区别逐渐模糊,部分彗星已失去挥发物质,类似小行星。截至2019年,已知彗星超6600颗,数量庞大。彗星在古代被视为凶兆,现代研究揭示其复杂结构与起源。",
|
||||
"source": "",
|
||||
"parse_status": "completed",
|
||||
"enable_status": "enabled",
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"file_name": "彗星.txt",
|
||||
"file_type": "txt",
|
||||
"file_size": 7710,
|
||||
"file_hash": "d69476ddbba45223a5e97e786539952c",
|
||||
"file_path": "data/files/1/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5/1754970756171067621.txt",
|
||||
"storage_size": 33689,
|
||||
"metadata": null,
|
||||
"created_at": "2025-08-12T11:52:36.168632+08:00",
|
||||
"updated_at": "2025-08-12T11:52:53.376871+08:00",
|
||||
"processed_at": "2025-08-12T11:52:53.376573+08:00",
|
||||
"error_message": "",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/knowledge/batch` - 批量获取知识
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge/batch?ids=9c8af585-ae15-44ce-8f73-45ad18394651&ids=4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "9c8af585-ae15-44ce-8f73-45ad18394651",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"type": "url",
|
||||
"title": "",
|
||||
"description": "",
|
||||
"source": "https://github.com/Tencent/WeKnora",
|
||||
"parse_status": "pending",
|
||||
"enable_status": "disabled",
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"file_name": "",
|
||||
"file_type": "",
|
||||
"file_size": 0,
|
||||
"file_hash": "",
|
||||
"file_path": "",
|
||||
"storage_size": 0,
|
||||
"metadata": null,
|
||||
"created_at": "2025-08-12T11:55:05.709266+08:00",
|
||||
"updated_at": "2025-08-12T11:55:05.709266+08:00",
|
||||
"processed_at": null,
|
||||
"error_message": "",
|
||||
"deleted_at": null
|
||||
},
|
||||
{
|
||||
"id": "4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"type": "file",
|
||||
"title": "彗星.txt",
|
||||
"description": "彗星是由冰和尘埃构成的太阳系小天体,接近太阳时会形成彗发和彗尾。其轨道周期差异大,来源包括柯伊伯带和奥尔特云。彗星与小行星的区别逐渐模糊,部分彗星已失去挥发物质,类似小行星。截至2019年,已知彗星超6600颗,数量庞大。彗星在古代被视为凶兆,现代研究揭示其复杂结构与起源。",
|
||||
"source": "",
|
||||
"parse_status": "completed",
|
||||
"enable_status": "enabled",
|
||||
"embedding_model_id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"file_name": "彗星.txt",
|
||||
"file_type": "txt",
|
||||
"file_size": 7710,
|
||||
"file_hash": "d69476ddbba45223a5e97e786539952c",
|
||||
"file_path": "data/files/1/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5/1754970756171067621.txt",
|
||||
"storage_size": 33689,
|
||||
"metadata": null,
|
||||
"created_at": "2025-08-12T11:52:36.168632+08:00",
|
||||
"updated_at": "2025-08-12T11:52:53.376871+08:00",
|
||||
"processed_at": "2025-08-12T11:52:53.376573+08:00",
|
||||
"error_message": "",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/knowledge/:id` - 删除知识
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge/9c8af585-ae15-44ce-8f73-45ad18394651' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Deleted successfully",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/knowledge/:id/download` - 下载知识文件
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5/download' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```
|
||||
attachment
|
||||
```
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
# 消息管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ---------------------------- | ------------------------ |
|
||||
| GET | `/messages/:session_id/load` | 获取最近的会话消息列表 |
|
||||
| DELETE | `/messages/:session_id/:id` | 删除消息 |
|
||||
|
||||
## GET `/messages/:session_id/load` - 获取最近的会话消息列表
|
||||
|
||||
**查询参数**:
|
||||
|
||||
- `before_time`: 上一次拉取的最早一条消息的 created_at 字段,为空拉取最近的消息
|
||||
- `limit`: 每页条数(默认 20)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request GET 'http://localhost:8080/api/v1/messages/ceb9babb-1e30-41d7-817d-fd584954304b/load?limit=3&before_time=2030-08-12T14%3A35%3A42.123456789Z' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"query": "彗尾的形状"
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "b8b90eeb-7dd5-4cf9-81c6-5ebcbd759451",
|
||||
"session_id": "ceb9babb-1e30-41d7-817d-fd584954304b",
|
||||
"request_id": "hCA8SDjxcAvv",
|
||||
"content": "<think>\n好的",
|
||||
"role": "assistant",
|
||||
"knowledge_references": [
|
||||
{
|
||||
"id": "c8347bef-127f-4a22-b962-edf5a75386ec",
|
||||
"content": "彗星xxx",
|
||||
"knowledge_id": "a6790b93-4700-4676-bd48-0d4804e1456b",
|
||||
"chunk_index": 0,
|
||||
"knowledge_title": "彗星.txt",
|
||||
"start_at": 0,
|
||||
"end_at": 2760,
|
||||
"seq": 0,
|
||||
"score": 4.038836479187012,
|
||||
"match_type": 4,
|
||||
"sub_chunk_id": [
|
||||
"688821f0-40bf-428e-8cb6-541531ebeb76",
|
||||
"c1e9903e-2b4d-4281-be15-0149288d45c2",
|
||||
"7d955251-3f79-4fd5-a6aa-02f81e044091"
|
||||
],
|
||||
"metadata": {},
|
||||
"chunk_type": "text",
|
||||
"parent_chunk_id": "",
|
||||
"image_info": "",
|
||||
"knowledge_filename": "彗星.txt",
|
||||
"knowledge_source": ""
|
||||
},
|
||||
{
|
||||
"id": "fa3aadee-cadb-4a84-9941-c839edc3e626",
|
||||
"content": "# 文档名称\n彗星.txt\n\n# 摘要\n彗星是由冰和尘埃构成的太阳系小天体,接近太阳时会释放气体形成彗发和彗尾。其轨道周期差异大,来源包括柯伊伯带和奥尔特云。彗星与小行星的区别逐渐模糊,部分彗星已失去挥发物质,类似小行星。目前已知彗星数量众多,且存在系外彗星。彗星在古代被视为凶兆,现代研究揭示其复杂结构与起源。",
|
||||
"knowledge_id": "a6790b93-4700-4676-bd48-0d4804e1456b",
|
||||
"chunk_index": 6,
|
||||
"knowledge_title": "彗星.txt",
|
||||
"start_at": 0,
|
||||
"end_at": 0,
|
||||
"seq": 6,
|
||||
"score": 0.6131043121858466,
|
||||
"match_type": 0,
|
||||
"sub_chunk_id": null,
|
||||
"metadata": {},
|
||||
"chunk_type": "summary",
|
||||
"parent_chunk_id": "c8347bef-127f-4a22-b962-edf5a75386ec",
|
||||
"image_info": "",
|
||||
"knowledge_filename": "彗星.txt",
|
||||
"knowledge_source": ""
|
||||
}
|
||||
],
|
||||
"agent_steps": [],
|
||||
"is_completed": true,
|
||||
"created_at": "2025-08-12T10:24:38.370548+08:00",
|
||||
"updated_at": "2025-08-12T10:25:40.416382+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
{
|
||||
"id": "7fa136ae-a045-424e-baac-52113d92ae94",
|
||||
"session_id": "ceb9babb-1e30-41d7-817d-fd584954304b",
|
||||
"request_id": "3475c004-0ada-4306-9d30-d7f5efce50d2",
|
||||
"content": "彗尾的形状",
|
||||
"role": "user",
|
||||
"knowledge_references": [],
|
||||
"agent_steps": [],
|
||||
"is_completed": true,
|
||||
"created_at": "2025-08-12T14:30:39.732246+08:00",
|
||||
"updated_at": "2025-08-12T14:30:39.733277+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
{
|
||||
"id": "9bcafbcf-a758-40af-a9a3-c4d8e0f49439",
|
||||
"session_id": "ceb9babb-1e30-41d7-817d-fd584954304b",
|
||||
"request_id": "3475c004-0ada-4306-9d30-d7f5efce50d2",
|
||||
"content": "<think>\n好的",
|
||||
"role": "assistant",
|
||||
"knowledge_references": [
|
||||
{
|
||||
"id": "c8347bef-127f-4a22-b962-edf5a75386ec",
|
||||
"content": "彗星xxx",
|
||||
"knowledge_id": "a6790b93-4700-4676-bd48-0d4804e1456b",
|
||||
"chunk_index": 0,
|
||||
"knowledge_title": "彗星.txt",
|
||||
"start_at": 0,
|
||||
"end_at": 2760,
|
||||
"seq": 0,
|
||||
"score": 4.038836479187012,
|
||||
"match_type": 3,
|
||||
"sub_chunk_id": [
|
||||
"688821f0-40bf-428e-8cb6-541531ebeb76",
|
||||
"c1e9903e-2b4d-4281-be15-0149288d45c2",
|
||||
"7d955251-3f79-4fd5-a6aa-02f81e044091"
|
||||
],
|
||||
"metadata": {},
|
||||
"chunk_type": "text",
|
||||
"parent_chunk_id": "",
|
||||
"image_info": "",
|
||||
"knowledge_filename": "彗星.txt",
|
||||
"knowledge_source": ""
|
||||
},
|
||||
{
|
||||
"id": "fa3aadee-cadb-4a84-9941-c839edc3e626",
|
||||
"content": "# 文档名称\n彗星.txt\n\n# 摘要\n彗星是由冰和尘埃构成的太阳系小天体,接近太阳时会释放气体形成彗发和彗尾。其轨道周期差异大,来源包括柯伊伯带和奥尔特云。彗星与小行星的区别逐渐模糊,部分彗星已失去挥发物质,类似小行星。目前已知彗星数量众多,且存在系外彗星。彗星在古代被视为凶兆,现代研究揭示其复杂结构与起源。",
|
||||
"knowledge_id": "a6790b93-4700-4676-bd48-0d4804e1456b",
|
||||
"chunk_index": 6,
|
||||
"knowledge_title": "彗星.txt",
|
||||
"start_at": 0,
|
||||
"end_at": 0,
|
||||
"seq": 6,
|
||||
"score": 0.6131043121858466,
|
||||
"match_type": 3,
|
||||
"sub_chunk_id": null,
|
||||
"metadata": {},
|
||||
"chunk_type": "summary",
|
||||
"parent_chunk_id": "c8347bef-127f-4a22-b962-edf5a75386ec",
|
||||
"image_info": "",
|
||||
"knowledge_filename": "彗星.txt",
|
||||
"knowledge_source": ""
|
||||
}
|
||||
],
|
||||
"agent_steps": [],
|
||||
"is_completed": true,
|
||||
"created_at": "2025-08-12T14:30:39.735108+08:00",
|
||||
"updated_at": "2025-08-12T14:31:17.829926+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/messages/:session_id/:id` - 删除消息
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/messages/ceb9babb-1e30-41d7-817d-fd584954304b/9bcafbcf-a758-40af-a9a3-c4d8e0f49439' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Message deleted successfully",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,271 @@
|
|||
# 模型管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | --------------------- | --------------------- |
|
||||
| POST | `/models` | 创建模型 |
|
||||
| GET | `/models` | 获取模型列表 |
|
||||
| GET | `/models/:id` | 获取模型详情 |
|
||||
| PUT | `/models/:id` | 更新模型 |
|
||||
| DELETE | `/models/:id` | 删除模型 |
|
||||
|
||||
## POST `/models` - 创建模型
|
||||
|
||||
### 创建对话模型(KnowledgeQA)
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/models' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--data '{
|
||||
"name": "qwen3:8b",
|
||||
"type": "KnowledgeQA",
|
||||
"source": "local",
|
||||
"description": "LLM Model for Knowledge QA",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": ""
|
||||
},
|
||||
"is_default": false
|
||||
}'
|
||||
```
|
||||
|
||||
### 创建嵌入模型(Embedding)
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/models' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--data '{
|
||||
"name": "nomic-embed-text:latest",
|
||||
"type": "Embedding",
|
||||
"source": "local",
|
||||
"description": "Embedding Model",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"embedding_parameters": {
|
||||
"dimension": 768,
|
||||
"truncate_prompt_tokens": 0
|
||||
}
|
||||
},
|
||||
"is_default": false
|
||||
}'
|
||||
```
|
||||
|
||||
### 创建排序模型(Rerank)
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/models' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--data '{
|
||||
"name": "linux6200/bge-reranker-v2-m3:latest",
|
||||
"type": "Rerank",
|
||||
"source": "local",
|
||||
"description": "Rerank Model for Knowledge QA",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": ""
|
||||
},
|
||||
"is_default": false
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "09c5a1d6-ee8b-4657-9a17-d3dcbd5c70cb",
|
||||
"tenant_id": 1,
|
||||
"name": "nomic-embed-text:latest3",
|
||||
"type": "Embedding",
|
||||
"source": "local",
|
||||
"description": "Embedding Model",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"embedding_parameters": {
|
||||
"dimension": 768,
|
||||
"truncate_prompt_tokens": 0
|
||||
}
|
||||
},
|
||||
"is_default": false,
|
||||
"status": "downloading",
|
||||
"created_at": "2025-08-12T10:39:01.454591766+08:00",
|
||||
"updated_at": "2025-08-12T10:39:01.454591766+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/models` - 获取模型列表
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/models' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"tenant_id": 1,
|
||||
"name": "nomic-embed-text:latest",
|
||||
"type": "Embedding",
|
||||
"source": "local",
|
||||
"description": "Embedding Model",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"embedding_parameters": {
|
||||
"dimension": 768,
|
||||
"truncate_prompt_tokens": 0
|
||||
}
|
||||
},
|
||||
"is_default": true,
|
||||
"status": "active",
|
||||
"created_at": "2025-08-11T20:10:41.813832+08:00",
|
||||
"updated_at": "2025-08-11T20:10:41.822354+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
{
|
||||
"id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"tenant_id": 1,
|
||||
"name": "qwen3:8b",
|
||||
"type": "KnowledgeQA",
|
||||
"source": "local",
|
||||
"description": "LLM Model for Knowledge QA",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"embedding_parameters": {
|
||||
"dimension": 0,
|
||||
"truncate_prompt_tokens": 0
|
||||
}
|
||||
},
|
||||
"is_default": true,
|
||||
"status": "active",
|
||||
"created_at": "2025-08-11T20:10:41.811761+08:00",
|
||||
"updated_at": "2025-08-11T20:10:41.825381+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/models/:id` - 获取模型详情
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/models/dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "dff7bc94-7885-4dd1-bfd5-bd96e4df2fc3",
|
||||
"tenant_id": 1,
|
||||
"name": "nomic-embed-text:latest",
|
||||
"type": "Embedding",
|
||||
"source": "local",
|
||||
"description": "Embedding Model",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"embedding_parameters": {
|
||||
"dimension": 768,
|
||||
"truncate_prompt_tokens": 0
|
||||
}
|
||||
},
|
||||
"is_default": true,
|
||||
"status": "active",
|
||||
"created_at": "2025-08-11T20:10:41.813832+08:00",
|
||||
"updated_at": "2025-08-11T20:10:41.822354+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/models/:id` - 更新模型
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/models/8fdc464d-8eaa-44d4-a85b-094b28af5330' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--data '{
|
||||
"name": "linux6200/bge-reranker-v2-m3:latest",
|
||||
"description": "Rerank Model for Knowledge QA new",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": ""
|
||||
},
|
||||
"is_default": false
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "8fdc464d-8eaa-44d4-a85b-094b28af5330",
|
||||
"tenant_id": 1,
|
||||
"name": "linux6200/bge-reranker-v2-m3:latest",
|
||||
"type": "Rerank",
|
||||
"source": "local",
|
||||
"description": "Rerank Model for Knowledge QA new",
|
||||
"parameters": {
|
||||
"base_url": "",
|
||||
"api_key": "",
|
||||
"embedding_parameters": {
|
||||
"dimension": 0,
|
||||
"truncate_prompt_tokens": 0
|
||||
}
|
||||
},
|
||||
"is_default": false,
|
||||
"status": "active",
|
||||
"created_at": "2025-08-12T10:57:39.512681+08:00",
|
||||
"updated_at": "2025-08-12T11:00:27.271678+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/models/:id` - 删除模型
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/models/8fdc464d-8eaa-44d4-a85b-094b28af5330' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Model deleted",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,361 @@
|
|||
# 会话管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | --------------------------------------- | --------------------- |
|
||||
| POST | `/sessions` | 创建会话 |
|
||||
| GET | `/sessions/:id` | 获取会话详情 |
|
||||
| GET | `/sessions` | 获取租户的会话列表 |
|
||||
| PUT | `/sessions/:id` | 更新会话 |
|
||||
| DELETE | `/sessions/:id` | 删除会话 |
|
||||
| POST | `/sessions/:session_id/generate_title` | 生成会话标题 |
|
||||
| GET | `/sessions/continue-stream/:session_id` | 继续未完成的会话 |
|
||||
|
||||
## POST `/sessions` - 创建会话
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sessions' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"session_strategy": {
|
||||
"max_rounds": 5,
|
||||
"enable_rewrite": true,
|
||||
"fallback_strategy": "FIXED_RESPONSE",
|
||||
"fallback_response": "对不起,我无法回答这个问题",
|
||||
"embedding_top_k": 10,
|
||||
"keyword_threshold": 0.5,
|
||||
"vector_threshold": 0.7,
|
||||
"rerank_model_id": "排序模型ID",
|
||||
"rerank_top_k": 3,
|
||||
"rerank_threshold": 0.7,
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_parameters": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。xxx",
|
||||
"context_template": "你是一个专业的智能信息检索助手xxx",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "411d6b70-9a85-4d03-bb74-aab0fd8bd12f",
|
||||
"title": "",
|
||||
"description": "",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"max_rounds": 5,
|
||||
"enable_rewrite": true,
|
||||
"fallback_strategy": "FIXED_RESPONSE",
|
||||
"fallback_response": "对不起,我无法回答这个问题",
|
||||
"embedding_top_k": 10,
|
||||
"keyword_threshold": 0.5,
|
||||
"vector_threshold": 0.7,
|
||||
"rerank_model_id": "排序模型ID",
|
||||
"rerank_top_k": 3,
|
||||
"rerank_threshold": 0.7,
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_parameters": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。xxx",
|
||||
"context_template": "你是一个专业的智能信息检索助手xxx",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"agent_config": null,
|
||||
"context_config": null,
|
||||
"created_at": "2025-08-12T12:26:19.611616669+08:00",
|
||||
"updated_at": "2025-08-12T12:26:19.611616919+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/sessions/:id` - 获取会话详情
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sessions/ceb9babb-1e30-41d7-817d-fd584954304b' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "ceb9babb-1e30-41d7-817d-fd584954304b",
|
||||
"title": "模型优化策略",
|
||||
"description": "",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"max_rounds": 5,
|
||||
"enable_rewrite": true,
|
||||
"fallback_strategy": "fixed",
|
||||
"fallback_response": "抱歉,我无法回答这个问题。",
|
||||
"embedding_top_k": 10,
|
||||
"keyword_threshold": 0.3,
|
||||
"vector_threshold": 0.5,
|
||||
"rerank_model_id": "",
|
||||
"rerank_top_k": 5,
|
||||
"rerank_threshold": 0.7,
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_parameters": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话",
|
||||
"context_template": "你是一个专业的智能信息检索助手",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"agent_config": null,
|
||||
"context_config": null,
|
||||
"created_at": "2025-08-12T10:24:38.308596+08:00",
|
||||
"updated_at": "2025-08-12T10:25:41.317761+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/sessions?page=&page_size=` - 获取租户的会话列表
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sessions?page=1&page_size=1' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "411d6b70-9a85-4d03-bb74-aab0fd8bd12f",
|
||||
"title": "",
|
||||
"description": "",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"max_rounds": 5,
|
||||
"enable_rewrite": true,
|
||||
"fallback_strategy": "FIXED_RESPONSE",
|
||||
"fallback_response": "对不起,我无法回答这个问题",
|
||||
"embedding_top_k": 10,
|
||||
"keyword_threshold": 0.5,
|
||||
"vector_threshold": 0.7,
|
||||
"rerank_model_id": "排序模型ID",
|
||||
"rerank_top_k": 3,
|
||||
"rerank_threshold": 0.7,
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_parameters": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。xxx",
|
||||
"context_template": "你是一个专业的智能信息检索助手xxx",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"created_at": "2025-08-12T12:26:19.611616+08:00",
|
||||
"updated_at": "2025-08-12T12:26:19.611616+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 1,
|
||||
"success": true,
|
||||
"total": 2
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/sessions/:id` - 更新会话
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/sessions/411d6b70-9a85-4d03-bb74-aab0fd8bd12f' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"title": "weknora",
|
||||
"description": "weknora description",
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"max_rounds": 5,
|
||||
"enable_rewrite": true,
|
||||
"fallback_strategy": "FIXED_RESPONSE",
|
||||
"fallback_response": "对不起,我无法回答这个问题",
|
||||
"embedding_top_k": 10,
|
||||
"keyword_threshold": 0.5,
|
||||
"vector_threshold": 0.7,
|
||||
"rerank_model_id": "排序模型ID",
|
||||
"rerank_top_k": 3,
|
||||
"rerank_threshold": 0.7,
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_parameters": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。xxx",
|
||||
"context_template": "你是一个专业的智能信息检索助手xxx",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "411d6b70-9a85-4d03-bb74-aab0fd8bd12f",
|
||||
"title": "weknora",
|
||||
"description": "weknora description",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"max_rounds": 5,
|
||||
"enable_rewrite": true,
|
||||
"fallback_strategy": "FIXED_RESPONSE",
|
||||
"fallback_response": "对不起,我无法回答这个问题",
|
||||
"embedding_top_k": 10,
|
||||
"keyword_threshold": 0.5,
|
||||
"vector_threshold": 0.7,
|
||||
"rerank_model_id": "排序模型ID",
|
||||
"rerank_top_k": 3,
|
||||
"rerank_threshold": 0.7,
|
||||
"summary_model_id": "8aea788c-bb30-4898-809e-e40c14ffb48c",
|
||||
"summary_parameters": {
|
||||
"max_tokens": 0,
|
||||
"repeat_penalty": 1,
|
||||
"top_k": 0,
|
||||
"top_p": 0,
|
||||
"frequency_penalty": 0,
|
||||
"presence_penalty": 0,
|
||||
"prompt": "这是用户和助手之间的对话。xxx",
|
||||
"context_template": "你是一个专业的智能信息检索助手xxx",
|
||||
"no_match_prefix": "<think>\n</think>\nNO_MATCH",
|
||||
"temperature": 0.3,
|
||||
"seed": 0,
|
||||
"max_completion_tokens": 2048
|
||||
},
|
||||
"created_at": "0001-01-01T00:00:00Z",
|
||||
"updated_at": "2025-08-12T14:20:56.738424351+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/sessions/:id` - 删除会话
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/sessions/411d6b70-9a85-4d03-bb74-aab0fd8bd12f' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Session deleted successfully",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/sessions/:session_id/generate_title` - 生成会话标题
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sessions/ceb9babb-1e30-41d7-817d-fd584954304b/generate_title' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "你好,我想了解关于人工智能的知识"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "人工智能是计算机科学的一个分支..."
|
||||
}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": "模型优化策略",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/sessions/continue-stream/:session_id` - 继续未完成的会话
|
||||
|
||||
**查询参数**:
|
||||
- `message_id`: 从 `/messages/:session_id/load` 接口中获取的 `is_completed` 为 `false` 的消息 ID
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sessions/continue-stream/ceb9babb-1e30-41d7-817d-fd584954304b?message_id=b8b90eeb-7dd5-4cf9-81c6-5ebcbd759451' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应格式**:
|
||||
服务器端事件流(Server-Sent Events),与 `/knowledge-chat/:session_id` 返回结果一致
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
# 标签管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ------------------------------------- | ------------------------ |
|
||||
| GET | `/knowledge-bases/:id/tags` | 获取知识库标签列表 |
|
||||
| POST | `/knowledge-bases/:id/tags` | 创建标签 |
|
||||
| PUT | `/knowledge-bases/:id/tags/:tag_id` | 更新标签 |
|
||||
| DELETE | `/knowledge-bases/:id/tags/:tag_id` | 删除标签 |
|
||||
|
||||
## GET `/knowledge-bases/:id/tags` - 获取知识库标签列表
|
||||
|
||||
**查询参数**:
|
||||
- `page`: 页码(默认 1)
|
||||
- `page_size`: 每页条数(默认 20)
|
||||
- `keyword`: 标签名称关键字搜索(可选)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags?page=1&page_size=10' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"total": 2,
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"data": [
|
||||
{
|
||||
"id": "tag-00000001",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "技术文档",
|
||||
"color": "#1890ff",
|
||||
"sort_order": 1,
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00",
|
||||
"knowledge_count": 5,
|
||||
"chunk_count": 120
|
||||
},
|
||||
{
|
||||
"id": "tag-00000002",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "常见问题",
|
||||
"color": "#52c41a",
|
||||
"sort_order": 2,
|
||||
"created_at": "2025-08-12T10:00:00+08:00",
|
||||
"updated_at": "2025-08-12T10:00:00+08:00",
|
||||
"knowledge_count": 3,
|
||||
"chunk_count": 45
|
||||
}
|
||||
]
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/knowledge-bases/:id/tags` - 创建标签
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"name": "产品手册",
|
||||
"color": "#faad14",
|
||||
"sort_order": 3
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "tag-00000003",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "产品手册",
|
||||
"color": "#faad14",
|
||||
"sort_order": 3,
|
||||
"created_at": "2025-08-12T11:00:00+08:00",
|
||||
"updated_at": "2025-08-12T11:00:00+08:00"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/knowledge-bases/:id/tags/:tag_id` - 更新标签
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags/tag-00000003' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"name": "产品手册更新",
|
||||
"color": "#ff4d4f"
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": "tag-00000003",
|
||||
"tenant_id": 1,
|
||||
"knowledge_base_id": "kb-00000001",
|
||||
"name": "产品手册更新",
|
||||
"color": "#ff4d4f",
|
||||
"sort_order": 3,
|
||||
"created_at": "2025-08-12T11:00:00+08:00",
|
||||
"updated_at": "2025-08-12T11:30:00+08:00"
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/knowledge-bases/:id/tags/:tag_id` - 删除标签
|
||||
|
||||
**查询参数**:
|
||||
- `force`: 设置为 `true` 时强制删除(即使标签被引用)
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/tags/tag-00000003?force=true' \
|
||||
--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \
|
||||
--header 'Content-Type: application/json'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,243 @@
|
|||
# 租户管理 API
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | -------------- | --------------------- |
|
||||
| POST | `/tenants` | 创建新租户 |
|
||||
| GET | `/tenants/:id` | 获取指定租户信息 |
|
||||
| PUT | `/tenants/:id` | 更新租户信息 |
|
||||
| DELETE | `/tenants/:id` | 删除租户 |
|
||||
| GET | `/tenants` | 获取租户列表 |
|
||||
|
||||
## POST `/tenants` - 创建新租户
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/tenants' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"name": "weknora",
|
||||
"description": "weknora tenants",
|
||||
"business": "wechat",
|
||||
"retriever_engines": {
|
||||
"engines": [
|
||||
{
|
||||
"retriever_type": "keywords",
|
||||
"retriever_engine_type": "postgres"
|
||||
},
|
||||
{
|
||||
"retriever_type": "vector",
|
||||
"retriever_engine_type": "postgres"
|
||||
}
|
||||
]
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 10000,
|
||||
"name": "weknora",
|
||||
"description": "weknora tenants",
|
||||
"api_key": "sk-aaLRAgvCRJcmtiL2vLMeB1FB5UV0Q-qB7DlTE1pJ9KA93XZG",
|
||||
"status": "active",
|
||||
"retriever_engines": {
|
||||
"engines": [
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "keywords"
|
||||
},
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "vector"
|
||||
}
|
||||
]
|
||||
},
|
||||
"business": "wechat",
|
||||
"storage_quota": 10737418240,
|
||||
"storage_used": 0,
|
||||
"created_at": "2025-08-11T20:37:28.396980093+08:00",
|
||||
"updated_at": "2025-08-11T20:37:28.396980301+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/tenants/:id` - 获取指定租户信息
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/tenants/10000' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-aaLRAgvCRJcmtiL2vLMeB1FB5UV0Q-qB7DlTE1pJ9KA93XZG'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 10000,
|
||||
"name": "weknora",
|
||||
"description": "weknora tenants",
|
||||
"api_key": "sk-aaLRAgvCRJcmtiL2vLMeB1FB5UV0Q-qB7DlTE1pJ9KA93XZG",
|
||||
"status": "active",
|
||||
"retriever_engines": {
|
||||
"engines": [
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "keywords"
|
||||
},
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "vector"
|
||||
}
|
||||
]
|
||||
},
|
||||
"business": "wechat",
|
||||
"storage_quota": 10737418240,
|
||||
"storage_used": 0,
|
||||
"created_at": "2025-08-11T20:37:28.39698+08:00",
|
||||
"updated_at": "2025-08-11T20:37:28.405693+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## PUT `/tenants/:id` - 更新租户信息
|
||||
|
||||
注意 API Key 会变更
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request PUT 'http://localhost:8080/api/v1/tenants/10000' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-KREi84yPtahKxMtIMOW-Cxx2dxb9xROpUuDSpi3vbiC1QVDe' \
|
||||
--data '{
|
||||
"name": "weknora new",
|
||||
"description": "weknora tenants new",
|
||||
"status": "active",
|
||||
"retriever_engines": {
|
||||
"engines": [
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "keywords"
|
||||
},
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "vector"
|
||||
}
|
||||
]
|
||||
},
|
||||
"business": "wechat",
|
||||
"storage_quota": 10737418240
|
||||
}'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 10000,
|
||||
"name": "weknora new",
|
||||
"description": "weknora tenants new",
|
||||
"api_key": "sk-IKtd9JGV4-aPGQ6RiL8YJu9Vzb3-ae4lgFkjFJZmhvUn2mLu",
|
||||
"status": "active",
|
||||
"retriever_engines": {
|
||||
"engines": [
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "keywords"
|
||||
},
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "vector"
|
||||
}
|
||||
]
|
||||
},
|
||||
"business": "wechat",
|
||||
"storage_quota": 10737418240,
|
||||
"storage_used": 0,
|
||||
"created_at": "0001-01-01T00:00:00Z",
|
||||
"updated_at": "2025-08-11T20:49:02.13421034+08:00",
|
||||
"deleted_at": null
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## DELETE `/tenants/:id` - 删除租户
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location --request DELETE 'http://localhost:8080/api/v1/tenants/10000' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-IKtd9JGV4-aPGQ6RiL8YJu9Vzb3-ae4lgFkjFJZmhvUn2mLu'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Tenant deleted successfully",
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/tenants` - 获取租户列表
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/tenants' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'X-API-Key: sk-An7_t_izCKFIJ4iht9Xjcjnj_MC48ILvwezEDki9ScfIa7KA'
|
||||
```
|
||||
|
||||
**响应**:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"items": [
|
||||
{
|
||||
"id": 10002,
|
||||
"name": "weknora",
|
||||
"description": "weknora tenants",
|
||||
"api_key": "sk-An7_t_izCKFIJ4iht9Xjcjnj_MC48ILvwezEDki9ScfIa7KA",
|
||||
"status": "active",
|
||||
"retriever_engines": {
|
||||
"engines": [
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "keywords"
|
||||
},
|
||||
{
|
||||
"retriever_engine_type": "postgres",
|
||||
"retriever_type": "vector"
|
||||
}
|
||||
]
|
||||
},
|
||||
"business": "wechat",
|
||||
"storage_quota": 10737418240,
|
||||
"storage_used": 0,
|
||||
"created_at": "2025-08-11T20:52:58.05679+08:00",
|
||||
"updated_at": "2025-08-11T20:52:58.060495+08:00",
|
||||
"deleted_at": null
|
||||
}
|
||||
]
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
```
|
||||
|
After Width: | Height: | Size: 942 KiB |
|
After Width: | Height: | Size: 14 MiB |
|
After Width: | Height: | Size: 398 KiB |
|
After Width: | Height: | Size: 258 KiB |
|
|
@ -0,0 +1,283 @@
|
|||
# WeKnora 开发指南
|
||||
|
||||
## 快速开发模式(推荐)
|
||||
|
||||
如果你需要频繁修改 `app` 或 `frontend` 代码,**不需要每次都重新构建 Docker 镜像**,可以使用本地开发模式。
|
||||
|
||||
### 方式一:使用 Make 命令(推荐)
|
||||
|
||||
#### 1. 启动基础设施服务
|
||||
|
||||
```bash
|
||||
make dev-start
|
||||
```
|
||||
|
||||
这将启动以下服务的 Docker 容器:
|
||||
- PostgreSQL(数据库)
|
||||
- Redis(缓存)
|
||||
- MinIO(对象存储)
|
||||
- Neo4j(图数据库)
|
||||
- DocReader(文档读取服务)
|
||||
- Jaeger(链路追踪)
|
||||
|
||||
#### 2. 启动后端应用(新终端)
|
||||
|
||||
```bash
|
||||
make dev-app
|
||||
```
|
||||
|
||||
这将在本地直接运行 Go 应用,修改代码后 Ctrl+C 停止,重新运行即可。
|
||||
|
||||
#### 3. 启动前端(新终端)
|
||||
|
||||
```bash
|
||||
make dev-frontend
|
||||
```
|
||||
|
||||
这将启动 Vite 开发服务器,支持热重载,修改代码后自动刷新。
|
||||
|
||||
#### 4. 查看服务状态
|
||||
|
||||
```bash
|
||||
make dev-status
|
||||
```
|
||||
|
||||
#### 5. 停止所有服务
|
||||
|
||||
```bash
|
||||
make dev-stop
|
||||
```
|
||||
|
||||
### 方式二:使用脚本命令
|
||||
|
||||
如果你更喜欢直接使用脚本:
|
||||
|
||||
```bash
|
||||
# 启动基础设施
|
||||
./scripts/dev.sh start
|
||||
|
||||
# 启动后端(新终端)
|
||||
./scripts/dev.sh app
|
||||
|
||||
# 启动前端(新终端)
|
||||
./scripts/dev.sh frontend
|
||||
|
||||
# 查看日志
|
||||
./scripts/dev.sh logs
|
||||
|
||||
# 停止所有服务
|
||||
./scripts/dev.sh stop
|
||||
```
|
||||
|
||||
## 访问地址
|
||||
|
||||
### 开发环境
|
||||
|
||||
- **前端开发服务器**: http://localhost:5173
|
||||
- **后端 API**: http://localhost:8080
|
||||
- **PostgreSQL**: localhost:5432
|
||||
- **Redis**: localhost:6379
|
||||
- **MinIO Console**: http://localhost:9001
|
||||
- **Neo4j Browser**: http://localhost:7474
|
||||
- **Jaeger UI**: http://localhost:16686
|
||||
|
||||
## 开发工作流对比
|
||||
|
||||
### ❌ 旧方式(慢)
|
||||
|
||||
```bash
|
||||
# 每次修改代码后都需要:
|
||||
sh scripts/build_images.sh -p # 重新构建镜像(很慢)
|
||||
sh scripts/start_all.sh --no-pull # 重启容器
|
||||
```
|
||||
|
||||
**耗时**:每次修改需要 2-5 分钟
|
||||
|
||||
### ✅ 新方式(快)
|
||||
|
||||
```bash
|
||||
# 首次启动(只需要一次):
|
||||
make dev-start
|
||||
|
||||
# 在另外两个终端分别运行:
|
||||
make dev-app # 修改 Go 代码后 Ctrl+C 重启即可(秒级)
|
||||
make dev-frontend # 修改前端代码自动热重载(无需重启)
|
||||
```
|
||||
|
||||
**耗时**:
|
||||
- 首次启动:1-2 分钟
|
||||
- 后续修改后端:5-10 秒(重启 Go 应用)
|
||||
- 后续修改前端:实时热重载
|
||||
|
||||
## 使用 Air 实现后端热重载(可选)
|
||||
|
||||
如果你希望后端代码修改后也能自动重启,可以安装 `air`:
|
||||
|
||||
### 1. 安装 Air
|
||||
|
||||
```bash
|
||||
go install github.com/cosmtrek/air@latest
|
||||
```
|
||||
|
||||
### 2. 创建配置文件
|
||||
|
||||
在项目根目录创建 `.air.toml`:
|
||||
|
||||
```toml
|
||||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main ./cmd/server"
|
||||
delay = 1000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
full_bin = ""
|
||||
include_dir = []
|
||||
include_ext = ["go", "tpl", "tmpl", "html", "yaml"]
|
||||
include_file = []
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
poll = false
|
||||
poll_interval = 0
|
||||
rerun = false
|
||||
rerun_delay = 500
|
||||
send_interrupt = false
|
||||
stop_on_error = false
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
main_only = false
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
keep_scroll = true
|
||||
```
|
||||
|
||||
### 3. 使用 Air 启动
|
||||
|
||||
```bash
|
||||
# 在项目根目录
|
||||
air
|
||||
```
|
||||
|
||||
现在修改 Go 代码后会自动重新编译和重启!
|
||||
|
||||
## 其他开发技巧
|
||||
|
||||
### 只修改前端
|
||||
|
||||
如果只修改前端,只需要:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端会连接到 http://localhost:8080 的后端 API。
|
||||
|
||||
### 只修改后端
|
||||
|
||||
如果只修改后端,只需要:
|
||||
|
||||
```bash
|
||||
# 启动基础设施
|
||||
make dev-start
|
||||
|
||||
# 运行后端
|
||||
make dev-app
|
||||
```
|
||||
|
||||
### 调试模式
|
||||
|
||||
#### 后端调试
|
||||
|
||||
使用 VS Code 或 GoLand 的调试功能,配置连接到本地运行的 Go 应用。
|
||||
|
||||
VS Code 配置示例(`.vscode/launch.json`):
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch Server",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}/cmd/server",
|
||||
"env": {
|
||||
"DB_HOST": "localhost",
|
||||
"DOCREADER_ADDR": "localhost:50051",
|
||||
"MINIO_ENDPOINT": "localhost:9000",
|
||||
"REDIS_ADDR": "localhost:6379",
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT": "localhost:4317",
|
||||
"NEO4J_URI": "bolt://localhost:7687"
|
||||
},
|
||||
"args": []
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 前端调试
|
||||
|
||||
使用浏览器开发者工具即可,Vite 提供了 source map。
|
||||
|
||||
## 生产环境部署
|
||||
|
||||
当你完成开发需要部署时,才需要构建镜像:
|
||||
|
||||
```bash
|
||||
# 构建所有镜像
|
||||
sh scripts/build_images.sh
|
||||
|
||||
# 或只构建特定镜像
|
||||
sh scripts/build_images.sh -p # 只构建后端
|
||||
sh scripts/build_images.sh -f # 只构建前端
|
||||
|
||||
# 启动生产环境
|
||||
sh scripts/start_all.sh
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 启动 dev-app 时报错连接不到数据库
|
||||
|
||||
A: 确保先运行了 `make dev-start`,并等待所有服务启动完成(大约 30 秒)。
|
||||
|
||||
### Q: 前端访问 API 时报 CORS 错误
|
||||
|
||||
A: 检查前端的代理配置,确保 `vite.config.ts` 中配置了正确的代理。
|
||||
|
||||
### Q: DocReader 服务需要重新构建怎么办?
|
||||
|
||||
A: DocReader 仍然使用 Docker 镜像,如果需要修改,需要重新构建:
|
||||
|
||||
```bash
|
||||
sh scripts/build_images.sh -d
|
||||
make dev-restart
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
- **日常开发**:使用 `make dev-*` 命令,快速迭代
|
||||
- **测试集成**:使用 `sh scripts/start_all.sh --no-pull` 测试完整环境
|
||||
- **生产部署**:使用 `sh scripts/build_images.sh` + `sh scripts/start_all.sh`
|
||||
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
# 开启知识图谱功能指南
|
||||
|
||||
本文档介绍如何在 WeKnora 中启用并验证知识图谱(Neo4j)功能,帮助你完成从环境准备到前端配置的全流程。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 已完成 WeKnora 后端与前端的基础部署。
|
||||
- 具备可用的 Docker/Docker Compose 运行环境。
|
||||
- 本地或远端可访问的 Neo4j 服务(推荐使用项目自带的 Docker Compose)。
|
||||
|
||||
## 步骤一:配置环境变量
|
||||
|
||||
在项目根目录的 `.env` 文件中新增或修改以下变量:
|
||||
|
||||
```
|
||||
NEO4J_ENABLE=true
|
||||
NEO4J_URI=bolt://neo4j:7687
|
||||
NEO4J_USERNAME=neo4j
|
||||
NEO4J_PASSWORD=your_strong_password
|
||||
# 可选:NEO4J_DATABASE=neo4j
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `NEO4J_ENABLE` 设置为 `true` 才会启用知识图谱相关逻辑。
|
||||
- `NEO4J_URI` 中的 `neo4j` 为 docker-compose 服务名,如使用外部实例请替换为实际地址。
|
||||
- 如果生产环境使用密钥管理,请确保密码通过安全方式注入。
|
||||
|
||||
## 步骤二:启动 Neo4j 服务
|
||||
|
||||
项目附带 Neo4j 组件,可直接用以下命令启动:
|
||||
|
||||
```bash
|
||||
docker-compose --profile neo4j up -d
|
||||
```
|
||||
|
||||
常见验证命令:
|
||||
|
||||
```bash
|
||||
docker ps | grep neo4j
|
||||
```
|
||||
|
||||
若需要自定义挂载或内存,可编辑 `docker-compose.yml` 中 `neo4j` 服务配置。
|
||||
|
||||
## 步骤三:重启 WeKnora 服务
|
||||
|
||||
为了让新的环境变量生效,重启后端与前端(示例仅供参考):
|
||||
|
||||
```bash
|
||||
make stop && make start
|
||||
# 或者
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
确保后端日志中出现 `neo4j` 初始化成功的提示。
|
||||
|
||||
## 步骤四:在前端启用实体/关系抽取
|
||||
|
||||
1. 登录 WeKnora 前端管理页面。
|
||||
2. 打开「知识库设置」或创建新的知识库。
|
||||
3. 勾选「启用实体抽取」与「启用关系抽取」开关。
|
||||
4. 根据界面提示补充所需的 LLM、回调或模型参数(若有)。
|
||||
|
||||
保存后,系统会在文档入库阶段自动触发实体与关系抽取任务。
|
||||
|
||||
## 步骤五:验证知识图谱
|
||||
|
||||
### 方式一:Neo4j 控制台
|
||||
|
||||
1. 访问 `http://localhost:7474`(或对应主机/端口)。
|
||||
2. 使用 `.env` 中的账号密码登录。
|
||||
3. 执行 `MATCH (n) RETURN n LIMIT 50;` 检查是否有新节点/关系。
|
||||
|
||||
### 方式二:WeKnora 界面
|
||||
|
||||
在知识库或对话页面中上传文档后,前端应展示图谱可视化入口;对话时系统会自动根据意图查询图谱并返回补充信息。
|
||||
|
||||
## 常见问题排查
|
||||
|
||||
- **无法连接 Neo4j**:确认网络可达、`NEO4J_URI` 与用户名密码正确,并检查 Neo4j 容器日志。
|
||||
- **未生成节点**:确认知识库已开启实体/关系抽取,且上传的文档已完成解析;查看后端日志中是否有抽取任务异常。
|
||||
- **查询无结果**:尝试在 Neo4j 控制台执行 `CALL db.schema.visualization;` 查看 schema 是否存在,必要时重新导入文档。
|
||||
|
||||
完成以上步骤后,知识图谱功能即成功启用,可结合 RAG 及 Agent 流程提升问答质量。
|
||||
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
# 快速开发模式说明
|
||||
|
||||
解决开发流程中,每次修改 `app`(后端)或 `frontend`(前端)代码后,都需要打包Docker镜像的问题,实现这两个模块的热更新
|
||||
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 方式 1:使用 Make 命令(推荐)
|
||||
|
||||
```bash
|
||||
# 终端 1:启动基础设施
|
||||
make dev-start
|
||||
|
||||
# 终端 2:启动后端
|
||||
make dev-app
|
||||
|
||||
# 终端 3:启动前端
|
||||
make dev-frontend
|
||||
```
|
||||
|
||||
### 方式 2:使用开发脚本
|
||||
|
||||
```bash
|
||||
# 终端 1
|
||||
./scripts/dev.sh start
|
||||
|
||||
# 终端 2
|
||||
./scripts/dev.sh app
|
||||
|
||||
# 终端 3
|
||||
./scripts/dev.sh frontend
|
||||
```
|
||||
|
||||
### 方式 3:一键启动(交互式)
|
||||
|
||||
```bash
|
||||
./scripts/quick-dev.sh
|
||||
```
|
||||
|
||||
|
||||
|
||||
### 使用 Air 实现后端热重载
|
||||
|
||||
安装 Air 后,后端代码修改会自动重新编译和重启:
|
||||
|
||||
```bash
|
||||
# 安装 Air
|
||||
go install github.com/cosmtrek/air@latest
|
||||
|
||||
# 确保在 PATH 中
|
||||
export PATH=$PATH:$(go env GOPATH)/bin
|
||||
|
||||
# 使用 Air 启动(自动检测)
|
||||
make dev-app
|
||||
```
|
||||
|
||||
|
||||
## 🔄 架构说明
|
||||
|
||||
### 开发模式架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ 本地开发环境 │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ 后端 App │◄────────┤ 前端 UI │ │
|
||||
│ │ (本地运行)│ │ (本地运行)│ │
|
||||
│ │ :8080 │ │ :5173 │ │
|
||||
│ └────┬─────┘ └──────────┘ │
|
||||
│ │ │
|
||||
│ │ 连接基础设施服务 │
|
||||
│ ▼ │
|
||||
│ ┌─────────────────────────────────────────────────┐ │
|
||||
│ │ Docker 基础设施容器 │ │
|
||||
│ ├─────────────────────────────────────────────────┤ │
|
||||
│ │ PostgreSQL │ Redis │ MinIO │ Neo4j │ DocReader │ │
|
||||
│ │ :5432 │ :6379 │ :9000 │ :7687 │ :50051 │ │
|
||||
│ └─────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 生产模式架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Docker Compose 环境 │
|
||||
├─────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ 后端 App │◄────────┤ 前端 UI │ │
|
||||
│ │ (容器运行)│ │ (容器运行)│ │
|
||||
│ │ :8080 │ │ :80 │ │
|
||||
│ └────┬─────┘ └──────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌─────────────────────────────────────────────────┐ │
|
||||
│ │ 基础设施容器 │ │
|
||||
│ ├─────────────────────────────────────────────────┤ │
|
||||
│ │ PostgreSQL │ Redis │ MinIO │ Neo4j │ DocReader │ │
|
||||
│ └─────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
|
@ -9,6 +9,7 @@ ENV VITE_IS_DOCKER=true
|
|||
|
||||
# 复制依赖文件
|
||||
COPY package*.json ./
|
||||
COPY packages/xlsx-0.20.2.tgz ./packages/xlsx-0.20.2.tgz
|
||||
|
||||
# 安装依赖
|
||||
RUN corepack enable
|
||||
|
|
|
|||
|
|
@ -10,16 +10,21 @@
|
|||
"dependencies": {
|
||||
"@microsoft/fetch-event-source": "^2.0.1",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/papaparse": "^5.5.0",
|
||||
"axios": "^1.8.4",
|
||||
"dompurify": "^3.2.6",
|
||||
"marked": "^5.1.2",
|
||||
"pagefind": "^1.1.1",
|
||||
"papaparse": "^5.5.3",
|
||||
"pinia": "^3.0.1",
|
||||
"swiper": "^12.0.3",
|
||||
"tdesign-icons-vue-next": "^0.4.1",
|
||||
"tdesign-vue-next": "^1.11.5",
|
||||
"tdesign-vue-next": "^1.17.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-i18n": "^11.1.12",
|
||||
"vue-router": "^4.5.0",
|
||||
"webpack": "^5.94.0"
|
||||
"webpack": "^5.94.0",
|
||||
"xlsx": "file:./packages/xlsx-0.20.2.tgz"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node22": "^22.0.1",
|
||||
|
|
@ -32,7 +37,7 @@
|
|||
"less-loader": "^12.2.0",
|
||||
"npm-run-all2": "^7.0.2",
|
||||
"typescript": "~5.8.0",
|
||||
"vite": "7.0.4",
|
||||
"vite": "^7.2.2",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
},
|
||||
|
|
@ -870,6 +875,50 @@
|
|||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@intlify/core-base": {
|
||||
"version": "11.1.12",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@intlify/core-base/-/core-base-11.1.12.tgz",
|
||||
"integrity": "sha512-whh0trqRsSqVLNEUCwU59pyJZYpU8AmSWl8M3Jz2Mv5ESPP6kFh4juas2NpZ1iCvy7GlNRffUD1xr84gceimjg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@intlify/message-compiler": "11.1.12",
|
||||
"@intlify/shared": "11.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/kazupon"
|
||||
}
|
||||
},
|
||||
"node_modules/@intlify/message-compiler": {
|
||||
"version": "11.1.12",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@intlify/message-compiler/-/message-compiler-11.1.12.tgz",
|
||||
"integrity": "sha512-Fv9iQSJoJaXl4ZGkOCN1LDM3trzze0AS2zRz2EHLiwenwL6t0Ki9KySYlyr27yVOj5aVz0e55JePO+kELIvfdQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@intlify/shared": "11.1.12",
|
||||
"source-map-js": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/kazupon"
|
||||
}
|
||||
},
|
||||
"node_modules/@intlify/shared": {
|
||||
"version": "11.1.12",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@intlify/shared/-/shared-11.1.12.tgz",
|
||||
"integrity": "sha512-Om86EjuQtA69hdNj3GQec9ZC0L0vPSAnXzB3gP/gyJ7+mA7t06d9aOAiqMZ+xEOsumGP4eEBlfl8zF2LOTzf2A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/kazupon"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.12",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@jridgewell/gen-mapping/-/gen-mapping-0.3.12.tgz",
|
||||
|
|
@ -1347,6 +1396,15 @@
|
|||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/papaparse": {
|
||||
"version": "5.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.5.0.tgz",
|
||||
"integrity": "sha512-GVs5iMQmUr54BAZYYkByv8zPofFxmyxUpISPb2oh8sayR3+1zbxasrOvoKiHJ/nnoq/uULuPsu1Lze1EkagVFg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/sortablejs": {
|
||||
"version": "1.15.8",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@types/sortablejs/-/sortablejs-1.15.8.tgz",
|
||||
|
|
@ -1916,12 +1974,13 @@
|
|||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/axios/-/axios-1.10.0.tgz",
|
||||
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/axios/-/axios-1.13.2.tgz",
|
||||
"integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
"form-data": "^4.0.4",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
|
|
@ -2031,6 +2090,7 @@
|
|||
"version": "1.0.8",
|
||||
"resolved": "https://mirrors.tencent.com/npm/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
},
|
||||
|
|
@ -2135,6 +2195,7 @@
|
|||
"version": "1.0.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
|
|
@ -2152,6 +2213,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
|
|
@ -2207,6 +2269,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
|
|
@ -2215,7 +2278,6 @@
|
|||
"version": "1.3.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
|
|
@ -2240,6 +2302,7 @@
|
|||
"version": "2.1.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.6",
|
||||
|
|
@ -2376,10 +2439,14 @@
|
|||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://mirrors.tencent.com/npm/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
|
|
@ -2410,10 +2477,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://mirrors.tencent.com/npm/form-data/-/form-data-4.0.3.tgz",
|
||||
"integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==",
|
||||
"license": "MIT",
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://mirrors.tencent.com/npm/form-data/-/form-data-4.0.4.tgz",
|
||||
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
|
|
@ -2461,6 +2527,7 @@
|
|||
"version": "1.3.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
|
|
@ -2484,6 +2551,7 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
|
|
@ -2540,6 +2608,7 @@
|
|||
"version": "1.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-symbols": "^1.0.3"
|
||||
},
|
||||
|
|
@ -2554,7 +2623,6 @@
|
|||
"version": "2.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/hasown/-/hasown-2.0.2.tgz",
|
||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
|
|
@ -2804,6 +2872,7 @@
|
|||
"version": "1.1.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
|
|
@ -2988,6 +3057,12 @@
|
|||
"@pagefind/windows-x64": "1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/papaparse": {
|
||||
"version": "5.5.3",
|
||||
"resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.3.tgz",
|
||||
"integrity": "sha512-5QvjGxYVjxO59MGU2lHVYpRWBBtKHnlIAcSe1uNFCkkptUh63NFRj0FJQm7nR67puEruUci/ZkjmEFrjCAyP4A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/parse-node-version": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/parse-node-version/-/parse-node-version-1.0.1.tgz",
|
||||
|
|
@ -3024,10 +3099,11 @@
|
|||
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.2.tgz",
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
|
|
@ -3392,6 +3468,25 @@
|
|||
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/swiper": {
|
||||
"version": "12.0.3",
|
||||
"resolved": "https://registry.npmjs.org/swiper/-/swiper-12.0.3.tgz",
|
||||
"integrity": "sha512-BHd6U1VPEIksrXlyXjMmRWO0onmdNPaTAFduzqR3pgjvi7KfmUCAm/0cj49u2D7B0zNjMw02TSeXfinC1hDCXg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/swiperjs"
|
||||
},
|
||||
{
|
||||
"type": "open_collective",
|
||||
"url": "http://opencollective.com/swiper"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4.7.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tapable": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/tapable/-/tapable-2.2.2.tgz",
|
||||
|
|
@ -3413,9 +3508,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/tdesign-vue-next": {
|
||||
"version": "1.14.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/tdesign-vue-next/-/tdesign-vue-next-1.14.2.tgz",
|
||||
"integrity": "sha512-Wcg0SjT4W7JmMhwCI4/rnk8bJzcmjed/YAemVDaOY33U8PqUsU3DxxP/vJ2gbLH7NkFgLGVNpeAdTqYdmHnV4w==",
|
||||
"version": "1.17.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/tdesign-vue-next/-/tdesign-vue-next-1.17.2.tgz",
|
||||
"integrity": "sha512-nTofPSKGQguOS+Lb62fDiLS1Rs3Ngzb8rE8sPEjfMdDjdFZ5kEUgvVp+J+8GKfgwVRAZRjv//qSzZVt6cqgXxA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.22.6",
|
||||
"@popperjs/core": "^2.11.8",
|
||||
|
|
@ -3423,11 +3519,11 @@
|
|||
"@types/sortablejs": "^1.15.1",
|
||||
"@types/tinycolor2": "^1.4.3",
|
||||
"@types/validator": "^13.7.17",
|
||||
"dayjs": "1.11.10",
|
||||
"dayjs": "^1.11.10",
|
||||
"lodash-es": "^4.17.21",
|
||||
"mitt": "^3.0.1",
|
||||
"sortablejs": "^1.15.0",
|
||||
"tdesign-icons-vue-next": "^0.3.6",
|
||||
"tdesign-icons-vue-next": "~0.4.1",
|
||||
"tinycolor2": "^1.6.0",
|
||||
"validator": "^13.9.0"
|
||||
},
|
||||
|
|
@ -3438,18 +3534,6 @@
|
|||
"vue": ">=3.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tdesign-vue-next/node_modules/tdesign-icons-vue-next": {
|
||||
"version": "0.3.7",
|
||||
"resolved": "https://mirrors.tencent.com/npm/tdesign-icons-vue-next/-/tdesign-icons-vue-next-0.3.7.tgz",
|
||||
"integrity": "sha512-Q5ebVty/TCqhBa0l/17kkhjC0pBAOGvn7C35MAt1xS+johKVM9QEDOy9R6XEl332AiwQ37MwqioczqjYC30ckw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.16.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/terser": {
|
||||
"version": "5.43.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/terser/-/terser-5.43.1.tgz",
|
||||
|
|
@ -3508,14 +3592,14 @@
|
|||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://mirrors.tencent.com/npm/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://mirrors.tencent.com/npm/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
|
|
@ -3579,25 +3663,27 @@
|
|||
}
|
||||
},
|
||||
"node_modules/validator": {
|
||||
"version": "13.15.15",
|
||||
"resolved": "https://mirrors.tencent.com/npm/validator/-/validator-13.15.15.tgz",
|
||||
"integrity": "sha512-BgWVbCI72aIQy937xbawcs+hrVaN/CZ2UwutgaJ36hGqRrLNM+f5LUT/YPRbo8IV/ASeFzXszezV+y2+rq3l8A==",
|
||||
"version": "13.15.23",
|
||||
"resolved": "https://mirrors.tencent.com/npm/validator/-/validator-13.15.23.tgz",
|
||||
"integrity": "sha512-4yoz1kEWqUjzi5zsPbAS/903QXSYp0UOtHsPpp7p9rHAw/W+dkInskAE386Fat3oKRROwO98d9ZB0G4cObgUyw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.0.4",
|
||||
"resolved": "https://mirrors.tencent.com/npm/vite/-/vite-7.0.4.tgz",
|
||||
"integrity": "sha512-SkaSguuS7nnmV7mfJ8l81JGBFV7Gvzp8IzgE8A8t23+AxuNX61Q5H1Tpz5efduSN7NHC8nQXD3sKQKZAu5mNEA==",
|
||||
"version": "7.2.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/vite/-/vite-7.2.2.tgz",
|
||||
"integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.6",
|
||||
"picomatch": "^4.0.2",
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.40.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.15"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
|
|
@ -3688,6 +3774,31 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vue-i18n": {
|
||||
"version": "11.1.12",
|
||||
"resolved": "https://mirrors.tencent.com/npm/vue-i18n/-/vue-i18n-11.1.12.tgz",
|
||||
"integrity": "sha512-BnstPj3KLHLrsqbVU2UOrPmr0+Mv11bsUZG0PyCOzsawCivk8W00GMXHeVUWIDOgNaScCuZah47CZFE+Wnl8mw==",
|
||||
"dependencies": {
|
||||
"@intlify/core-base": "11.1.12",
|
||||
"@intlify/shared": "11.1.12",
|
||||
"@vue/devtools-api": "^6.5.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/kazupon"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue-i18n/node_modules/@vue/devtools-api": {
|
||||
"version": "6.6.4",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
|
||||
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vue-router": {
|
||||
"version": "4.5.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/vue-router/-/vue-router-4.5.1.tgz",
|
||||
|
|
@ -3811,6 +3922,18 @@
|
|||
"node": "^18.17.0 || >=20.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xlsx": {
|
||||
"version": "0.20.2",
|
||||
"resolved": "file:packages/xlsx-0.20.2.tgz",
|
||||
"integrity": "sha512-+nKZ39+nvK7Qq6i0PvWWRA4j/EkfWOtkP/YhMtupm+lJIiHxUrgTr1CcKv1nBk1rHtkRRQ3O2+Ih/q/sA+FXZA==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"xlsx": "bin/xlsx.njs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/yallist/-/yallist-3.1.1.tgz",
|
||||
|
|
|
|||
|
|
@ -14,17 +14,21 @@
|
|||
"dependencies": {
|
||||
"@microsoft/fetch-event-source": "^2.0.1",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/papaparse": "^5.5.0",
|
||||
"axios": "^1.8.4",
|
||||
"dompurify": "^3.2.6",
|
||||
"marked": "^5.1.2",
|
||||
"pagefind": "^1.1.1",
|
||||
"papaparse": "^5.5.3",
|
||||
"pinia": "^3.0.1",
|
||||
"swiper": "^12.0.3",
|
||||
"tdesign-icons-vue-next": "^0.4.1",
|
||||
"tdesign-vue-next": "^1.11.5",
|
||||
"tdesign-vue-next": "^1.17.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-i18n": "^9.9.0",
|
||||
"vue-i18n": "^11.1.12",
|
||||
"vue-router": "^4.5.0",
|
||||
"webpack": "^5.94.0"
|
||||
"webpack": "^5.94.0",
|
||||
"xlsx": "file:./packages/xlsx-0.20.2.tgz"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node22": "^22.0.1",
|
||||
|
|
@ -37,7 +41,7 @@
|
|||
"less-loader": "^12.2.0",
|
||||
"npm-run-all2": "^7.0.2",
|
||||
"typescript": "~5.8.0",
|
||||
"vite": "7.0.4",
|
||||
"vite": "^7.2.2",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"overrides": {
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
# 临时创建的 packages 目录
|
||||
|
|
@ -1,31 +1,11 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ConfigProvider } from 'tdesign-vue-next'
|
||||
import enUS from 'tdesign-vue-next/es/locale/en_US'
|
||||
import zhCN from 'tdesign-vue-next/es/locale/zh_CN'
|
||||
import ruRU from 'tdesign-vue-next/es/locale/ru_RU'
|
||||
|
||||
const { locale } = useI18n()
|
||||
|
||||
const tdesignLocale = computed(() => {
|
||||
switch (locale.value) {
|
||||
case 'en-US':
|
||||
return enUS
|
||||
case 'ru-RU':
|
||||
return ruRU
|
||||
case 'zh-CN':
|
||||
default:
|
||||
return zhCN
|
||||
}
|
||||
})
|
||||
import ManualKnowledgeEditor from '@/components/manual-knowledge-editor.vue'
|
||||
</script>
|
||||
<template>
|
||||
<ConfigProvider :global-config="tdesignLocale">
|
||||
<div id="app">
|
||||
<RouterView />
|
||||
</div>
|
||||
</ConfigProvider>
|
||||
<div id="app">
|
||||
<RouterView />
|
||||
<ManualKnowledgeEditor />
|
||||
</div>
|
||||
</template>
|
||||
<style>
|
||||
body,
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export interface LoginResponse {
|
|||
email: string
|
||||
avatar?: string
|
||||
tenant_id: number
|
||||
can_access_all_tenants?: boolean
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
|
|
@ -66,6 +67,7 @@ export interface UserInfo {
|
|||
email: string
|
||||
avatar?: string
|
||||
tenant_id: string
|
||||
can_access_all_tenants?: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,20 @@ export async function knowledgeChat(data: { session_id: string; query: string; }
|
|||
return postChat(`/api/v1/knowledge-chat/${data.session_id}`, { query: data.query });
|
||||
}
|
||||
|
||||
// Agent chat with streaming support
|
||||
export async function agentChat(data: {
|
||||
session_id: string;
|
||||
query: string;
|
||||
knowledge_base_ids?: string[];
|
||||
agent_enabled: boolean;
|
||||
}) {
|
||||
return postChat(`/api/v1/agent-chat/${data.session_id}`, {
|
||||
query: data.query,
|
||||
knowledge_base_ids: data.knowledge_base_ids,
|
||||
agent_enabled: data.agent_enabled
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMessageList(data: { session_id: string; limit: number, created_at: string }) {
|
||||
if (data.created_at) {
|
||||
return get(`/api/v1/messages/${data.session_id}/load?before_time=${encodeURIComponent(data.created_at)}&limit=${data.limit}`);
|
||||
|
|
@ -28,4 +42,12 @@ export async function getMessageList(data: { session_id: string; limit: number,
|
|||
|
||||
export async function delSession(session_id: string) {
|
||||
return del(`/api/v1/sessions/${session_id}`);
|
||||
}
|
||||
|
||||
export async function getSession(session_id: string) {
|
||||
return get(`/api/v1/sessions/${session_id}`);
|
||||
}
|
||||
|
||||
export async function stopSession(session_id: string, message_id: string) {
|
||||
return post(`/api/v1/sessions/${session_id}/stop`, { message_id });
|
||||
}
|
||||
|
|
@ -28,7 +28,7 @@ export function useStream() {
|
|||
let renderTimer: number | null = null
|
||||
|
||||
// 启动流式请求
|
||||
const startStream = async (params: { session_id: any; query: any; method: string; url: string }) => {
|
||||
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; method: string; url: string }) => {
|
||||
// 重置状态
|
||||
output.value = '';
|
||||
error.value = null;
|
||||
|
|
@ -46,21 +46,69 @@ export function useStream() {
|
|||
return;
|
||||
}
|
||||
|
||||
// 获取跨租户访问请求头
|
||||
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
|
||||
const defaultTenantId = localStorage.getItem('weknora_tenant');
|
||||
let tenantIdHeader: string | null = null;
|
||||
if (selectedTenantId) {
|
||||
try {
|
||||
const defaultTenant = defaultTenantId ? JSON.parse(defaultTenantId) : null;
|
||||
const defaultId = defaultTenant?.id ? String(defaultTenant.id) : null;
|
||||
if (selectedTenantId !== defaultId) {
|
||||
tenantIdHeader = selectedTenantId;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse tenant info', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate knowledge_base_ids for agent-chat requests
|
||||
// Note: knowledge_base_ids can be empty if user hasn't selected any, but we allow it
|
||||
// The backend will handle the case when no knowledge bases are selected
|
||||
const isAgentChat = params.url === '/api/v1/agent-chat';
|
||||
// Removed validation - allow empty knowledge_base_ids array
|
||||
// The backend should handle this case appropriately
|
||||
|
||||
try {
|
||||
let url =
|
||||
params.method == "POST"
|
||||
? `${apiUrl}${params.url}/${params.session_id}`
|
||||
: `${apiUrl}${params.url}/${params.session_id}?message_id=${params.query}`;
|
||||
|
||||
// Prepare POST body with required fields for agent-chat
|
||||
// knowledge_base_ids array and agent_enabled can update Session's SessionAgentConfig
|
||||
const postBody: any = {
|
||||
query: params.query,
|
||||
agent_enabled: params.agent_enabled !== undefined ? params.agent_enabled : true
|
||||
};
|
||||
// Always include knowledge_base_ids for agent-chat (already validated above)
|
||||
if (params.knowledge_base_ids !== undefined && params.knowledge_base_ids.length > 0) {
|
||||
postBody.knowledge_base_ids = params.knowledge_base_ids;
|
||||
}
|
||||
// Include web_search_enabled if provided
|
||||
if (params.web_search_enabled !== undefined) {
|
||||
postBody.web_search_enabled = params.web_search_enabled;
|
||||
}
|
||||
// Include summary_model_id if provided (for non-Agent mode)
|
||||
if (params.summary_model_id) {
|
||||
postBody.summary_model_id = params.summary_model_id;
|
||||
}
|
||||
// Include mcp_service_ids if provided (for Agent mode)
|
||||
if (params.mcp_service_ids !== undefined && params.mcp_service_ids.length > 0) {
|
||||
postBody.mcp_service_ids = params.mcp_service_ids;
|
||||
}
|
||||
|
||||
await fetchEventSource(url, {
|
||||
method: params.method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${token}`,
|
||||
"X-Request-ID": `${generateRandomString(12)}`,
|
||||
...(tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
|
||||
},
|
||||
body:
|
||||
params.method == "POST"
|
||||
? JSON.stringify({ query: params.query })
|
||||
? JSON.stringify(postBody)
|
||||
: null,
|
||||
signal: controller.signal,
|
||||
openWhenHidden: true,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { get, post } from '../../utils/request';
|
||||
import { get, post, put } from '../../utils/request';
|
||||
|
||||
// 初始化配置数据类型
|
||||
export interface InitializationConfig {
|
||||
|
|
@ -70,7 +70,65 @@ export interface DownloadTask {
|
|||
endTime?: string;
|
||||
}
|
||||
|
||||
// 根据知识库ID执行配置更新
|
||||
// 简化版知识库配置更新接口(只传模型ID)
|
||||
export interface KBModelConfigRequest {
|
||||
llmModelId: string
|
||||
embeddingModelId: string
|
||||
vlm_config?: {
|
||||
enabled: boolean
|
||||
model_id?: string
|
||||
}
|
||||
documentSplitting: {
|
||||
chunkSize: number
|
||||
chunkOverlap: number
|
||||
separators: string[]
|
||||
}
|
||||
multimodal: {
|
||||
enabled: boolean
|
||||
storageType?: 'cos' | 'minio'
|
||||
cos?: {
|
||||
secretId: string
|
||||
secretKey: string
|
||||
region: string
|
||||
bucketName: string
|
||||
appId: string
|
||||
pathPrefix: string
|
||||
}
|
||||
minio?: {
|
||||
bucketName: string
|
||||
useSSL: boolean
|
||||
pathPrefix: string
|
||||
}
|
||||
}
|
||||
nodeExtract: {
|
||||
enabled: boolean
|
||||
text: string
|
||||
tags: string[]
|
||||
nodes: Node[]
|
||||
relations: Relation[]
|
||||
}
|
||||
questionGeneration?: {
|
||||
enabled: boolean
|
||||
questionCount: number
|
||||
}
|
||||
}
|
||||
|
||||
export function updateKBConfig(kbId: string, config: KBModelConfigRequest): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('开始知识库配置更新(简化版)...', kbId, config);
|
||||
put(`/api/v1/initialization/config/${kbId}`, config)
|
||||
.then((response: any) => {
|
||||
console.log('知识库配置更新完成', response);
|
||||
resolve(response);
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('知识库配置更新失败:', error);
|
||||
reject(error.error || error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 根据知识库ID执行配置更新(旧版,保留兼容性)
|
||||
export function initializeSystemByKB(kbId: string, config: InitializationConfig): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('开始知识库配置更新...', kbId, config);
|
||||
|
|
@ -100,8 +158,16 @@ export function checkOllamaStatus(): Promise<{ available: boolean; version?: str
|
|||
});
|
||||
}
|
||||
|
||||
// 列出已安装的 Ollama 模型
|
||||
export function listOllamaModels(): Promise<string[]> {
|
||||
// Ollama 模型详细信息接口
|
||||
export interface OllamaModelInfo {
|
||||
name: string;
|
||||
size: number;
|
||||
digest: string;
|
||||
modified_at: string;
|
||||
}
|
||||
|
||||
// 列出已安装的 Ollama 模型(详细信息)
|
||||
export function listOllamaModels(): Promise<OllamaModelInfo[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get('/api/v1/initialization/ollama/models')
|
||||
.then((response: any) => {
|
||||
|
|
@ -310,6 +376,21 @@ export function testMultimodalFunction(testData: {
|
|||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// 添加跨租户访问请求头(如果选择了其他租户)
|
||||
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
|
||||
const defaultTenantId = localStorage.getItem('weknora_tenant');
|
||||
if (selectedTenantId) {
|
||||
try {
|
||||
const defaultTenant = defaultTenantId ? JSON.parse(defaultTenantId) : null;
|
||||
const defaultId = defaultTenant?.id ? String(defaultTenant.id) : null;
|
||||
if (selectedTenantId !== defaultId) {
|
||||
headers['X-Tenant-ID'] = selectedTenantId;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to parse tenant info', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 使用原生fetch因为需要发送FormData
|
||||
fetch('/api/v1/initialization/multimodal/test', {
|
||||
method: 'POST',
|
||||
|
|
@ -335,7 +416,7 @@ export function testMultimodalFunction(testData: {
|
|||
export interface TextRelationExtractionRequest {
|
||||
text: string;
|
||||
tags: string[];
|
||||
llmConfig: LLMConfig;
|
||||
llm_config: LLMConfig;
|
||||
}
|
||||
|
||||
export interface Node {
|
||||
|
|
@ -351,9 +432,9 @@ export interface Relation {
|
|||
|
||||
export interface LLMConfig {
|
||||
source: 'local' | 'remote';
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model_name: string;
|
||||
base_url: string;
|
||||
api_key: string;
|
||||
}
|
||||
|
||||
export interface TextRelationExtractionResponse {
|
||||
|
|
@ -364,7 +445,7 @@ export interface TextRelationExtractionResponse {
|
|||
// 文本内容关系提取
|
||||
export function extractTextRelations(request: TextRelationExtractionRequest): Promise<TextRelationExtractionResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/extract/text-relation', request)
|
||||
post('/api/v1/initialization/extract/text-relation', request, { timeout: 60000 })
|
||||
.then((response: any) => {
|
||||
resolve(response.data || { nodes: [], relations: [] });
|
||||
})
|
||||
|
|
@ -377,7 +458,7 @@ export function extractTextRelations(request: TextRelationExtractionRequest): Pr
|
|||
|
||||
export interface FabriTextRequest {
|
||||
tags: string[];
|
||||
llmConfig: LLMConfig;
|
||||
llm_config: LLMConfig;
|
||||
}
|
||||
|
||||
export interface FabriTextResponse {
|
||||
|
|
@ -399,7 +480,7 @@ export function fabriText(request: FabriTextRequest): Promise<FabriTextResponse>
|
|||
}
|
||||
|
||||
export interface FabriTagRequest {
|
||||
llmConfig: LLMConfig;
|
||||
llm_config: LLMConfig;
|
||||
}
|
||||
|
||||
export interface FabriTagResponse {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,21 @@ export function listKnowledgeBases() {
|
|||
return get(`/api/v1/knowledge-bases`);
|
||||
}
|
||||
|
||||
export function createKnowledgeBase(data: { name: string; description?: string; chunking_config?: any }) {
|
||||
export function createKnowledgeBase(data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
type?: 'document' | 'faq';
|
||||
chunking_config?: any;
|
||||
embedding_model_id?: string;
|
||||
summary_model_id?: string;
|
||||
vlm_config?: {
|
||||
enabled: boolean;
|
||||
model_id?: string;
|
||||
};
|
||||
cos_config?: any;
|
||||
extract_config?: any;
|
||||
faq_config?: { index_mode: string; question_index_mode?: string };
|
||||
}) {
|
||||
return post(`/api/v1/knowledge-bases`, data);
|
||||
}
|
||||
|
||||
|
|
@ -26,18 +40,46 @@ export function copyKnowledgeBase(data: { source_id: string; target_id?: string
|
|||
}
|
||||
|
||||
// 知识文件 API(基于具体知识库)
|
||||
export function uploadKnowledgeFile(kbId: string, data = {}) {
|
||||
return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, data);
|
||||
export function uploadKnowledgeFile(kbId: string, data = {}, onProgress?: (progressEvent: any) => void) {
|
||||
return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, data, onProgress);
|
||||
}
|
||||
|
||||
export function listKnowledgeFiles(kbId: string, { page, page_size }: { page: number; page_size: number }) {
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?page=${page}&page_size=${page_size}`);
|
||||
export function createKnowledgeFromURL(kbId: string, data: { url: string; enable_multimodel?: boolean }) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/knowledge/url`, data);
|
||||
}
|
||||
|
||||
export function createManualKnowledge(kbId: string, data: { title: string; content: string; status: string }) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/knowledge/manual`, data);
|
||||
}
|
||||
|
||||
export function listKnowledgeFiles(
|
||||
kbId: string,
|
||||
params: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string },
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
query.append('page', String(params.page));
|
||||
query.append('page_size', String(params.page_size));
|
||||
if (params.tag_id) {
|
||||
query.append('tag_id', params.tag_id);
|
||||
}
|
||||
if (params.keyword) {
|
||||
query.append('keyword', params.keyword);
|
||||
}
|
||||
if (params.file_type) {
|
||||
query.append('file_type', params.file_type);
|
||||
}
|
||||
const qs = query.toString();
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`);
|
||||
}
|
||||
|
||||
export function getKnowledgeDetails(id: string) {
|
||||
return get(`/api/v1/knowledge/${id}`);
|
||||
}
|
||||
|
||||
export function updateManualKnowledge(id: string, data: { title: string; content: string; status: string }) {
|
||||
return put(`/api/v1/knowledge/manual/${id}`, data);
|
||||
}
|
||||
|
||||
export function delKnowledgeDetails(id: string) {
|
||||
return del(`/api/v1/knowledge/${id}`);
|
||||
}
|
||||
|
|
@ -52,4 +94,100 @@ export function batchQueryKnowledge(idsQueryString: string) {
|
|||
|
||||
export function getKnowledgeDetailsCon(id: string, page: number) {
|
||||
return get(`/api/v1/chunks/${id}?page=${page}&page_size=25`);
|
||||
}
|
||||
|
||||
// Get chunk by chunk_id only (new endpoint - to be added to backend)
|
||||
export function getChunkByIdOnly(chunkId: string) {
|
||||
return get(`/api/v1/chunks/by-id/${chunkId}`);
|
||||
}
|
||||
|
||||
// Delete a single generated question from a chunk by question ID
|
||||
export function deleteGeneratedQuestion(chunkId: string, questionId: string) {
|
||||
return del(`/api/v1/chunks/by-id/${chunkId}/questions`, { question_id: questionId });
|
||||
}
|
||||
|
||||
export function listKnowledgeTags(
|
||||
kbId: string,
|
||||
params?: { page?: number; page_size?: number; keyword?: string },
|
||||
) {
|
||||
const query = buildQuery(params);
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/tags${query}`);
|
||||
}
|
||||
|
||||
export function createKnowledgeBaseTag(
|
||||
kbId: string,
|
||||
data: { name: string; color?: string; sort_order?: number },
|
||||
) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/tags`, data);
|
||||
}
|
||||
|
||||
export function updateKnowledgeBaseTag(
|
||||
kbId: string,
|
||||
tagId: string,
|
||||
data: { name?: string; color?: string; sort_order?: number },
|
||||
) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}`, data);
|
||||
}
|
||||
|
||||
export function deleteKnowledgeBaseTag(kbId: string, tagId: string, params?: { force?: boolean }) {
|
||||
const forceQuery = params?.force ? '?force=true' : '';
|
||||
return del(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}${forceQuery}`);
|
||||
}
|
||||
|
||||
export function updateKnowledgeTagBatch(data: { updates: Record<string, string | null> }) {
|
||||
return put(`/api/v1/knowledge/tags`, data);
|
||||
}
|
||||
|
||||
export function updateFAQEntryTagBatch(kbId: string, data: { updates: Record<string, string | null> }) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/tags`, data);
|
||||
}
|
||||
|
||||
const buildQuery = (params?: Record<string, any>) => {
|
||||
if (!params) return '';
|
||||
const query = new URLSearchParams();
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null || value === '') return;
|
||||
query.append(key, String(value));
|
||||
});
|
||||
const queryString = query.toString();
|
||||
return queryString ? `?${queryString}` : '';
|
||||
};
|
||||
|
||||
export function listFAQEntries(
|
||||
kbId: string,
|
||||
params?: { page?: number; page_size?: number; tag_id?: string; keyword?: string },
|
||||
) {
|
||||
const query = buildQuery(params);
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/faq/entries${query}`);
|
||||
}
|
||||
|
||||
export function upsertFAQEntries(kbId: string, data: { entries: any[]; mode: 'append' | 'replace' }) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/faq/entries`, data);
|
||||
}
|
||||
|
||||
export function createFAQEntry(kbId: string, data: any) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/faq/entry`, data);
|
||||
}
|
||||
|
||||
export function updateFAQEntry(kbId: string, entryId: string, data: any) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/${entryId}`, data);
|
||||
}
|
||||
|
||||
export function updateFAQEntryStatusBatch(kbId: string, data: { updates: Record<string, boolean> }) {
|
||||
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/status`, data);
|
||||
}
|
||||
|
||||
export function deleteFAQEntries(kbId: string, ids: string[]) {
|
||||
return del(`/api/v1/knowledge-bases/${kbId}/faq/entries`, { ids });
|
||||
}
|
||||
|
||||
export function searchFAQEntries(
|
||||
kbId: string,
|
||||
data: {
|
||||
query_text: string
|
||||
vector_threshold?: number
|
||||
match_count?: number
|
||||
}
|
||||
) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/faq/search`, data);
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
export interface MCPService {
|
||||
id: string
|
||||
tenant_id?: number
|
||||
name: string
|
||||
description: string
|
||||
enabled: boolean
|
||||
transport_type: 'sse' | 'http-streamable' | 'stdio'
|
||||
url?: string // Optional: required for SSE/HTTP Streamable
|
||||
headers?: Record<string, string>
|
||||
auth_config?: {
|
||||
api_key?: string
|
||||
token?: string
|
||||
custom_headers?: Record<string, string>
|
||||
}
|
||||
advanced_config?: {
|
||||
timeout?: number
|
||||
retry_count?: number
|
||||
retry_delay?: number
|
||||
}
|
||||
stdio_config?: {
|
||||
command: 'uvx' | 'npx' // Command: uvx or npx
|
||||
args: string[] // Command arguments array
|
||||
}
|
||||
env_vars?: Record<string, string> // Environment variables for stdio transport
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface MCPTool {
|
||||
name: string
|
||||
description: string
|
||||
inputSchema: Record<string, any>
|
||||
}
|
||||
|
||||
export interface MCPResource {
|
||||
uri: string
|
||||
name: string
|
||||
description?: string
|
||||
mimeType?: string
|
||||
}
|
||||
|
||||
export interface MCPTestResult {
|
||||
success: boolean
|
||||
message?: string
|
||||
tools?: MCPTool[]
|
||||
resources?: MCPResource[]
|
||||
}
|
||||
|
||||
// List all MCP services
|
||||
export async function listMCPServices(): Promise<MCPService[]> {
|
||||
const response: any = await get('/api/v1/mcp-services')
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
// Get a single MCP service by ID
|
||||
export async function getMCPService(id: string): Promise<MCPService> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// Create a new MCP service
|
||||
export async function createMCPService(data: Partial<MCPService>): Promise<MCPService> {
|
||||
const response: any = await post('/api/v1/mcp-services', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// Update an existing MCP service
|
||||
export async function updateMCPService(id: string, data: Partial<MCPService>): Promise<MCPService> {
|
||||
const response: any = await put(`/api/v1/mcp-services/${id}`, data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// Delete an MCP service
|
||||
export async function deleteMCPService(id: string): Promise<void> {
|
||||
await del(`/api/v1/mcp-services/${id}`)
|
||||
}
|
||||
|
||||
// Test MCP service connection
|
||||
export async function testMCPService(id: string): Promise<MCPTestResult> {
|
||||
const response: any = await post(`/api/v1/mcp-services/${id}/test`, {})
|
||||
// 后端返回格式: { success: true, data: MCPTestResult }
|
||||
// response interceptor 已经返回了 data,所以 response 就是 { success: true, data: {...} }
|
||||
if (response && response.data) {
|
||||
return response.data
|
||||
}
|
||||
// 如果格式不对,尝试直接返回 response(可能是直接返回的数据)
|
||||
return response
|
||||
}
|
||||
|
||||
// Get tools from an MCP service
|
||||
export async function getMCPServiceTools(id: string): Promise<MCPTool[]> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}/tools`)
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
// Get resources from an MCP service
|
||||
export async function getMCPServiceResources(id: string): Promise<MCPResource[]> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${id}/resources`)
|
||||
return response.data || []
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
import { get, post, put, del } from '../../utils/request';
|
||||
|
||||
// 模型类型定义
|
||||
export interface ModelConfig {
|
||||
id?: string;
|
||||
tenant_id?: number;
|
||||
name: string;
|
||||
type: 'KnowledgeQA' | 'Embedding' | 'Rerank' | 'VLLM';
|
||||
source: 'local' | 'remote';
|
||||
description?: string;
|
||||
parameters: {
|
||||
base_url?: string;
|
||||
api_key?: string;
|
||||
embedding_parameters?: {
|
||||
dimension?: number;
|
||||
truncate_prompt_tokens?: number;
|
||||
};
|
||||
interface_type?: 'ollama' | 'openai'; // VLLM专用
|
||||
parameter_size?: string; // Ollama模型参数大小 (e.g., "7B", "13B", "70B")
|
||||
};
|
||||
is_default?: boolean;
|
||||
is_builtin?: boolean;
|
||||
status?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
deleted_at?: string | null;
|
||||
}
|
||||
|
||||
// 创建模型
|
||||
export function createModel(data: ModelConfig): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/models', data)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || '创建模型失败'));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('创建模型失败:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 获取模型列表
|
||||
export function listModels(type?: string): Promise<ModelConfig[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = `/api/v1/models`;
|
||||
get(url)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
if (type) {
|
||||
response.data = response.data.filter((item: ModelConfig) => item.type === type);
|
||||
}
|
||||
resolve(response.data);
|
||||
} else {
|
||||
resolve([]);
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('获取模型列表失败:', error);
|
||||
resolve([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 获取单个模型
|
||||
export function getModel(id: string): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
get(`/api/v1/models/${id}`)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || '获取模型失败'));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('获取模型失败:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 更新模型
|
||||
export function updateModel(id: string, data: Partial<ModelConfig>): Promise<ModelConfig> {
|
||||
return new Promise((resolve, reject) => {
|
||||
put(`/api/v1/models/${id}`, data)
|
||||
.then((response: any) => {
|
||||
if (response.success && response.data) {
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error(response.message || '更新模型失败'));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('更新模型失败:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 删除模型
|
||||
export function deleteModel(id: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
del(`/api/v1/models/${id}`)
|
||||
.then((response: any) => {
|
||||
if (response.success) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error(response.message || '删除模型失败'));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('删除模型失败:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -1,12 +1,81 @@
|
|||
import { get } from '@/utils/request'
|
||||
import { get, put } from '@/utils/request'
|
||||
|
||||
export interface SystemInfo {
|
||||
version: string
|
||||
commit_id?: string
|
||||
build_time?: string
|
||||
go_version?: string
|
||||
keyword_index_engine?: string
|
||||
vector_store_engine?: string
|
||||
graph_database_engine?: string
|
||||
minio_enabled?: boolean
|
||||
}
|
||||
|
||||
export interface ToolDefinition {
|
||||
name: string
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface PlaceholderDefinition {
|
||||
name: string
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface AgentConfig {
|
||||
max_iterations: number
|
||||
reflection_enabled: boolean
|
||||
allowed_tools: string[]
|
||||
temperature: number
|
||||
knowledge_bases?: string[]
|
||||
system_prompt_web_enabled?: string // Custom system prompt when web search is enabled
|
||||
system_prompt_web_disabled?: string // Custom system prompt when web search is disabled
|
||||
use_custom_system_prompt?: boolean
|
||||
available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要
|
||||
available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要
|
||||
}
|
||||
|
||||
export interface ConversationConfig {
|
||||
prompt: string
|
||||
context_template: string
|
||||
temperature: number
|
||||
max_completion_tokens: number
|
||||
use_custom_system_prompt?: boolean
|
||||
use_custom_context_template?: boolean
|
||||
max_rounds: number
|
||||
embedding_top_k: number
|
||||
keyword_threshold: number
|
||||
vector_threshold: number
|
||||
rerank_top_k: number
|
||||
rerank_threshold: number
|
||||
enable_rewrite: boolean
|
||||
fallback_strategy: string
|
||||
fallback_response: string
|
||||
fallback_prompt?: string
|
||||
summary_model_id?: string
|
||||
rerank_model_id?: string
|
||||
rewrite_prompt_system?: string
|
||||
rewrite_prompt_user?: string
|
||||
enable_query_expansion?: boolean
|
||||
}
|
||||
|
||||
export function getSystemInfo(): Promise<{ data: SystemInfo }> {
|
||||
return get('/api/v1/system/info')
|
||||
}
|
||||
|
||||
export function getAgentConfig(): Promise<{ data: AgentConfig }> {
|
||||
return get('/api/v1/tenants/kv/agent-config')
|
||||
}
|
||||
|
||||
export function updateAgentConfig(config: AgentConfig): Promise<{ data: AgentConfig }> {
|
||||
return put('/api/v1/tenants/kv/agent-config', config)
|
||||
}
|
||||
|
||||
export function getConversationConfig(): Promise<{ data: ConversationConfig }> {
|
||||
return get('/api/v1/tenants/kv/conversation-config')
|
||||
}
|
||||
|
||||
export function updateConversationConfig(config: ConversationConfig): Promise<{ data: ConversationConfig }> {
|
||||
return put('/api/v1/tenants/kv/conversation-config', config)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { get } from '@/utils/request'
|
||||
|
||||
// 租户信息接口
|
||||
export interface TenantInfo {
|
||||
id: number
|
||||
name: string
|
||||
description?: string
|
||||
api_key?: string
|
||||
status?: string
|
||||
business?: string
|
||||
storage_quota?: number
|
||||
storage_used?: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
// 搜索租户参数
|
||||
export interface SearchTenantsParams {
|
||||
keyword?: string
|
||||
tenant_id?: number
|
||||
page?: number
|
||||
page_size?: number
|
||||
}
|
||||
|
||||
// 搜索租户响应
|
||||
export interface SearchTenantsResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
items: TenantInfo[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有租户列表(需要跨租户访问权限)
|
||||
* @deprecated 建议使用 searchTenants 代替,支持分页和搜索
|
||||
*/
|
||||
export async function listAllTenants(): Promise<{ success: boolean; data?: { items: TenantInfo[] }; message?: string }> {
|
||||
try {
|
||||
const response = await get('/api/v1/tenants/all')
|
||||
return response as unknown as { success: boolean; data?: { items: TenantInfo[] }; message?: string }
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || '获取租户列表失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索租户(支持分页、关键词搜索和租户ID过滤)
|
||||
*/
|
||||
export async function searchTenants(params: SearchTenantsParams = {}): Promise<SearchTenantsResponse> {
|
||||
try {
|
||||
const queryParams = new URLSearchParams()
|
||||
if (params.keyword) {
|
||||
queryParams.append('keyword', params.keyword)
|
||||
}
|
||||
if (params.tenant_id) {
|
||||
queryParams.append('tenant_id', String(params.tenant_id))
|
||||
}
|
||||
if (params.page) {
|
||||
queryParams.append('page', String(params.page))
|
||||
}
|
||||
if (params.page_size) {
|
||||
queryParams.append('page_size', String(params.page_size))
|
||||
}
|
||||
|
||||
const queryString = queryParams.toString()
|
||||
const url = `/api/v1/tenants/search${queryString ? '?' + queryString : ''}`
|
||||
const response = await get(url)
|
||||
return response as unknown as SearchTenantsResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || '搜索租户失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import { get, put } from '@/utils/request'
|
||||
|
||||
// WebSearchProviderConfig represents information about a web search provider
|
||||
export interface WebSearchProviderConfig {
|
||||
id: string
|
||||
name: string
|
||||
free: boolean
|
||||
requires_api_key: boolean
|
||||
description?: string
|
||||
api_url?: string
|
||||
}
|
||||
|
||||
// WebSearchConfig represents the web search configuration for a tenant
|
||||
export interface WebSearchConfig {
|
||||
provider: string
|
||||
api_key?: string
|
||||
max_results: number
|
||||
include_date: boolean
|
||||
compression_method: string
|
||||
blacklist: string[]
|
||||
embedding_model_id?: string
|
||||
embedding_dimension?: number
|
||||
rerank_model_id?: string
|
||||
document_fragments?: number
|
||||
}
|
||||
|
||||
// Get web search providers
|
||||
export function getWebSearchProviders() {
|
||||
return get('/api/v1/web-search/providers')
|
||||
}
|
||||
|
||||
// Get tenant web search config via KV API
|
||||
export function getTenantWebSearchConfig() {
|
||||
return get('/api/v1/tenants/kv/web-search-config')
|
||||
}
|
||||
|
||||
// Update tenant web search config via KV API
|
||||
export function updateTenantWebSearchConfig(config: WebSearchConfig) {
|
||||
return put('/api/v1/tenants/kv/web-search-config', config)
|
||||
}
|
||||
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" class="r4oyk8abi__design-iconfont" width="128" height="128">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 2C5.79086 2 4 3.79086 4 6C4 7.56981 4.90422 8.92935 6.22252 9.58448C6.39251 9.66896 6.5 9.84241 6.5 10.0322V11H9.5V10.0322C9.5 9.84241 9.60749 9.66896 9.77748 9.58448C11.0958 8.92935 12 7.56981 12 6C12 3.79086 10.2091 2 8 2ZM3 6C3 3.23858 5.23858 1 8 1C10.7614 1 13 3.23858 13 6C13 7.85144 11.9936 9.46702 10.5 10.331V11.5C10.5 11.7761 10.2761 12 10 12H6C5.72386 12 5.5 11.7761 5.5 11.5V10.331C4.00636 9.46702 3 7.85144 3 6Z" fill="#32CE3F"></path>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 13.5H6V12.5H10V13.5Z" fill="#32CE3F"></path>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 15H7V14H9V15Z" fill="#32CE3F"></path>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.4269 5.11946L7.60516 7.94123L5.7821 6.11819L6.48921 5.41108L7.60516 6.52702L9.71982 4.41235L10.4269 5.11946Z" fill="#32CE3F"></path>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="128" height="128">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 2C5.79086 2 4 3.79086 4 6C4 7.56981 4.90422 8.92935 6.22252 9.58448C6.39251 9.66896 6.5 9.84241 6.5 10.0322V11H9.5V10.0322C9.5 9.84241 9.60749 9.66896 9.77748 9.58448C11.0958 8.92935 12 7.56981 12 6C12 3.79086 10.2091 2 8 2ZM3 6C3 3.23858 5.23858 1 8 1C10.7614 1 13 3.23858 13 6C13 7.85144 11.9936 9.46702 10.5 10.331V11.5C10.5 11.7761 10.2761 12 10 12H6C5.72386 12 5.5 11.7761 5.5 11.5V10.331C4.00636 9.46702 3 7.85144 3 6Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.3"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 13.5H6V12.5H10V13.5Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.3"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 15H7V14H9V15Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.3"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.4269 5.11946L7.60516 7.94123L5.7821 6.11819L6.48921 5.41108L7.60516 6.52702L9.71982 4.41235L10.4269 5.11946Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.3"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1022 B After Width: | Height: | Size: 1.1 KiB |
|
|
@ -0,0 +1,5 @@
|
|||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" fill="#07C05F" stroke="#07C05F" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z" fill="#07C05F" stroke="#07C05F" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z" fill="#07C05F" stroke="#07C05F" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 992 B |
|
|
@ -0,0 +1,5 @@
|
|||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 995 B |
|
|
@ -0,0 +1,4 @@
|
|||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="10" cy="10" r="3.5" stroke="#00000099" stroke-width="1.8"/>
|
||||
<path d="M13.5 10V11.5C13.5 12.163 13.7634 12.7989 14.2322 13.2678C14.7011 13.7366 15.337 14 16 14C16.663 14 17.2989 13.7366 17.7678 13.2678C18.2366 12.7989 18.5 12.163 18.5 11.5V10C18.5 7.74566 17.6045 5.58365 16.0104 3.98959C14.4163 2.39553 12.2543 1.5 10 1.5C7.74566 1.5 5.58365 2.39553 3.98959 3.98959C2.39553 5.58365 1.5 7.74566 1.5 10C1.5 12.2543 2.39553 14.4163 3.98959 16.0104C5.58365 17.6045 7.74566 18.5 10 18.5H12" stroke="#00000099" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 692 B |
|
|
@ -0,0 +1,82 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600">
|
||||
<!-- Background -->
|
||||
<defs>
|
||||
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:#F0FDF4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#DCFCE7;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="800" height="600" fill="url(#grad1)"/>
|
||||
|
||||
<!-- Decorative circles -->
|
||||
<circle cx="100" cy="80" r="100" fill="#10B981" opacity="0.04"/>
|
||||
<circle cx="700" cy="520" r="120" fill="#10B981" opacity="0.04"/>
|
||||
|
||||
<!-- Title -->
|
||||
<text x="400" y="70" font-family="PingFang SC, sans-serif" font-size="36" font-weight="700" fill="#065F46" text-anchor="middle">智能文档检索</text>
|
||||
<text x="400" y="105" font-family="PingFang SC, sans-serif" font-size="16" fill="#059669" text-anchor="middle">多模态文档解析 • 语义理解 • 精准检索</text>
|
||||
|
||||
<!-- Search Interface -->
|
||||
<g transform="translate(100, 150)">
|
||||
<!-- Search box with icon -->
|
||||
<rect width="600" height="60" rx="12" fill="white" stroke="#10B981" stroke-width="2.5" filter="drop-shadow(0 4px 20px rgba(16, 185, 129, 0.15))"/>
|
||||
<circle cx="35" cy="30" r="12" stroke="#10B981" stroke-width="2.5" fill="none"/>
|
||||
<line x1="44" y1="39" x2="52" y2="47" stroke="#10B981" stroke-width="2.5" stroke-linecap="round"/>
|
||||
<text x="70" y="36" font-family="PingFang SC, sans-serif" font-size="16" fill="#9CA3AF">输入查询内容进行智能检索...</text>
|
||||
|
||||
<!-- Search button -->
|
||||
<rect x="480" y="12" width="100" height="36" rx="8" fill="#10B981"/>
|
||||
<text x="530" y="36" font-family="PingFang SC, sans-serif" font-size="15" font-weight="600" fill="white" text-anchor="middle">检索</text>
|
||||
</g>
|
||||
|
||||
<!-- Document Results -->
|
||||
<!-- Result 1 -->
|
||||
<g transform="translate(100, 250)">
|
||||
<rect width="600" height="90" rx="12" fill="white" stroke="#10B981" stroke-width="2" filter="drop-shadow(0 2px 12px rgba(16, 185, 129, 0.1))"/>
|
||||
|
||||
<!-- Document icon -->
|
||||
<g transform="translate(25, 20)">
|
||||
<rect width="50" height="50" rx="8" fill="#D1FAE5"/>
|
||||
<path d="M15 15 L35 15 M15 25 L35 25 M15 35 L25 35" stroke="#059669" stroke-width="2.5" stroke-linecap="round"/>
|
||||
</g>
|
||||
|
||||
<!-- Content -->
|
||||
<text x="95" y="35" font-family="PingFang SC, sans-serif" font-size="18" font-weight="600" fill="#065F46">RAG系统技术文档.pdf</text>
|
||||
<text x="95" y="57" font-family="PingFang SC, sans-serif" font-size="13" fill="#6B7280">详细介绍了检索增强生成的核心原理和实现方案...</text>
|
||||
<text x="95" y="75" font-family="PingFang SC, sans-serif" font-size="12" fill="#9CA3AF">3.2 MB • 127页 • 2024-01-20</text>
|
||||
</g>
|
||||
|
||||
<!-- Result 2 -->
|
||||
<g transform="translate(100, 360)">
|
||||
<rect width="600" height="90" rx="12" fill="white" stroke="#E5E7EB" stroke-width="1.5" filter="drop-shadow(0 2px 8px rgba(0, 0, 0, 0.05))"/>
|
||||
|
||||
<!-- Document icon -->
|
||||
<g transform="translate(25, 20)">
|
||||
<rect width="50" height="50" rx="8" fill="#DBEAFE"/>
|
||||
<path d="M15 15 L35 15 M15 25 L35 25 M15 35 L28 35" stroke="#1E40AF" stroke-width="2.5" stroke-linecap="round"/>
|
||||
</g>
|
||||
|
||||
<!-- Content -->
|
||||
<text x="95" y="35" font-family="PingFang SC, sans-serif" font-size="18" font-weight="600" fill="#1F2937">向量检索优化方案.docx</text>
|
||||
<text x="95" y="57" font-family="PingFang SC, sans-serif" font-size="13" fill="#6B7280">基于Embedding的语义检索技术实践与优化...</text>
|
||||
<text x="95" y="75" font-family="PingFang SC, sans-serif" font-size="12" fill="#9CA3AF">1.8 MB • 45页 • 2024-01-19</text>
|
||||
</g>
|
||||
|
||||
<!-- Result 3 -->
|
||||
<g transform="translate(100, 470)">
|
||||
<rect width="600" height="90" rx="12" fill="white" stroke="#E5E7EB" stroke-width="1.5" filter="drop-shadow(0 2px 8px rgba(0, 0, 0, 0.05))"/>
|
||||
|
||||
<!-- Image icon -->
|
||||
<g transform="translate(25, 20)">
|
||||
<rect width="50" height="50" rx="8" fill="#FEF3C7"/>
|
||||
<circle cx="20" cy="28" r="5" fill="#F59E0B"/>
|
||||
<path d="M12 42 L20 34 L28 42 L38 32" stroke="#F59E0B" stroke-width="2.5" fill="none" stroke-linecap="round"/>
|
||||
</g>
|
||||
|
||||
<!-- Content -->
|
||||
<text x="95" y="35" font-family="PingFang SC, sans-serif" font-size="18" font-weight="600" fill="#1F2937">知识图谱架构图.png</text>
|
||||
<text x="95" y="57" font-family="PingFang SC, sans-serif" font-size="13" fill="#6B7280">展示知识图谱的节点关系和查询路径...</text>
|
||||
<text x="95" y="75" font-family="PingFang SC, sans-serif" font-size="12" fill="#9CA3AF">1.2 MB • 1920×1080 • 2024-01-18</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
After Width: | Height: | Size: 4.5 KiB |
|
|
@ -0,0 +1,154 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600">
|
||||
<!-- Background - Same green gradient as screenshot-1 -->
|
||||
<defs>
|
||||
<linearGradient id="grad2" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:#F0FDF4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#DCFCE7;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="800" height="600" fill="url(#grad2)"/>
|
||||
|
||||
<!-- Decorative circles -->
|
||||
<circle cx="120" cy="90" r="110" fill="#10B981" opacity="0.04"/>
|
||||
<circle cx="680" cy="510" r="130" fill="#10B981" opacity="0.04"/>
|
||||
|
||||
<!-- Title -->
|
||||
<text x="400" y="70" font-family="PingFang SC, sans-serif" font-size="36" font-weight="700" fill="#065F46" text-anchor="middle">混合检索策略</text>
|
||||
<text x="400" y="105" font-family="PingFang SC, sans-serif" font-size="16" fill="#059669" text-anchor="middle">BM25 关键词 + 向量语义 + 知识图谱</text>
|
||||
|
||||
<!-- Three retrieval methods -->
|
||||
<!-- BM25 -->
|
||||
<g transform="translate(80, 170)">
|
||||
<rect width="180" height="280" rx="12" fill="white" stroke="#F59E0B" stroke-width="2.5" filter="drop-shadow(0 4px 16px rgba(245, 158, 11, 0.15))"/>
|
||||
<rect width="180" height="50" rx="12" fill="#FEF3C7"/>
|
||||
<text x="90" y="33" font-family="PingFang SC, sans-serif" font-size="18" font-weight="700" fill="#92400E" text-anchor="middle">BM25</text>
|
||||
|
||||
<!-- Icon -->
|
||||
<g transform="translate(65, 70)">
|
||||
<circle cx="25" cy="25" r="20" fill="#FBBF24" opacity="0.2"/>
|
||||
<text x="25" y="33" font-family="Arial" font-size="24" font-weight="700" fill="#F59E0B" text-anchor="middle">K</text>
|
||||
</g>
|
||||
|
||||
<!-- Features -->
|
||||
<text x="90" y="135" font-family="PingFang SC, sans-serif" font-size="14" fill="#92400E" text-anchor="middle">关键词匹配</text>
|
||||
|
||||
<g transform="translate(20, 155)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#FEF3C7"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#78350F" text-anchor="middle">TF-IDF 权重</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(20, 195)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#FEF3C7"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#78350F" text-anchor="middle">词频统计</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(20, 235)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#FEF3C7"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#78350F" text-anchor="middle">精确匹配</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- Vector -->
|
||||
<g transform="translate(310, 170)">
|
||||
<rect width="180" height="280" rx="12" fill="white" stroke="#3B82F6" stroke-width="2.5" filter="drop-shadow(0 4px 16px rgba(59, 130, 246, 0.15))"/>
|
||||
<rect width="180" height="50" rx="12" fill="#DBEAFE"/>
|
||||
<text x="90" y="33" font-family="PingFang SC, sans-serif" font-size="18" font-weight="700" fill="#1E40AF" text-anchor="middle">向量检索</text>
|
||||
|
||||
<!-- Icon - Vector space -->
|
||||
<g transform="translate(65, 70)">
|
||||
<circle cx="25" cy="25" r="20" fill="#60A5FA" opacity="0.2"/>
|
||||
<circle cx="15" cy="20" r="3" fill="#1E40AF"/>
|
||||
<circle cx="25" cy="15" r="3" fill="#1E40AF"/>
|
||||
<circle cx="35" cy="20" r="3" fill="#1E40AF"/>
|
||||
<circle cx="20" cy="28" r="4" fill="#3B82F6"/>
|
||||
<circle cx="30" cy="28" r="4" fill="#3B82F6"/>
|
||||
<circle cx="15" cy="35" r="3" fill="#1E40AF"/>
|
||||
<circle cx="25" cy="38" r="3" fill="#1E40AF"/>
|
||||
<circle cx="35" cy="35" r="3" fill="#1E40AF"/>
|
||||
<!-- Connection lines -->
|
||||
<line x1="15" y1="20" x2="25" y2="15" stroke="#3B82F6" stroke-width="1" opacity="0.5"/>
|
||||
<line x1="25" y1="15" x2="35" y2="20" stroke="#3B82F6" stroke-width="1" opacity="0.5"/>
|
||||
<line x1="15" y1="20" x2="20" y2="28" stroke="#3B82F6" stroke-width="1" opacity="0.5"/>
|
||||
<line x1="35" y1="20" x2="30" y2="28" stroke="#3B82F6" stroke-width="1" opacity="0.5"/>
|
||||
<line x1="20" y1="28" x2="15" y2="35" stroke="#3B82F6" stroke-width="1" opacity="0.5"/>
|
||||
<line x1="30" y1="28" x2="35" y2="35" stroke="#3B82F6" stroke-width="1" opacity="0.5"/>
|
||||
</g>
|
||||
|
||||
<!-- Features -->
|
||||
<text x="90" y="135" font-family="PingFang SC, sans-serif" font-size="14" fill="#1E40AF" text-anchor="middle">语义理解</text>
|
||||
|
||||
<g transform="translate(20, 155)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#DBEAFE"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#1E3A8A" text-anchor="middle">Embedding</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(20, 195)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#DBEAFE"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#1E3A8A" text-anchor="middle">余弦相似度</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(20, 235)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#DBEAFE"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#1E3A8A" text-anchor="middle">ANN 检索</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- Knowledge Graph -->
|
||||
<g transform="translate(540, 170)">
|
||||
<rect width="180" height="280" rx="12" fill="white" stroke="#10B981" stroke-width="2.5" filter="drop-shadow(0 4px 16px rgba(16, 185, 129, 0.15))"/>
|
||||
<rect width="180" height="50" rx="12" fill="#DCFCE7"/>
|
||||
<text x="90" y="33" font-family="PingFang SC, sans-serif" font-size="18" font-weight="700" fill="#065F46" text-anchor="middle">知识图谱</text>
|
||||
|
||||
<!-- Icon - Graph nodes -->
|
||||
<g transform="translate(65, 70)">
|
||||
<circle cx="25" cy="25" r="20" fill="#34D399" opacity="0.2"/>
|
||||
<!-- Nodes -->
|
||||
<circle cx="15" cy="15" r="5" fill="#FFFFFF" stroke="#10B981" stroke-width="2"/>
|
||||
<circle cx="35" cy="15" r="5" fill="#FFFFFF" stroke="#10B981" stroke-width="2"/>
|
||||
<circle cx="25" cy="28" r="6" fill="#10B981" stroke="#065F46" stroke-width="2"/>
|
||||
<circle cx="15" cy="38" r="5" fill="#FFFFFF" stroke="#10B981" stroke-width="2"/>
|
||||
<circle cx="35" cy="38" r="5" fill="#FFFFFF" stroke="#10B981" stroke-width="2"/>
|
||||
<!-- Edges -->
|
||||
<line x1="15" y1="15" x2="25" y2="28" stroke="#10B981" stroke-width="2"/>
|
||||
<line x1="35" y1="15" x2="25" y2="28" stroke="#10B981" stroke-width="2"/>
|
||||
<line x1="25" y1="28" x2="15" y2="38" stroke="#10B981" stroke-width="2"/>
|
||||
<line x1="25" y1="28" x2="35" y2="38" stroke="#10B981" stroke-width="2"/>
|
||||
</g>
|
||||
|
||||
<!-- Features -->
|
||||
<text x="90" y="135" font-family="PingFang SC, sans-serif" font-size="14" fill="#065F46" text-anchor="middle">关系推理</text>
|
||||
|
||||
<g transform="translate(20, 155)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#DCFCE7"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#064E3B" text-anchor="middle">实体识别</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(20, 195)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#DCFCE7"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#064E3B" text-anchor="middle">路径查询</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(20, 235)">
|
||||
<rect x="0" y="0" width="140" height="30" rx="6" fill="#DCFCE7"/>
|
||||
<text x="70" y="20" font-family="PingFang SC, sans-serif" font-size="12" fill="#064E3B" text-anchor="middle">子图匹配</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- Arrows to fusion -->
|
||||
<path d="M170 460 L400 510" stroke="#9CA3AF" stroke-width="2.5" stroke-dasharray="5,3" marker-end="url(#arrowGray)"/>
|
||||
<path d="M400 460 L400 510" stroke="#9CA3AF" stroke-width="2.5" stroke-dasharray="5,3" marker-end="url(#arrowGray)"/>
|
||||
<path d="M630 460 L400 510" stroke="#9CA3AF" stroke-width="2.5" stroke-dasharray="5,3" marker-end="url(#arrowGray)"/>
|
||||
|
||||
<!-- Fusion result -->
|
||||
<g transform="translate(250, 520)">
|
||||
<rect width="300" height="50" rx="10" fill="#10B981" filter="drop-shadow(0 4px 16px rgba(16, 185, 129, 0.25))"/>
|
||||
<text x="150" y="32" font-family="PingFang SC, sans-serif" font-size="16" font-weight="700" fill="white" text-anchor="middle">融合排序 → 最优结果</text>
|
||||
</g>
|
||||
|
||||
<!-- Arrow marker -->
|
||||
<defs>
|
||||
<marker id="arrowGray" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
|
||||
<polygon points="0 0, 10 3, 0 6" fill="#9CA3AF"/>
|
||||
</marker>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.2 KiB |
|
|
@ -0,0 +1,102 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600">
|
||||
<!-- Background - Same green gradient -->
|
||||
<defs>
|
||||
<linearGradient id="grad3" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:#F0FDF4;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#DCFCE7;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="800" height="600" fill="url(#grad3)"/>
|
||||
|
||||
<!-- Decorative circles -->
|
||||
<circle cx="110" cy="85" r="105" fill="#10B981" opacity="0.04"/>
|
||||
<circle cx="690" cy="515" r="125" fill="#10B981" opacity="0.04"/>
|
||||
|
||||
<!-- Title -->
|
||||
<text x="400" y="70" font-family="PingFang SC, sans-serif" font-size="36" font-weight="700" fill="#065F46" text-anchor="middle">Agentic RAG</text>
|
||||
<text x="400" y="105" font-family="PingFang SC, sans-serif" font-size="16" fill="#059669" text-anchor="middle">基于 ReAct 范式的智能检索代理</text>
|
||||
|
||||
<!-- Query Input -->
|
||||
<g transform="translate(300, 140)">
|
||||
<rect width="200" height="50" rx="10" fill="white" stroke="#10B981" stroke-width="2" filter="drop-shadow(0 4px 16px rgba(16, 185, 129, 0.15))"/>
|
||||
<text x="100" y="32" font-family="PingFang SC, sans-serif" font-size="16" font-weight="600" fill="#065F46" text-anchor="middle">用户问题</text>
|
||||
</g>
|
||||
|
||||
<!-- Arrow down -->
|
||||
<path d="M400 200 L400 225" stroke="#059669" stroke-width="3" marker-end="url(#arrowGreen)"/>
|
||||
|
||||
<!-- ReAct Loop Container -->
|
||||
<g transform="translate(120, 235)">
|
||||
<rect width="560" height="240" rx="16" fill="white" stroke="#8B5CF6" stroke-width="3" stroke-dasharray="10,5" filter="drop-shadow(0 4px 20px rgba(139, 92, 246, 0.15))"/>
|
||||
<text x="280" y="30" font-family="PingFang SC, sans-serif" font-size="18" font-weight="700" fill="#5B21B6" text-anchor="middle">ReAct 循环</text>
|
||||
|
||||
<!-- Reasoning -->
|
||||
<g transform="translate(40, 55)">
|
||||
<rect width="220" height="75" rx="10" fill="#EDE9FE" stroke="#8B5CF6" stroke-width="2"/>
|
||||
<text x="110" y="25" font-family="PingFang SC, sans-serif" font-size="17" font-weight="700" fill="#5B21B6" text-anchor="middle">① Reasoning</text>
|
||||
<text x="110" y="45" font-family="PingFang SC, sans-serif" font-size="13" fill="#6B21A8" text-anchor="middle">分析问题</text>
|
||||
<text x="110" y="63" font-family="PingFang SC, sans-serif" font-size="13" fill="#6B21A8" text-anchor="middle">规划行动策略</text>
|
||||
</g>
|
||||
|
||||
<!-- Arrow to Tools -->
|
||||
<path d="M270 92 L290 92" stroke="#8B5CF6" stroke-width="2.5" marker-end="url(#arrowPurple)"/>
|
||||
|
||||
<!-- Acting with Tools -->
|
||||
<g transform="translate(300, 55)">
|
||||
<rect width="220" height="160" rx="10" fill="#FEF3C7" stroke="#F59E0B" stroke-width="2"/>
|
||||
<text x="110" y="25" font-family="PingFang SC, sans-serif" font-size="17" font-weight="700" fill="#92400E" text-anchor="middle">② Acting (Tools)</text>
|
||||
|
||||
<!-- Tool 1 -->
|
||||
<g transform="translate(20, 38)">
|
||||
<rect width="180" height="28" rx="6" fill="white" stroke="#F59E0B" stroke-width="1.5"/>
|
||||
<circle cx="14" cy="14" r="6" fill="#FBBF24"/>
|
||||
<text x="95" y="18" font-family="PingFang SC, sans-serif" font-size="12" fill="#78350F" text-anchor="middle">🔍 向量检索</text>
|
||||
</g>
|
||||
|
||||
<!-- Tool 2 -->
|
||||
<g transform="translate(20, 73)">
|
||||
<rect width="180" height="28" rx="6" fill="white" stroke="#F59E0B" stroke-width="1.5"/>
|
||||
<circle cx="14" cy="14" r="6" fill="#FBBF24"/>
|
||||
<text x="95" y="18" font-family="PingFang SC, sans-serif" font-size="12" fill="#78350F" text-anchor="middle">🔗 知识图谱</text>
|
||||
</g>
|
||||
|
||||
<!-- Tool 3 -->
|
||||
<g transform="translate(20, 108)">
|
||||
<rect width="180" height="28" rx="6" fill="white" stroke="#F59E0B" stroke-width="1.5"/>
|
||||
<circle cx="14" cy="14" r="6" fill="#FBBF24"/>
|
||||
<text x="95" y="18" font-family="PingFang SC, sans-serif" font-size="12" fill="#78350F" text-anchor="middle">📊 BM25检索</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- Arrow back to Reasoning (loop) -->
|
||||
<path d="M300 160 Q 280 195 150 160" stroke="#8B5CF6" stroke-width="2.5" stroke-dasharray="5,3" fill="none" marker-end="url(#arrowPurple)"/>
|
||||
<text x="220" y="200" font-family="PingFang SC, sans-serif" font-size="12" fill="#7C3AED" text-anchor="middle">迭代优化</text>
|
||||
</g>
|
||||
|
||||
<!-- Arrow down to result -->
|
||||
<path d="M400 485 L400 505" stroke="#059669" stroke-width="3" marker-end="url(#arrowGreen)"/>
|
||||
|
||||
<!-- Final Answer -->
|
||||
<g transform="translate(250, 515)">
|
||||
<rect width="300" height="50" rx="10" fill="#10B981" filter="drop-shadow(0 4px 16px rgba(16, 185, 129, 0.25))"/>
|
||||
<text x="150" y="32" font-family="PingFang SC, sans-serif" font-size="16" font-weight="700" fill="white" text-anchor="middle">③ 生成增强答案</text>
|
||||
</g>
|
||||
|
||||
<!-- Side annotation -->
|
||||
<g transform="translate(50, 320)">
|
||||
<text x="0" y="0" font-family="PingFang SC, sans-serif" font-size="13" font-weight="600" fill="#059669">特点:</text>
|
||||
<text x="0" y="22" font-family="PingFang SC, sans-serif" font-size="12" fill="#6B7280">• 自主推理</text>
|
||||
<text x="0" y="42" font-family="PingFang SC, sans-serif" font-size="12" fill="#6B7280">• 工具调用</text>
|
||||
<text x="0" y="62" font-family="PingFang SC, sans-serif" font-size="12" fill="#6B7280">• 动态迭代</text>
|
||||
</g>
|
||||
|
||||
<!-- Arrow markers -->
|
||||
<defs>
|
||||
<marker id="arrowGreen" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
|
||||
<polygon points="0 0, 10 3, 0 6" fill="#059669"/>
|
||||
</marker>
|
||||
<marker id="arrowPurple" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
|
||||
<polygon points="0 0, 10 3, 0 6" fill="#8B5CF6"/>
|
||||
</marker>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.6 KiB |
|
|
@ -1,5 +1,4 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10 12.5C11.3807 12.5 12.5 11.3807 12.5 10C12.5 8.61929 11.3807 7.5 10 7.5C8.61929 7.5 7.5 8.61929 7.5 10C7.5 11.3807 8.61929 12.5 10 12.5Z" stroke="#07C05F" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M1.66675 10.7333V9.26667C1.66675 8.4 2.37508 7.68333 3.25008 7.68333C4.75841 7.68333 5.35008 6.61667 4.59175 5.30833C4.14175 4.55833 4.38341 3.58333 5.14175 3.13333L6.58342 2.30833C7.24175 1.90833 8.09175 2.125 8.49175 2.78333L8.57508 2.92501C9.32508 4.23334 10.6751 4.23334 11.4334 2.92501L11.5167 2.78333C11.9167 2.125 12.7667 1.90833 13.4251 2.30833L14.8667 3.13333C15.6251 3.58333 15.8667 4.55833 15.4167 5.30833C14.6584 6.61667 15.2501 7.68333 16.7584 7.68333C17.6251 7.68333 18.3417 8.39167 18.3417 9.26667V10.7333C18.3417 11.6 17.6334 12.3167 16.7584 12.3167C15.2501 12.3167 14.6584 13.3833 15.4167 14.6917C15.8667 15.45 15.6251 16.4167 14.8667 16.8667L13.4251 17.6917C12.7667 18.0917 11.9167 17.875 11.5167 17.2167L11.4334 17.075C10.6834 15.7667 9.33341 15.7667 8.57508 17.075L8.49175 17.2167C8.09175 17.875 7.24175 18.0917 6.58342 17.6917L5.14175 16.8667C4.38341 16.4167 4.14175 15.4417 4.59175 14.6917C5.35008 13.3833 4.75841 12.3167 3.25008 12.3167C2.37508 12.3167 1.66675 11.6 1.66675 10.7333Z" stroke="#07C05F" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<path d="M10 12.5C11.3807 12.5 12.5 11.3807 12.5 10C12.5 8.61929 11.3807 7.5 10 7.5C8.61929 7.5 7.5 8.61929 7.5 10C7.5 11.3807 8.61929 12.5 10 12.5Z" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16.1667 12.5C16.0557 12.7513 16.0227 13.0301 16.0721 13.3006C16.1214 13.5711 16.251 13.8203 16.4417 14.0167L16.4917 14.0667C16.6447 14.2194 16.7658 14.4008 16.8482 14.6006C16.9305 14.8003 16.9725 15.0145 16.9725 15.2308C16.9725 15.4472 16.9305 15.6614 16.8482 15.8611C16.7658 16.0609 16.6447 16.2423 16.4917 16.395C16.339 16.548 16.1576 16.6691 15.9578 16.7514C15.7581 16.8338 15.5439 16.8758 15.3275 16.8758C15.1112 16.8758 14.897 16.8338 14.6972 16.7514C14.4975 16.6691 14.3161 16.548 14.1633 16.395L14.1133 16.345C13.917 16.1543 13.6678 16.0247 13.3973 15.9754C13.1268 15.926 12.848 15.959 12.5967 16.07C12.3503 16.1761 12.1423 16.3521 11.9993 16.5762C11.8563 16.8003 11.7848 17.0625 11.7942 17.3283V17.5C11.7942 17.9421 11.6184 18.3659 11.3059 18.6785C10.9933 18.991 10.5695 19.1667 10.1275 19.1667C9.6854 19.1667 9.26163 18.991 8.94907 18.6785C8.63651 18.3659 8.46083 17.9421 8.46083 17.5V17.425C8.46458 17.1515 8.38642 16.8831 8.23616 16.6542C8.0859 16.4252 7.87016 16.2461 7.61583 16.1383C7.36452 16.0273 7.08571 15.9943 6.81523 16.0437C6.54474 16.093 6.29555 16.2227 6.09917 16.4133L6.04917 16.4633C5.89641 16.6163 5.71499 16.7374 5.51525 16.8198C5.31551 16.9021 5.10132 16.9441 4.88499 16.9441C4.66866 16.9441 4.45447 16.9021 4.25473 16.8198C4.05499 16.7374 3.87357 16.6163 3.72083 16.4633C3.56783 16.3106 3.4467 16.1292 3.36438 15.9294C3.28205 15.7297 3.24005 15.5155 3.24005 15.2992C3.24005 15.0828 3.28205 14.8687 3.36438 14.6689C3.4467 14.4692 3.56783 14.2877 3.72083 14.135L3.77083 14.085C3.96147 13.8886 4.09115 13.6394 4.14049 13.3689C4.18984 13.0985 4.15685 12.8196 4.04583 12.5683C3.93975 12.322 3.76374 12.1139 3.53965 11.9709C3.31556 11.8279 3.05339 11.7564 2.7875 11.7658H2.61583C2.17379 11.7658 1.75001 11.5902 1.43745 11.2776C1.12489 10.965 0.949219 10.5412 0.949219 10.0992C0.949219 9.65712 1.12489 9.23335 1.43745 8.92079C1.75001 8.60823 2.17379 8.43255 2.61583 8.43255H2.69083C2.96438 8.4288 3.23272 8.35065 3.46167 8.20038C3.69063 8.05012 3.86979 7.83438 3.9775 7.58005C4.0885 7.32874 4.12149 7.04993 4.07215 6.77944C4.02281 6.50896 3.89313 6.25977 3.7025 6.06339L3.6525 6.01339C3.4995 5.86063 3.37837 5.67921 3.29604 5.47947C3.21372 5.27973 3.17172 5.06554 3.17172 4.84921C3.17172 4.63288 3.21372 4.41869 3.29604 4.21895C3.37837 4.01921 3.4995 3.83779 3.6525 3.68505C3.80524 3.53205 3.98666 3.41092 4.1864 3.3286C4.38614 3.24627 4.60033 3.20427 4.81666 3.20427C5.03299 3.20427 5.24719 3.24627 5.44693 3.3286C5.64666 3.41092 5.82809 3.53205 5.98083 3.68505L6.03083 3.73505C6.22721 3.92569 6.4764 4.05537 6.74688 4.10472C7.01737 4.15406 7.29618 4.12107 7.5475 4.01005H7.61583C7.86213 3.90397 8.07024 3.72796 8.21324 3.50387C8.35624 3.27978 8.42774 3.01761 8.41833 2.75172V2.58005C8.41833 2.13801 8.59401 1.71424 8.90657 1.40168C9.21913 1.08912 9.6429 0.913452 10.0849 0.913452C10.527 0.913452 10.9507 1.08912 11.2633 1.40168C11.5759 1.71424 11.7515 2.13801 11.7515 2.58005V2.65505C11.7421 2.92094 11.8136 3.18311 11.9566 3.4072C12.0996 3.63129 12.3077 3.8073 12.554 3.91339C12.8053 4.0244 13.0841 4.05739 13.3546 4.00805C13.6251 3.95871 13.8743 3.82903 14.0706 3.63839L14.1206 3.58839C14.2734 3.43539 14.4548 3.31426 14.6545 3.23193C14.8543 3.14961 15.0685 3.10761 15.2848 3.10761C15.5011 3.10761 15.7153 3.14961 15.9151 3.23193C16.1148 3.31426 16.2962 3.43539 16.449 3.58839C16.602 3.74113 16.7231 3.92255 16.8054 4.12229C16.8878 4.32203 16.9298 4.53622 16.9298 4.75255C16.9298 4.96888 16.8878 5.18307 16.8054 5.38281C16.7231 5.58255 16.602 5.76397 16.449 5.91672L16.399 5.96672C16.2084 6.1631 16.0787 6.41229 16.0293 6.68277C15.98 6.95326 16.013 7.23207 16.124 7.48339V7.58005C16.2301 7.82635 16.4061 8.03446 16.6302 8.17746C16.8543 8.32046 17.1164 8.39196 17.3823 8.38255H17.554C17.996 8.38255 18.4198 8.55823 18.7324 8.87079C19.0449 9.18335 19.2206 9.60712 19.2206 10.0492C19.2206 10.4912 19.0449 10.915 18.7324 11.2276C18.4198 11.5401 17.996 11.7158 17.554 11.7158H17.479C17.2131 11.7064 16.951 11.7779 16.7269 11.9209C16.5028 12.0639 16.3268 12.272 16.2206 12.5183V12.5Z" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 4.3 KiB |
|
|
@ -1,5 +1,4 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10 12.5C11.3807 12.5 12.5 11.3807 12.5 10C12.5 8.61929 11.3807 7.5 10 7.5C8.61929 7.5 7.5 8.61929 7.5 10C7.5 11.3807 8.61929 12.5 10 12.5Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M1.66675 10.7333V9.26667C1.66675 8.4 2.37508 7.68333 3.25008 7.68333C4.75841 7.68333 5.35008 6.61667 4.59175 5.30833C4.14175 4.55833 4.38341 3.58333 5.14175 3.13333L6.58342 2.30833C7.24175 1.90833 8.09175 2.125 8.49175 2.78333L8.57508 2.92501C9.32508 4.23334 10.6751 4.23334 11.4334 2.92501L11.5167 2.78333C11.9167 2.125 12.7667 1.90833 13.4251 2.30833L14.8667 3.13333C15.6251 3.58333 15.8667 4.55833 15.4167 5.30833C14.6584 6.61667 15.2501 7.68333 16.7584 7.68333C17.6251 7.68333 18.3417 8.39167 18.3417 9.26667V10.7333C18.3417 11.6 17.6334 12.3167 16.7584 12.3167C15.2501 12.3167 14.6584 13.3833 15.4167 14.6917C15.8667 15.45 15.6251 16.4167 14.8667 16.8667L13.4251 17.6917C12.7667 18.0917 11.9167 17.875 11.5167 17.2167L11.4334 17.075C10.6834 15.7667 9.33341 15.7667 8.57508 17.075L8.49175 17.2167C8.09175 17.875 7.24175 18.0917 6.58342 17.6917L5.14175 16.8667C4.38341 16.4167 4.14175 15.4417 4.59175 14.6917C5.35008 13.3833 4.75841 12.3167 3.25008 12.3167C2.37508 12.3167 1.66675 11.6 1.66675 10.7333Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
<path d="M10 12.5C11.3807 12.5 12.5 11.3807 12.5 10C12.5 8.61929 11.3807 7.5 10 7.5C8.61929 7.5 7.5 8.61929 7.5 10C7.5 11.3807 8.61929 12.5 10 12.5Z" stroke="#00000099" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M16.1667 12.5C16.0557 12.7513 16.0227 13.0301 16.0721 13.3006C16.1214 13.5711 16.251 13.8203 16.4417 14.0167L16.4917 14.0667C16.6447 14.2194 16.7658 14.4008 16.8482 14.6006C16.9305 14.8003 16.9725 15.0145 16.9725 15.2308C16.9725 15.4472 16.9305 15.6614 16.8482 15.8611C16.7658 16.0609 16.6447 16.2423 16.4917 16.395C16.339 16.548 16.1576 16.6691 15.9578 16.7514C15.7581 16.8338 15.5439 16.8758 15.3275 16.8758C15.1112 16.8758 14.897 16.8338 14.6972 16.7514C14.4975 16.6691 14.3161 16.548 14.1633 16.395L14.1133 16.345C13.917 16.1543 13.6678 16.0247 13.3973 15.9754C13.1268 15.926 12.848 15.959 12.5967 16.07C12.3503 16.1761 12.1423 16.3521 11.9993 16.5762C11.8563 16.8003 11.7848 17.0625 11.7942 17.3283V17.5C11.7942 17.9421 11.6184 18.3659 11.3059 18.6785C10.9933 18.991 10.5695 19.1667 10.1275 19.1667C9.6854 19.1667 9.26163 18.991 8.94907 18.6785C8.63651 18.3659 8.46083 17.9421 8.46083 17.5V17.425C8.46458 17.1515 8.38642 16.8831 8.23616 16.6542C8.0859 16.4252 7.87016 16.2461 7.61583 16.1383C7.36452 16.0273 7.08571 15.9943 6.81523 16.0437C6.54474 16.093 6.29555 16.2227 6.09917 16.4133L6.04917 16.4633C5.89641 16.6163 5.71499 16.7374 5.51525 16.8198C5.31551 16.9021 5.10132 16.9441 4.88499 16.9441C4.66866 16.9441 4.45447 16.9021 4.25473 16.8198C4.05499 16.7374 3.87357 16.6163 3.72083 16.4633C3.56783 16.3106 3.4467 16.1292 3.36438 15.9294C3.28205 15.7297 3.24005 15.5155 3.24005 15.2992C3.24005 15.0828 3.28205 14.8687 3.36438 14.6689C3.4467 14.4692 3.56783 14.2877 3.72083 14.135L3.77083 14.085C3.96147 13.8886 4.09115 13.6394 4.14049 13.3689C4.18984 13.0985 4.15685 12.8196 4.04583 12.5683C3.93975 12.322 3.76374 12.1139 3.53965 11.9709C3.31556 11.8279 3.05339 11.7564 2.7875 11.7658H2.61583C2.17379 11.7658 1.75001 11.5902 1.43745 11.2776C1.12489 10.965 0.949219 10.5412 0.949219 10.0992C0.949219 9.65712 1.12489 9.23335 1.43745 8.92079C1.75001 8.60823 2.17379 8.43255 2.61583 8.43255H2.69083C2.96438 8.4288 3.23272 8.35065 3.46167 8.20038C3.69063 8.05012 3.86979 7.83438 3.9775 7.58005C4.0885 7.32874 4.12149 7.04993 4.07215 6.77944C4.02281 6.50896 3.89313 6.25977 3.7025 6.06339L3.6525 6.01339C3.4995 5.86063 3.37837 5.67921 3.29604 5.47947C3.21372 5.27973 3.17172 5.06554 3.17172 4.84921C3.17172 4.63288 3.21372 4.41869 3.29604 4.21895C3.37837 4.01921 3.4995 3.83779 3.6525 3.68505C3.80524 3.53205 3.98666 3.41092 4.1864 3.3286C4.38614 3.24627 4.60033 3.20427 4.81666 3.20427C5.03299 3.20427 5.24719 3.24627 5.44693 3.3286C5.64666 3.41092 5.82809 3.53205 5.98083 3.68505L6.03083 3.73505C6.22721 3.92569 6.4764 4.05537 6.74688 4.10472C7.01737 4.15406 7.29618 4.12107 7.5475 4.01005H7.61583C7.86213 3.90397 8.07024 3.72796 8.21324 3.50387C8.35624 3.27978 8.42774 3.01761 8.41833 2.75172V2.58005C8.41833 2.13801 8.59401 1.71424 8.90657 1.40168C9.21913 1.08912 9.6429 0.913452 10.0849 0.913452C10.527 0.913452 10.9507 1.08912 11.2633 1.40168C11.5759 1.71424 11.7515 2.13801 11.7515 2.58005V2.65505C11.7421 2.92094 11.8136 3.18311 11.9566 3.4072C12.0996 3.63129 12.3077 3.8073 12.554 3.91339C12.8053 4.0244 13.0841 4.05739 13.3546 4.00805C13.6251 3.95871 13.8743 3.82903 14.0706 3.63839L14.1206 3.58839C14.2734 3.43539 14.4548 3.31426 14.6545 3.23193C14.8543 3.14961 15.0685 3.10761 15.2848 3.10761C15.5011 3.10761 15.7153 3.14961 15.9151 3.23193C16.1148 3.31426 16.2962 3.43539 16.449 3.58839C16.602 3.74113 16.7231 3.92255 16.8054 4.12229C16.8878 4.32203 16.9298 4.53622 16.9298 4.75255C16.9298 4.96888 16.8878 5.18307 16.8054 5.38281C16.7231 5.58255 16.602 5.76397 16.449 5.91672L16.399 5.96672C16.2084 6.1631 16.0787 6.41229 16.0293 6.68277C15.98 6.95326 16.013 7.23207 16.124 7.48339V7.58005C16.2301 7.82635 16.4061 8.03446 16.6302 8.17746C16.8543 8.32046 17.1164 8.39196 17.3823 8.38255H17.554C17.996 8.38255 18.4198 8.55823 18.7324 8.87079C19.0449 9.18335 19.2206 9.60712 19.2206 10.0492C19.2206 10.4912 19.0449 10.915 18.7324 11.2276C18.4198 11.5401 17.996 11.7158 17.554 11.7158H17.479C17.2131 11.7064 16.951 11.7779 16.7269 11.9209C16.5028 12.0639 16.3268 12.272 16.2206 12.5183V12.5Z" stroke="#00000099" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 4.3 KiB |
|
|
@ -0,0 +1,8 @@
|
|||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="9" cy="9" r="7" stroke="#07C05F" stroke-width="1.2" fill="none"/>
|
||||
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="#07C05F" stroke-width="1.2" fill="none"/>
|
||||
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="#07C05F" stroke-width="1.2" fill="none"/>
|
||||
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="#07C05F" stroke-width="1.2" stroke-linecap="round"/>
|
||||
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="#07C05F" stroke-width="1.2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
||||
|
After Width: | Height: | Size: 576 B |
|
|
@ -0,0 +1,8 @@
|
|||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
||||
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
||||
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
||||
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
|
||||
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
||||
|
After Width: | Height: | Size: 601 B |
|
|
@ -0,0 +1,3 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20" width="128" height="128">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.17736 1.28207C9.32257 1.23367 9.4805 1.24024 9.6212 1.30054L18.3713 5.05054C18.5619 5.13222 18.6995 5.30316 18.7388 5.50681C18.778 5.71045 18.7136 5.9203 18.567 6.06694C18.5138 6.12012 18.4366 6.24314 18.3744 6.46076C18.3146 6.66994 18.2812 6.92361 18.2812 7.1875C18.2812 7.45139 18.3146 7.70506 18.3744 7.91424C18.4366 8.13186 18.5138 8.25487 18.567 8.30806C18.811 8.55214 18.811 8.94786 18.567 9.19194C18.5138 9.24512 18.4366 9.36814 18.3744 9.58576C18.3146 9.79494 18.2812 10.0486 18.2812 10.3125C18.2812 10.5764 18.3146 10.8301 18.3744 11.0392C18.4366 11.2569 18.5138 11.3799 18.567 11.4331C18.811 11.6771 18.811 12.0729 18.567 12.3169C18.5138 12.3701 18.4366 12.4931 18.3744 12.7108C18.3146 12.92 18.2812 13.1736 18.2812 13.4375C18.2812 13.7014 18.3146 13.955 18.3744 14.1642C18.4366 14.3819 18.5138 14.5049 18.567 14.558C18.709 14.7001 18.7741 14.9017 18.7419 15.1001C18.7097 15.2984 18.5843 15.4691 18.4045 15.559L12.1545 18.684C11.9886 18.767 11.7944 18.772 11.6245 18.6976L1.62449 14.3226C1.397 14.2231 1.25 13.9983 1.25 13.75V4.375C1.25 4.10599 1.42215 3.86715 1.67736 3.78207L9.17736 1.28207ZM2.5 5.33064L10.9868 9.04362C10.9627 9.10997 10.9413 9.1765 10.9225 9.24236C10.826 9.58006 10.7812 9.95139 10.7812 10.3125C10.7812 10.6736 10.826 11.0449 10.9225 11.3826C10.9694 11.5469 11.0321 11.7153 11.1153 11.875C11.0321 12.0347 10.9694 12.2031 10.9225 12.3674C10.826 12.705 10.7812 13.0764 10.7812 13.4375C10.7812 13.7986 10.826 14.17 10.9225 14.5076C10.9694 14.6719 11.0321 14.8403 11.1153 15C11.0321 15.1597 10.9694 15.3281 10.9225 15.4924C10.826 15.83 10.7812 16.2014 10.7812 16.5625C10.7812 16.6986 10.7876 16.8361 10.8007 16.9728L2.5 13.3413V5.33064ZM12.1275 17.3C12.1265 17.2964 12.1254 17.2929 12.1244 17.2892C12.0646 17.08 12.0312 16.8264 12.0312 16.5625C12.0312 16.2986 12.0646 16.045 12.1244 15.8358C12.1695 15.6779 12.2225 15.5697 12.2686 15.502L17.0432 13.1146C17.0351 13.2224 17.0312 13.3304 17.0312 13.4375C17.0312 13.7986 17.076 14.17 17.1725 14.5076C17.1944 14.5844 17.2198 14.662 17.249 14.7393L12.1275 17.3ZM17.249 11.6142L12.1275 14.175C12.1265 14.1714 12.1254 14.1679 12.1244 14.1642C12.0646 13.955 12.0312 13.7014 12.0312 13.4375C12.0312 13.1736 12.0646 12.92 12.1244 12.7108C12.1695 12.5529 12.2225 12.4447 12.2686 12.377L17.0432 9.98965C17.0351 10.0974 17.0312 10.2054 17.0312 10.3125C17.0312 10.6736 17.076 11.0449 17.1725 11.3826C17.1944 11.4594 17.2198 11.537 17.249 11.6142ZM17.249 8.48921L12.1275 11.05C12.1265 11.0464 12.1254 11.0428 12.1244 11.0392C12.0646 10.8301 12.0312 10.5764 12.0312 10.3125C12.0312 10.0486 12.0646 9.79494 12.1244 9.58576C12.1695 9.42785 12.2225 9.31975 12.2686 9.252L17.0432 6.86465C17.0351 6.9724 17.0312 7.0804 17.0312 7.1875C17.0312 7.54861 17.076 7.91994 17.1725 8.25764C17.1944 8.33437 17.2198 8.412 17.249 8.48921ZM16.6402 5.66864L9.34721 2.54307L3.61469 4.45391L11.8573 8.06006L16.6402 5.66864Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.3"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.0 KiB |
|
|
@ -1,3 +1,3 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" class="gh6beppe9__design-iconfont" width="128" height="128">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M2 3C2 2.17157 2.67157 1.5 3.5 1.5H12C12.2761 1.5 12.5 1.72386 12.5 2V11C12.5 11.2761 12.2761 11.5 12 11.5H4C3.44772 11.5 3 11.9477 3 12.5C3 13.0523 3.44772 13.5 4 13.5H13V2.5H14V14C14 14.2761 13.7761 14.5 13.5 14.5H4C2.89543 14.5 2 13.6046 2 12.5V3ZM3 10.7676C3.29417 10.5974 3.63571 10.5 4 10.5H11.5V2.5H3.5C3.22386 2.5 3 2.72386 3 3V10.7676ZM12.5 13H3.5V12H12.5V13Z" fill="#32CE3F"></path>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="128" height="128">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M2 3C2 2.17157 2.67157 1.5 3.5 1.5H12C12.2761 1.5 12.5 1.72386 12.5 2V11C12.5 11.2761 12.2761 11.5 12 11.5H4C3.44772 11.5 3 11.9477 3 12.5C3 13.0523 3.44772 13.5 4 13.5H13V2.5H14V14C14 14.2761 13.7761 14.5 13.5 14.5H4C2.89543 14.5 2 13.6046 2 12.5V3ZM3 10.7676C3.29417 10.5974 3.63571 10.5 4 10.5H11.5V2.5H3.5C3.22386 2.5 3 2.72386 3 3V10.7676ZM12.5 13H3.5V12H12.5V13Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.3"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 583 B After Width: | Height: | Size: 578 B |
|
|
@ -0,0 +1,297 @@
|
|||
<template>
|
||||
<div
|
||||
ref="wrapperRef"
|
||||
class="faq-tag-wrapper"
|
||||
@mouseenter="handleMouseEnter"
|
||||
@mouseleave="handleMouseLeave"
|
||||
>
|
||||
<slot />
|
||||
<Teleport to="body">
|
||||
<Transition name="fade">
|
||||
<div
|
||||
v-if="showTooltip && content"
|
||||
ref="tooltipRef"
|
||||
class="faq-tag-tooltip"
|
||||
:class="tooltipClass"
|
||||
:style="tooltipStyle"
|
||||
>
|
||||
<div class="tooltip-content">{{ content }}</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
content: string
|
||||
placement?: 'top' | 'bottom' | 'left' | 'right'
|
||||
type?: 'answer' | 'similar' | 'negative'
|
||||
}>()
|
||||
|
||||
const showTooltip = ref(false)
|
||||
const tooltipRef = ref<HTMLElement | null>(null)
|
||||
const wrapperRef = ref<HTMLElement | null>(null)
|
||||
const tooltipStyle = ref<{ top: string; left: string }>({ top: '0px', left: '0px' })
|
||||
|
||||
const tooltipClass = computed(() => {
|
||||
return {
|
||||
[`tooltip-${props.type || 'answer'}`]: true,
|
||||
[`placement-${props.placement || 'top'}`]: true,
|
||||
}
|
||||
})
|
||||
|
||||
const updatePosition = async () => {
|
||||
if (!wrapperRef.value || !tooltipRef.value) return
|
||||
|
||||
await nextTick()
|
||||
|
||||
// 再次检查,确保DOM已渲染
|
||||
if (!tooltipRef.value) return
|
||||
|
||||
const rect = wrapperRef.value.getBoundingClientRect()
|
||||
const tooltipRect = tooltipRef.value.getBoundingClientRect()
|
||||
const placement = props.placement || 'top'
|
||||
|
||||
let top = 0
|
||||
let left = 0
|
||||
|
||||
switch (placement) {
|
||||
case 'top':
|
||||
top = rect.top - tooltipRect.height - 8
|
||||
left = rect.left + (rect.width / 2) - (tooltipRect.width / 2)
|
||||
break
|
||||
case 'bottom':
|
||||
top = rect.bottom + 8
|
||||
left = rect.left + (rect.width / 2) - (tooltipRect.width / 2)
|
||||
break
|
||||
case 'left':
|
||||
top = rect.top + (rect.height / 2) - (tooltipRect.height / 2)
|
||||
left = rect.left - tooltipRect.width - 8
|
||||
break
|
||||
case 'right':
|
||||
top = rect.top + (rect.height / 2) - (tooltipRect.height / 2)
|
||||
left = rect.right + 8
|
||||
break
|
||||
}
|
||||
|
||||
// 边界检测
|
||||
const padding = 8
|
||||
if (left < padding) left = padding
|
||||
if (left + tooltipRect.width > window.innerWidth - padding) {
|
||||
left = window.innerWidth - tooltipRect.width - padding
|
||||
}
|
||||
if (top < padding) {
|
||||
// 如果上方空间不足,改为下方显示
|
||||
if (placement === 'top') {
|
||||
top = rect.bottom + 8
|
||||
} else {
|
||||
top = padding
|
||||
}
|
||||
}
|
||||
if (top + tooltipRect.height > window.innerHeight - padding) {
|
||||
top = window.innerHeight - tooltipRect.height - padding
|
||||
}
|
||||
|
||||
tooltipStyle.value = {
|
||||
top: `${top}px`,
|
||||
left: `${left}px`,
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
showTooltip.value = true
|
||||
nextTick(() => {
|
||||
updatePosition()
|
||||
})
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
showTooltip.value = false
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('scroll', updatePosition, true)
|
||||
window.addEventListener('resize', updatePosition)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('scroll', updatePosition, true)
|
||||
window.removeEventListener('resize', updatePosition)
|
||||
})
|
||||
|
||||
watch(showTooltip, (newVal) => {
|
||||
if (newVal) {
|
||||
nextTick(() => {
|
||||
updatePosition()
|
||||
})
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.faq-tag-wrapper {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
overflow: visible;
|
||||
flex-shrink: 1;
|
||||
flex: 0 1 auto;
|
||||
|
||||
// 确保内部的tag也能正确收缩
|
||||
:deep(.t-tag) {
|
||||
max-width: 100% !important;
|
||||
min-width: 0 !important;
|
||||
width: auto !important;
|
||||
display: inline-flex !important;
|
||||
}
|
||||
|
||||
:deep(.t-tag span),
|
||||
:deep(.t-tag > span) {
|
||||
display: block !important;
|
||||
overflow: hidden !important;
|
||||
text-overflow: ellipsis !important;
|
||||
white-space: nowrap !important;
|
||||
max-width: 100% !important;
|
||||
min-width: 0 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.faq-tag-tooltip {
|
||||
position: fixed;
|
||||
z-index: 9999;
|
||||
max-width: 320px;
|
||||
min-width: 100px;
|
||||
padding: 10px 14px;
|
||||
background: #FFFFFF;
|
||||
color: #000000e6;
|
||||
border: 1px solid #e7ebf0;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.08);
|
||||
font-family: "PingFang SC";
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
line-height: 1.6;
|
||||
word-break: break-word;
|
||||
pointer-events: none;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&.placement-top::before {
|
||||
bottom: -10px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
border-top-color: #e7ebf0;
|
||||
}
|
||||
|
||||
&.placement-top::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -9px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 0;
|
||||
height: 0;
|
||||
border: 5px solid transparent;
|
||||
border-top-color: #FFFFFF;
|
||||
}
|
||||
|
||||
&.placement-bottom::before {
|
||||
top: -10px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
border-bottom-color: #e7ebf0;
|
||||
}
|
||||
|
||||
&.placement-bottom::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -9px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 0;
|
||||
height: 0;
|
||||
border: 5px solid transparent;
|
||||
border-bottom-color: #FFFFFF;
|
||||
}
|
||||
|
||||
&.placement-left::before {
|
||||
right: -10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
border-left-color: #e7ebf0;
|
||||
}
|
||||
|
||||
&.placement-left::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -9px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 0;
|
||||
height: 0;
|
||||
border: 5px solid transparent;
|
||||
border-left-color: #FFFFFF;
|
||||
}
|
||||
|
||||
&.placement-right::before {
|
||||
left: -10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
border-right-color: #e7ebf0;
|
||||
}
|
||||
|
||||
&.placement-right::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -9px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 0;
|
||||
height: 0;
|
||||
border: 5px solid transparent;
|
||||
border-right-color: #FFFFFF;
|
||||
}
|
||||
|
||||
// 所有类型使用统一的常规边框颜色
|
||||
&.tooltip-answer,
|
||||
&.tooltip-similar,
|
||||
&.tooltip-negative {
|
||||
// 边框和箭头颜色已在主样式中定义为 #e7ebf0
|
||||
// 无需额外覆盖
|
||||
}
|
||||
}
|
||||
|
||||
.tooltip-content {
|
||||
color: #000000e6;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
|
||||
.fade-enter-from {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
|
@ -0,0 +1,500 @@
|
|||
<template>
|
||||
<div v-if="visible" class="kb-overlay" @click="close">
|
||||
<div class="kb-dropdown" @click.stop @wheel.stop :style="dropdownStyle">
|
||||
<!-- 搜索 -->
|
||||
<div class="kb-search">
|
||||
<input
|
||||
ref="searchInput"
|
||||
v-model="searchQuery"
|
||||
type="text"
|
||||
:placeholder="$t('knowledgeBase.searchPlaceholder')"
|
||||
class="kb-search-input"
|
||||
@keydown.down.prevent="moveSelection(1)"
|
||||
@keydown.up.prevent="moveSelection(-1)"
|
||||
@keydown.enter.prevent="toggleSelection"
|
||||
@keydown.esc="close"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="kb-list" ref="kbList" @wheel.stop>
|
||||
<div
|
||||
v-for="(kb, index) in filteredKnowledgeBases"
|
||||
:key="kb.id"
|
||||
:class="['kb-item', { selected: isSelected(kb.id), highlighted: highlightedIndex === index }]"
|
||||
@click="toggleKb(kb.id)"
|
||||
@mouseenter="highlightedIndex = index"
|
||||
>
|
||||
<div class="kb-item-left">
|
||||
<div class="checkbox" :class="{ checked: isSelected(kb.id) }">
|
||||
<svg v-if="isSelected(kb.id)" width="12" height="12" viewBox="0 0 12 12" fill="none">
|
||||
<path d="M10 3L4.5 8.5L2 6" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="kb-icon" :class="{ 'faq': kb.type === 'faq' }">
|
||||
<svg v-if="kb.type === 'faq'" width="14" height="14" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M9 9C9 7.89543 9.89543 7 11 7H13C14.1046 7 15 7.89543 15 9C15 10.1046 14.1046 11 13 11H12V14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="12" cy="17" r="1" fill="currentColor"/>
|
||||
</svg>
|
||||
<svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M22 19C22 19.5304 21.7893 20.0391 21.4142 20.4142C21.0391 20.7893 20.5304 21 20 21H4C3.46957 21 2.96086 20.7893 2.58579 20.4142C2.21071 20.0391 2 19.5304 2 19V5C2 4.46957 2.21071 3.96086 2.58579 3.58579C2.96086 3.21071 3.46957 3 4 3H9L11 6H20C20.5304 6 21.0391 6.21071 21.4142 6.58579C21.7893 6.96086 22 7.46957 22 8V19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="kb-name-wrap">
|
||||
<span class="kb-name">{{ kb.name }}</span>
|
||||
<span class="kb-docs">({{ kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0) }})</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="filteredKnowledgeBases.length === 0" class="kb-empty">
|
||||
{{ searchQuery ? $t('knowledgeBase.noMatch') : $t('knowledgeBase.noKnowledge') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部操作 -->
|
||||
<div class="kb-actions">
|
||||
<button @click="selectAll" class="kb-btn">{{ $t('common.selectAll') }}</button>
|
||||
<button @click="clearAll" class="kb-btn">{{ $t('common.clear') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, nextTick } from 'vue'
|
||||
import { useSettingsStore } from '@/stores/settings'
|
||||
import { listKnowledgeBases } from '@/api/knowledge-base'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
interface KnowledgeBase {
|
||||
id: string
|
||||
name: string
|
||||
type?: 'document' | 'faq'
|
||||
knowledge_count?: number
|
||||
chunk_count?: number
|
||||
embedding_model_id?: string
|
||||
summary_model_id?: string
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
anchorEl?: any | null // 支持 DOM 节点、ref、组件实例
|
||||
dropdownWidth?: number
|
||||
offsetY?: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits(['close', 'update:visible'])
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
// 本地状态
|
||||
const searchQuery = ref('')
|
||||
const highlightedIndex = ref(0)
|
||||
const knowledgeBases = ref<KnowledgeBase[]>([])
|
||||
const searchInput = ref<HTMLInputElement | null>(null)
|
||||
const kbList = ref<HTMLElement | null>(null)
|
||||
const dropdownStyle = ref<Record<string, string>>({})
|
||||
|
||||
// props 默认
|
||||
const dropdownWidth = props.dropdownWidth ?? 300
|
||||
const offsetY = props.offsetY ?? 8
|
||||
|
||||
// 过滤:只显示已初始化(有 embedding & summary)的
|
||||
const filteredKnowledgeBases = computed(() => {
|
||||
const valid = knowledgeBases.value.filter(
|
||||
k => k.embedding_model_id && k.summary_model_id
|
||||
)
|
||||
if (!searchQuery.value) return valid
|
||||
const q = searchQuery.value.toLowerCase()
|
||||
return valid.filter(k => k.name.toLowerCase().includes(q))
|
||||
})
|
||||
|
||||
const selectedKbIds = computed(() => settingsStore.settings.selectedKnowledgeBases || [])
|
||||
|
||||
// helper: 从 props.anchorEl 获取真实 DOM 元素(支持多种传入形式)
|
||||
const resolveAnchorEl = () => {
|
||||
const a = props.anchorEl
|
||||
if (!a) return null
|
||||
// 如果是 Vue ref:取 .value
|
||||
if (typeof a === 'object' && 'value' in a) {
|
||||
return a.value ?? null
|
||||
}
|
||||
// 如果是组件实例(可能有 $el)
|
||||
if (typeof a === 'object' && '$el' in a) {
|
||||
// @ts-ignore
|
||||
return a.$el ?? null
|
||||
}
|
||||
// 直接 DOM 节点或 DOMRect
|
||||
return a
|
||||
}
|
||||
|
||||
const isSelected = (id: string) => selectedKbIds.value.includes(id)
|
||||
|
||||
const toggleKb = (id: string) => {
|
||||
isSelected(id) ? settingsStore.removeKnowledgeBase(id) : settingsStore.addKnowledgeBase(id)
|
||||
}
|
||||
|
||||
const toggleSelection = () => {
|
||||
const kb = filteredKnowledgeBases.value[highlightedIndex.value]
|
||||
if (kb) toggleKb(kb.id)
|
||||
}
|
||||
|
||||
const moveSelection = (dir: number) => {
|
||||
const max = filteredKnowledgeBases.value.length
|
||||
if (max === 0) return
|
||||
highlightedIndex.value = Math.max(0, Math.min(max - 1, highlightedIndex.value + dir))
|
||||
nextTick(() => {
|
||||
const items = kbList.value?.querySelectorAll('.kb-item')
|
||||
items?.[highlightedIndex.value]?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
|
||||
})
|
||||
}
|
||||
|
||||
const selectAll = () => settingsStore.selectKnowledgeBases(filteredKnowledgeBases.value.map(k => k.id))
|
||||
const clearAll = () => settingsStore.clearKnowledgeBases()
|
||||
|
||||
const close = () => {
|
||||
emit('update:visible', false)
|
||||
emit('close')
|
||||
}
|
||||
|
||||
const loadKnowledgeBases = async () => {
|
||||
try {
|
||||
const res: any = await listKnowledgeBases()
|
||||
if (res?.data && Array.isArray(res.data)) knowledgeBases.value = res.data
|
||||
} catch (e) {
|
||||
console.error(t('knowledgeBase.loadingFailed'), e)
|
||||
}
|
||||
}
|
||||
|
||||
// 计算下拉位置:水平居中对齐到按钮中点,处理视口边界
|
||||
const updateDropdownPosition = () => {
|
||||
const anchor = resolveAnchorEl()
|
||||
|
||||
// fallback 函数
|
||||
const applyFallback = () => {
|
||||
const vw = window.innerWidth;
|
||||
const topFallback = Math.max(80, window.innerHeight / 2 - 160);
|
||||
dropdownStyle.value = {
|
||||
position: 'fixed',
|
||||
width: `${dropdownWidth}px`,
|
||||
left: `${Math.round((vw - dropdownWidth) / 2)}px`,
|
||||
top: `${Math.round(topFallback)}px`,
|
||||
transform: 'none',
|
||||
margin: '0',
|
||||
padding: '0',
|
||||
};
|
||||
};
|
||||
|
||||
if (!anchor) {
|
||||
applyFallback()
|
||||
return
|
||||
}
|
||||
|
||||
// 获取 anchor 的 bounding rect(相对于视口)
|
||||
let rect: DOMRect | null = null
|
||||
try {
|
||||
if (typeof anchor.getBoundingClientRect === 'function') {
|
||||
rect = anchor.getBoundingClientRect()
|
||||
console.log('[KB Selector] Button rect:', {
|
||||
top: rect.top,
|
||||
bottom: rect.bottom,
|
||||
left: rect.left,
|
||||
right: rect.right,
|
||||
width: rect.width,
|
||||
height: rect.height
|
||||
})
|
||||
} else if (anchor.width !== undefined && anchor.left !== undefined) {
|
||||
// 已经是 DOMRect
|
||||
rect = anchor as DOMRect
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[KnowledgeBaseSelector] Error getting bounding rect:', e)
|
||||
}
|
||||
|
||||
if (!rect || rect.width === 0 || rect.height === 0) {
|
||||
applyFallback()
|
||||
return
|
||||
}
|
||||
|
||||
const vw = window.innerWidth
|
||||
const vh = window.innerHeight
|
||||
|
||||
// 左对齐到触发元素的左边缘
|
||||
// 使用 Math.floor 而不是 Math.round,避免像素对齐问题
|
||||
let left = Math.floor(rect.left)
|
||||
|
||||
// 边界处理:不超出视口左右(留 16px margin)
|
||||
const minLeft = 16
|
||||
const maxLeft = Math.max(16, vw - dropdownWidth - 16)
|
||||
left = Math.max(minLeft, Math.min(maxLeft, left))
|
||||
|
||||
// 垂直定位:紧贴按钮,使用合理的高度避免空白
|
||||
const preferredDropdownHeight = 280 // 优选高度(紧凑且够用)
|
||||
const maxDropdownHeight = 360 // 最大高度
|
||||
const minDropdownHeight = 200 // 最小高度
|
||||
const topMargin = 20 // 顶部留白
|
||||
const spaceBelow = vh - rect.bottom // 下方剩余空间
|
||||
const spaceAbove = rect.top // 上方剩余空间
|
||||
|
||||
console.log('[KB Selector] Space check:', {
|
||||
spaceBelow,
|
||||
spaceAbove,
|
||||
windowHeight: vh
|
||||
})
|
||||
|
||||
let actualHeight: number
|
||||
let shouldOpenBelow: boolean
|
||||
|
||||
// 优先考虑下方空间
|
||||
if (spaceBelow >= minDropdownHeight + offsetY) {
|
||||
// 下方有足够空间,向下弹出
|
||||
actualHeight = Math.min(preferredDropdownHeight, spaceBelow - offsetY - 16)
|
||||
shouldOpenBelow = true
|
||||
console.log('[KB Selector] Position: below button', { actualHeight })
|
||||
} else {
|
||||
// 向上弹出,优先使用 preferredHeight,必要时才扩展到 maxHeight
|
||||
const availableHeight = spaceAbove - offsetY - topMargin
|
||||
if (availableHeight >= preferredDropdownHeight) {
|
||||
// 有足够空间显示优选高度
|
||||
actualHeight = preferredDropdownHeight
|
||||
} else {
|
||||
// 空间不够,使用可用空间(但不小于最小高度)
|
||||
actualHeight = Math.max(minDropdownHeight, availableHeight)
|
||||
}
|
||||
shouldOpenBelow = false
|
||||
console.log('[KB Selector] Position: above button', { actualHeight })
|
||||
}
|
||||
|
||||
// 根据弹出方向使用不同的定位方式
|
||||
if (shouldOpenBelow) {
|
||||
// 向下弹出:使用 top 定位
|
||||
const top = Math.floor(rect.bottom + offsetY)
|
||||
console.log('[KB Selector] Opening below, top:', top)
|
||||
dropdownStyle.value = {
|
||||
position: 'fixed',
|
||||
width: `${dropdownWidth}px`,
|
||||
left: `${left}px`,
|
||||
top: `${top}px`,
|
||||
maxHeight: `${actualHeight}px`,
|
||||
transform: 'none',
|
||||
margin: '0',
|
||||
padding: '0'
|
||||
}
|
||||
} else {
|
||||
// 向上弹出:使用 bottom 定位
|
||||
const bottom = vh - rect.top + offsetY
|
||||
console.log('[KB Selector] Opening above, bottom:', bottom)
|
||||
dropdownStyle.value = {
|
||||
position: 'fixed',
|
||||
width: `${dropdownWidth}px`,
|
||||
left: `${left}px`,
|
||||
bottom: `${bottom}px`,
|
||||
maxHeight: `${actualHeight}px`,
|
||||
transform: 'none',
|
||||
margin: '0',
|
||||
padding: '0'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 事件监听器引用,用于清理
|
||||
let resizeHandler: (() => void) | null = null
|
||||
let scrollHandler: (() => void) | null = null
|
||||
|
||||
// 当 visible 变化时处理
|
||||
watch(() => props.visible, async (v) => {
|
||||
if (v) {
|
||||
await loadKnowledgeBases();
|
||||
// 等 DOM 渲染完再计算位置
|
||||
await nextTick();
|
||||
// 多次更新位置确保准确
|
||||
requestAnimationFrame(() => {
|
||||
updateDropdownPosition();
|
||||
requestAnimationFrame(() => {
|
||||
updateDropdownPosition();
|
||||
setTimeout(() => {
|
||||
updateDropdownPosition();
|
||||
}, 50);
|
||||
});
|
||||
});
|
||||
// 确保 focus
|
||||
nextTick(() => searchInput.value?.focus());
|
||||
// 监听 resize/scroll 做微调(使用 passive 提高性能)
|
||||
resizeHandler = () => updateDropdownPosition();
|
||||
scrollHandler = () => updateDropdownPosition();
|
||||
window.addEventListener('resize', resizeHandler, { passive: true });
|
||||
window.addEventListener('scroll', scrollHandler, { passive: true, capture: true });
|
||||
} else {
|
||||
searchQuery.value = '';
|
||||
highlightedIndex.value = 0;
|
||||
// 清理事件监听器
|
||||
if (resizeHandler) {
|
||||
window.removeEventListener('resize', resizeHandler);
|
||||
resizeHandler = null;
|
||||
}
|
||||
if (scrollHandler) {
|
||||
window.removeEventListener('scroll', scrollHandler, { capture: true });
|
||||
scrollHandler = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
// 确保所有元素使用 border-box 盒模型
|
||||
.kb-overlay,
|
||||
.kb-overlay *,
|
||||
.kb-overlay *::before,
|
||||
.kb-overlay *::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.kb-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9999;
|
||||
background: transparent;
|
||||
/* 不阻止点击穿透,但防止触摸滚动 */
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
/* 下拉面板使用 fixed 定位,相对于视口 */
|
||||
.kb-dropdown {
|
||||
position: fixed !important;
|
||||
background: #fff;
|
||||
border: 1px solid #e7e9eb;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 6px 28px rgba(15, 23, 42, 0.08);
|
||||
overflow: hidden;
|
||||
animation: fadeIn 0.15s ease-out;
|
||||
z-index: 10000;
|
||||
margin: 0;
|
||||
/* 确保定位准确,动画使用 scale 而不是 translate */
|
||||
transform-origin: top left;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 宽度由 JS 控制(dropdownWidth),这里只做内部样式 */
|
||||
.kb-search {
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid #f1f3f4;
|
||||
}
|
||||
.kb-search-input {
|
||||
width: 100%;
|
||||
padding: 6px 10px;
|
||||
font-size: 12px;
|
||||
border: 1px solid #eef1f2;
|
||||
border-radius: 6px;
|
||||
background: #fbfdfc;
|
||||
outline: none;
|
||||
transition: border 0.12s;
|
||||
}
|
||||
.kb-search-input:focus {
|
||||
border-color: #10b981;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.kb-list {
|
||||
flex: 1;
|
||||
min-height: 0; /* 允许 flex 子元素缩小 */
|
||||
max-height: 260px;
|
||||
overflow-y: auto;
|
||||
padding: 6px 8px;
|
||||
/* 确保滚动限制在此容器内 */
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.kb-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.kb-item:last-child { margin-bottom: 0; }
|
||||
|
||||
.kb-item:hover,
|
||||
.kb-item.highlighted { background: #f6f8f7; }
|
||||
|
||||
.kb-item.selected { background: #eefdf5; }
|
||||
|
||||
.kb-item-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
width: 16px; height: 16px;
|
||||
border-radius: 3px;
|
||||
border: 1.5px solid #d7dadd;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.checkbox.checked {
|
||||
background: #10b981;
|
||||
border-color: #10b981;
|
||||
}
|
||||
.checkbox.checked svg {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
.kb-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
color: #059669;
|
||||
|
||||
&.faq {
|
||||
color: #0052d9;
|
||||
}
|
||||
}
|
||||
.kb-name-wrap { display:flex; flex-direction: row; align-items: center; gap: 4px; min-width: 0; }
|
||||
.kb-name { font-size: 12px; color: #222; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.4; }
|
||||
.kb-docs { font-size: 11px; color: #8b9196; flex-shrink: 0; }
|
||||
|
||||
.kb-empty { padding: 20px 8px; text-align: center; color: #9aa0a6; font-size: 12px; }
|
||||
|
||||
.kb-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
border-top: 1px solid #f2f4f5;
|
||||
background: #fafcfc;
|
||||
}
|
||||
.kb-btn {
|
||||
flex: 1;
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #e1e5e6;
|
||||
background: #fff;
|
||||
font-size: 12px;
|
||||
color: #52575a;
|
||||
cursor: pointer;
|
||||
transition: all 0.12s;
|
||||
}
|
||||
.kb-btn:hover {
|
||||
border-color: #10b981;
|
||||
color: #10b981;
|
||||
background: #f0fdf6;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: scale(0.98); }
|
||||
to { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
<template>
|
||||
<div class="language-switcher">
|
||||
<t-select
|
||||
v-model="selectedLanguage"
|
||||
:options="languageOptions"
|
||||
@change="handleLanguageChange"
|
||||
:popup-props="{ overlayClassName: 'language-select-popup' }"
|
||||
size="small"
|
||||
>
|
||||
<template #prefixIcon>
|
||||
<t-icon name="translate" />
|
||||
</template>
|
||||
</t-select>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { locale } = useI18n()
|
||||
|
||||
const languageOptions = [
|
||||
{ label: '中文', value: 'zh-CN' },
|
||||
{ label: 'English', value: 'en-US' },
|
||||
{ label: 'Русский', value: 'ru-RU' }
|
||||
]
|
||||
|
||||
const selectedLanguage = ref(localStorage.getItem('locale') || 'zh-CN')
|
||||
|
||||
const handleLanguageChange = (value: string) => {
|
||||
console.log('Язык изменен на:', value)
|
||||
if (value && ['ru-RU', 'en-US', 'zh-CN'].includes(value)) {
|
||||
locale.value = value
|
||||
localStorage.setItem('locale', value)
|
||||
// Перезагрузка страницы для применения нового языка
|
||||
setTimeout(() => {
|
||||
window.location.reload()
|
||||
}, 100)
|
||||
}
|
||||
}
|
||||
|
||||
// Синхронизация с i18n при инициализации
|
||||
watch(() => locale.value, (newLocale) => {
|
||||
if (selectedLanguage.value !== newLocale) {
|
||||
selectedLanguage.value = newLocale
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.language-switcher {
|
||||
.t-button {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
|
||||
&:hover {
|
||||
color: #333;
|
||||
background-color: rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
}
|
||||
|
||||
.t-icon {
|
||||
margin-right: 4px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||