Casibase项目API接口详解与使用指南
概述
Casibase是一个开源的企业级AI知识库和MCP(Model-Context-Protocol)/A2A(Agent-to-Agent)管理平台,提供丰富的RESTful API接口。本文详细解析Casibase的核心API接口,并提供完整的使用指南。
API基础信息
基础路径
所有API接口的基础路径为 /api
认证方式
Casibase使用Casdoor进行身份认证,支持OAuth 2.0和JWT(JSON Web Token)认证
响应格式
{
"status": "ok/error",
"msg": "消息内容",
"data": "响应数据",
"data2": "额外数据"
}
核心API接口分类
1. 应用管理API (Application API)
添加应用
POST /api/add-application
Content-Type: application/json
{
"name": "my-app",
"displayName": "我的应用",
"description": "这是一个示例应用",
"type": "chat",
"provider": "ai-platform",
"model": "gpt-4"
}
获取应用列表
GET /api/get-applications
删除应用
POST /api/delete-application
Content-Type: application/json
{
"name": "my-app"
}
2. 聊天管理API (Chat API)
创建聊天会话
POST /api/add-chat
Content-Type: application/json
{
"name": "tech-support",
"displayName": "技术支持聊天",
"application": "my-app",
"messages": []
}
发送消息
POST /api/add-message
Content-Type: application/json
{
"chat": "tech-support",
"text": "你好,我需要技术支持",
"user": "current-user",
"author": "user"
}
AI平台兼容接口
POST /api/api/chat/completions
Content-Type: application/json
{
"model": "gpt-4",
"messages": [
{"role": "user", "content": "你好"}
],
"temperature": 0.7
}
3. 文件管理API (File API)
上传文件
POST /api/add-file?store=default&key=documents&isLeaf=true&filename=manual.pdf
激活文件
POST /api/activate-file?key=documents&filename=manual.pdf
获取文件树
GET /api/get-file-tree?store=default&key=documents
4. 向量存储API (Vector API)
添加向量
POST /api/add-vector
Content-Type: application/json
{
"name": "document-embedding",
"text": "这是文档内容...",
"vector": [0.1, 0.2, 0.3, ...],
"metadata": {
"source": "manual.pdf",
"page": 1
}
}
批量添加向量
POST /api/add-vectors
Content-Type: application/json
[
{
"name": "doc1",
"text": "内容1",
"vector": [...]
},
{
"name": "doc2",
"text": "内容2",
"vector": [...]
}
]
删除所有向量
POST /api/delete-all-vectors
5. 记录管理API (Record API)
添加记录
POST /api/add-record
Content-Type: application/json
{
"name": "user-interaction-001",
"type": "chat",
"content": "用户咨询产品功能",
"metadata": {
"user": "john",
"timestamp": "2024-01-01T10:00:00Z"
}
}
批量添加记录
POST /api/add-records
Content-Type: application/json
[
{
"name": "record-001",
"type": "log",
"content": "系统启动"
},
{
"name": "record-002",
"type": "error",
"content": "连接超时"
}
]
提交记录
POST /api/commit-record
Content-Type: application/json
{
"name": "user-interaction-001",
"status": "completed"
}
6. 模型提供商API (Provider API)
添加提供商
POST /api/add-provider
Content-Type: application/json
{
"name": "ai-platform-prod",
"type": "ai-platform",
"category": "model",
"clientId": "your-client-id",
"clientSecret": "your-client-secret",
"endpoint": "https://api.ai-platform.com/v1"
}
获取提供商列表
GET /api/get-providers
7. 存储管理API (Store API)
添加存储
POST /api/add-store
Content-Type: application/json
{
"name": "knowledge-base",
"displayName": "知识库存储",
"type": "vector",
"provider": "pinecone",
"configuration": {
"index": "main-index",
"environment": "us-west1"
}
}
API使用示例
Python客户端示例
import requests
import json
class CasibaseClient:
def __init__(self, base_url, token):
self.base_url = base_url.rstrip('/')
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def create_chat(self, name, application):
url = f"{self.base_url}/api/add-chat"
data = {
"name": name,
"application": application,
"displayName": f"Chat {name}"
}
response = requests.post(url, json=data, headers=self.headers)
return response.json()
def send_message(self, chat_name, message):
url = f"{self.base_url}/api/add-message"
data = {
"chat": chat_name,
"text": message,
"author": "user"
}
response = requests.post(url, json=data, headers=self.headers)
return response.json()
def ai_platform_completion(self, messages, model="gpt-4"):
url = f"{self.base_url}/api/api/chat/completions"
data = {
"model": model,
"messages": messages,
"temperature": 0.7
}
response = requests.post(url, json=data, headers=self.headers)
return response.json()
# 使用示例
client = CasibaseClient("https://your-casibase-instance.com", "your-auth-token")
# 创建聊天
chat = client.create_chat("support-chat", "my-app")
# 发送消息
response = client.send_message("support-chat", "你好,我需要帮助")
# 使用AI平台兼容接口
messages = [{"role": "user", "content": "解释一下机器学习"}]
completion = client.ai_platform_completion(messages)
JavaScript/Node.js客户端示例
const axios = require('axios');
class CasibaseClient {
constructor(baseUrl, token) {
this.client = axios.create({
baseURL: baseUrl,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
}
async getApplications() {
const response = await this.client.get('/api/get-applications');
return response.data;
}
async addVector(name, text, embedding, metadata = {}) {
const data = {
name,
text,
vector: embedding,
metadata
};
const response = await this.client.post('/api/add-vector', data);
return response.data;
}
async chatCompletion(messages, model = 'gpt-4') {
const data = {
model,
messages,
temperature: 0.7
};
const response = await this.client.post('/api/api/chat/completions', data);
return response.data;
}
}
// 使用示例
const client = new CasibaseClient('https://your-casibase-instance.com', 'your-token');
async function main() {
// 获取应用列表
const apps = await client.getApplications();
console.log('Applications:', apps);
// 添加向量数据
const vector = await client.addVector(
'doc-001',
'这是文档内容',
[0.1, 0.2, 0.3], // 假设的嵌入向量
{ source: 'manual.pdf' }
);
// 使用聊天补全
const completion = await client.chatCompletion([
{ role: 'user', content: '你好,AI助手' }
]);
console.log('Completion:', completion);
}
错误处理与状态码
常见HTTP状态码
| 状态码 | 含义 | 描述 |
|---|---|---|
| 200 | OK | 请求成功 |
| 400 | Bad Request | 请求参数错误 |
| 401 | Unauthorized | 未认证 |
| 403 | Forbidden | 权限不足 |
| 404 | Not Found | 资源不存在 |
| 500 | Internal Server Error | 服务器内部错误 |
错误响应示例
{
"status": "error",
"msg": "Authentication failed: invalid token",
"data": null
}
最佳实践
1. 认证管理
# 定期刷新token
def refresh_token():
# 实现token刷新逻辑
pass
# 添加请求重试机制
def make_request_with_retry(url, data, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.post(url, json=data, headers=headers)
if response.status_code == 401:
refresh_token()
continue
return response.json()
except requests.exceptions.RequestException:
if attempt == max_retries - 1:
raise
2. 批量操作优化
// 批量添加记录时使用分页
async function batchAddRecords(records, batchSize = 100) {
for (let i = 0; i < records.length; i += batchSize) {
const batch = records.slice(i, i + batchSize);
await client.addRecords(batch);
// 添加延迟避免服务器过载
await new Promise(resolve => setTimeout(resolve, 100));
}
}
3. 性能监控
import time
import statistics
class PerformanceMonitor:
def __init__(self):
self.latencies = []
def track_latency(self, func, *args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
latency = time.time() - start_time
self.latencies.append(latency)
return result
def get_stats(self):
return {
'count': len(self.latencies),
'avg': statistics.mean(self.latencies) if self.latencies else 0,
'max': max(self.latencies) if self.latencies else 0,
'min': min(self.latencies) if self.latencies else 0
}
安全注意事项
- Token保护: 不要将认证token硬编码在客户端代码中
- 输入验证: 对所有用户输入进行验证和清理
- 速率限制: 实现适当的请求速率限制
- 错误处理: 不要向客户端暴露详细的错误信息
- HTTPS: 始终使用HTTPS进行API通信
总结
Casibase提供了丰富而强大的API接口,涵盖了AI知识库管理的各个方面。通过合理使用这些API,开发者可以构建强大的AI应用、知识管理系统和智能对话平台。本文提供的示例和最佳实践将帮助您快速上手并高效使用Casibase API。
记住始终遵循API使用的最佳实践,包括适当的错误处理、性能监控和安全措施,以确保应用的稳定性和安全性。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



