接口 v8 - 高级版
v8 接口是高级版本,提供企业级 AI 聊天功能和知识库集成。
注意:接口 v8 使用专用的接口规范,不兼容 OpenAI API。如需 OpenAI 兼容性,请使用 v1 接口。
概述
v8 接口提供高级功能,包括:
- 持久化对话管理:支持对话的创建、更新、删除
- 知识库集成:完整的记忆系统和语义搜索
- 工具调用支持:函数调用和工具集成
- 多模态支持:文本、图像、文档、音频处理
- 高级认证:复杂令牌系统和权限管理
- 流式响应:实时流式传输支持
认证
所有 API 请求都需要使用特殊外部令牌格式的 Bearer 令牌认证。
令牌格式
令牌必须以 ek-(普通用户)或 ak-(管理员)为前缀,后跟 base64 编码的 JSON 对象:
# 普通用户令牌
Authorization: Bearer ek-<base64_encoded_json>
# 管理员令牌(用于管理操作)
Authorization: Bearer ak-<base64_encoded_json>
令牌结构
base64 编码的 JSON 包含:
{
"hash": "md5_签名", //必填
"app_id": "您的集成ID", //必填
"user_id": "外部用户ID", //必填
"user_name": "外部用户名", //选填
"expired_time": 1782897155 //必填,秒级的时间戳格式
}
令牌生成
- 从管理面板获取您集成的
hash_token(普通用户)或admin_token(管理员)和app_id - 使用您的
user_id、可选的user_name和expired_time创建 JSON 负载 - 生成 MD5 哈希:
- 普通用户:
md5(hash_token + app_id + user_id + expired_time) - 管理员用户:
md5(admin_token + app_id + user_id + expired_time)
- 普通用户:
- Base64 编码完整的 JSON
- 添加
ek-(普通用户)或ak-(管理员)前缀
令牌生成示例 (JavaScript)
import CryptoJS from "crypto-js";
function generateToken(token, appId, userId, expiredTime, userName = null, isAdmin = false) {
// 创建签名
const message = token + appId + userId + expiredTime;
const hash = CryptoJS.MD5(message).toString();
// 创建负载
const payload = {
hash: hash,
app_id: appId,
user_id: userId,
expired_time: expiredTime,
};
// 如果提供了用户名,添加到负载中
if (userName) {
payload.user_name = userName;
}
// 编码并返回
const encoded = btoa(JSON.stringify(payload));
const prefix = isAdmin ? "ak-" : "ek-";
return `${prefix}${encoded}`;
}
// 使用示例:
// 普通用户令牌
const userToken = generateToken(hashToken, appId, userId, expiredTime, userName, false);
// 管理员令牌
const adminToken = generateToken(adminToken, appId, userId, expiredTime, userName, true);
基础 URL
所有 API 端点都以以下前缀开头:
https://[your-dathor-instance.com]/v8
端点概览
模型
GET /models- 列出可用 AI 模型
对话管理
GET /chat/conversations- 获取用户的所有对话POST /chat/conversations- 创建新对话GET /chat/conversations/:conversation_id- 获取特定对话PUT /chat/conversations/:conversation_id- 更新对话标题和自定义数据DELETE /chat/conversations/:conversation_id- 删除对话
消息操作
POST /chat/conversations/:conversation_id/messages- 发送消息并获取AI响应GET /chat/conversations/:conversation_id/messages- 获取对话中的所有消息DELETE /chat/conversations/:conversation_id/messages- 删除对话中的所有消息DELETE /chat/conversations/:conversation_id/messages/:message_id- 删除特定消息
实用工具
POST /chat/conversations/:conversation_id/generate-title- 自动生成对话标题
文件
POST /files/extract- 从上传的文件中提取文本内容
记忆(知识库)
GET /memories- 获取可用记忆库列表POST /memories- 创建新记忆库(仅限管理员)GET /memories/:memory_id- 获取记忆库详情PUT /memories/:memory_id- 更新记忆库(仅限管理员)DELETE /memories/:memory_id- 删除记忆库(仅限管理员)GET /memories/:memory_id/contents- 获取记忆库内容列表POST /memories/:memory_id/contents-filter- 使用高级过滤功能获取内容列表(推荐方式)GET /memories/:memory_id/contents/:content_id- 获取记忆库中的特定内容GET /memories/:memory_id/contents/:content_id/chunks- 获取特定内容的所有分块(仅限管理员)POST /memories/:memory_id/contents- 在记忆库中创建内容(仅限管理员)PUT /memories/:memory_id/contents/:content_id- 更新记忆库中的内容(仅限管理员)DELETE /memories/:memory_id/contents/:content_id- 删除记忆库中的内容(仅限管理员)POST /memories/:memory_id/embeddings-search-chunks- 使用嵌入相似度搜索分块POST /memories/:memory_id/embeddings-search-contents- 使用嵌入相似度搜索内容
模型
GET /models
获取可用 AI 模型列表。
响应:
[
{
"id": "gpt-4o-mini",
"object": "model",
"created": 1677610602,
"owned_by": "openai"
}
]
对话
GET /chat/conversations
获取认证用户的所有对话。
响应:
[
{
"id": "uuid",
"integration_id": "uuid",
"external_user_id": "string",
"title": "对话标题",
"settings": {
"model": "gpt-4o-mini",
"temperature": 0.7,
"max_tokens": 4096,
"top_p": 0,
"frequency_penalty": 0,
"presence_penalty": 0,
"prompt": null,
"history_messages_count": 10
},
"reference_settings": {
"memories": {
"collections": [],
"content_filter": null,
"min_similarity": 0.5,
"limit": 5,
"unmatch_message": null
}
},
"status": "active",
"custom_data": {
"key1": "value1",
"key2": "value2"
},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
]
POST /chat/conversations
创建新对话。
注意: 请求体中的所有字段都是可选的。如果未指定,将使用默认值(默认值请参见配置选项部分)。
请求体:
{
"title": "可选的对话标题",
"settings": {
"model": "gpt-4o-mini",
"temperature": 0.7,
"max_tokens": 4096,
"prompt": "系统提示"
},
"reference_settings": {
"memories": {
"collections": ["memory_id_1", "memory_id_2"],
"content_filter": null,
"min_similarity": 0.5,
"limit": 5,
"unmatch_message": null
}
},
"custom_data": {
"key1": "value1",
"key2": "value2"
}
}
GET /chat/conversations/:conversation_id
通过 ID 获取特定对话。
响应:
{
"id": "uuid",
"integration_id": "uuid",
"external_user_id": "string",
"title": "对话标题",
"settings": {
"model": "gpt-4o-mini",
"temperature": 0.7,
"max_tokens": 4096,
"top_p": 0,
"frequency_penalty": 0,
"presence_penalty": 0,
"prompt": null,
"history_messages_count": 10
},
"reference_settings": {
"memories": {
"collections": [],
"content_filter": null,
"min_similarity": 0.5,
"limit": 5,
"unmatch_message": null
}
},
"status": "active",
"custom_data": {
"key1": "value1",
"key2": "value2"
},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
PUT /chat/conversations/:conversation_id
更新对话标题和自定义数据。
请求体:
{
"title": "新的对话标题",
"custom_data": {
"key1": "updated_value1",
"key2": "updated_value2"
}
}
响应:
{
"message": "对话更新成功"
}
DELETE /chat/conversations/:conversation_id
删除对话(软删除)。
响应:
{
"message": "对话删除成功"
}
消息
POST /chat/conversations/:conversation_id/messages
发送消息并获取 AI 响应。
注意:
stream参数默认为true。如果未指定,响应将以流式方式返回。
请求体:
{
"content": "您的消息文本",
"attachments": [
{
"type": "image",
"url": "https://example.com/image.jpg",
"metadata": {}
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市和省份,例如:北京,北京市"
}
},
"required": ["location"]
}
}
}
],
"messages": [
{
"role": "user",
"content": "额外的上下文或之前的消息"
}
],
"custom_data": {
"key1": "value1",
"key2": "value2"
},
"stream": true
}
请求参数:
content(可选)- 您的消息文本attachments(可选)- 附件数组(图片、文件等)tools(可选)- 用于函数调用的工具定义数组messages(可选)- 要包含在对话上下文中的额外消息custom_data(可选) - 自定义数据stream(可选)- 是否流式返回响应(默认:true)
非流式响应:
{
"content": "AI 响应文本",
"reasoning": "AI 生成响应时使用的思维链的描述",
"model": "gpt-4o-mini",
"finish_reason": "stop",
"tool_calls": [
{
"id": "call_123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\":\"北京,北京市\"}"
}
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 15,
"total_tokens": 25
}
}
注意:
tool_calls字段仅在 AI 模型决定调用函数时出现。当进行工具调用时,content字段可能为 null。
流式响应: 服务器发送事件格式:
data: {"type":0,"model":"gpt-4o-mini","content":"","reasoning":"用户跟我打招呼,我应该礼貌回复","finish_reason":null,"usage":null}
data: {"type":0,"model":"gpt-4o-mini","content":"你好","finish_reason":null,"usage":null}
data: {"type":0,"model":"gpt-4o-mini","content":"!","finish_reason":"stop","usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}
data: [DONE]
带工具调用的流式响应:
data: {"type":0,"model":"gpt-4o-mini","content":null,"tool_calls":[{"id":"call_123","type":"function","function":{"name":"get_weather","arguments":"{\"location\""}}],"finish_reason":null,"usage":null}
data: {"type":0,"model":"gpt-4o-mini","content":null,"tool_calls":[{"id":"call_123","type":"function","function":{"name":"get_weather","arguments":"{\"location\":\"北京,北京市\"}"}}],"finish_reason":"tool_calls","usage":{"prompt_tokens":15,"completion_tokens":10,"total_tokens":25}}
data: [DONE]
注意: 在流式模式下进行工具调用时,
tool_calls字段将在多个事件中逐步构建,直到函数参数完整。
GET /chat/conversations/:conversation_id/messages
获取对话中的所有消息。
DELETE /chat/conversations/:conversation_id/messages
删除对话中的所有消息。
DELETE /chat/conversations/:conversation_id/messages/:message_id
删除特定消息。
实用工具
POST /chat/conversations/:conversation_id/generate-title
根据对话消息自动生成对话标题。
响应:
{
"title": "生成的对话标题"
}
文件
POST /files/extract
从上传的文件中提取文本内容。此端点支持多种文件格式,并根据文件扩展名自动检测文件类型。
请求:
请求必须作为 multipart/form-data 发送,文件字段名为 file。
Content-Type: multipart/form-data
表单字段:
file(必填)- 要提取文本的文件。文件必须具有有效的扩展名。
支持的文件类型:
- 文档:
.pdf,.docx,.doc,.txt,.md - 电子表格:
.xlsx,.xls,.csv - 演示文稿:
.pptx - 网页:
.html,.htm - 数据:
.json,.yaml,.yml
请求示例 (cURL):
curl -X POST "https://your-dathor-instance.com/v8/files/extract" \
-H "Authorization: Bearer ek-<your_token>" \
-F "file=@/path/to/document.pdf"
请求示例 (JavaScript):
const formData = new FormData();
formData.append('file', fileInput.files[0]);
const response = await fetch('https://your-dathor-instance.com/v8/files/extract', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
},
body: formData
});
const result = await response.json();
成功响应 (200):
{
"content": "从文件中提取的文本内容...",
"metadata": {
"type": "pdf",
"pageCount": 10,
"language": "zh"
}
}
响应字段:
content(string) - 从文件中提取的文本内容。此内容已针对 UTF-8 存储进行了清理,可安全用于 PostgreSQL 数据库。metadata(object, 可选) - 关于已解析文件的其他元数据。结构因文件类型而异:- PDF:
type,pageCount,language - Excel/CSV:
type,sheetCount,sheetNames,totalRows - Word:
type,paragraphCount,language - JSON:
type,isArray,keys,itemCount,depth - YAML:
type,isArray,keys,itemCount,depth - HTML:
type,title,metaTags,linkCount - 文本/Markdown:
type,lineCount,wordCount
- PDF:
错误响应:
400 Bad Request - 缺少或无效的文件:
{
"error": "File is required"
}
{
"error": "File extension is required"
}
500 Internal Server Error - 解析错误或不支持的文件类型:
{
"error": "Unsupported file type: abc. Supported types are: pdf, csv, docx, doc, txt, md, xlsx, xls, pptx, html, htm, json, yaml, yml"
}
{
"error": "Failed to parse PDF buffer: Invalid PDF format"
}
注意事项:
- 根据文件类型和服务器配置,可能会应用文件大小限制。
- 文件扩展名会自动从文件名检测。没有扩展名的文件将被拒绝。
- 对于大文件,解析可能需要一些时间。建议在客户端应用程序中实现超时处理。
记忆(知识库)
GET /memories
获取认证用户的可用记忆库列表。
响应:
[
{
"id": "uuid",
"name": "我的知识库",
"description": "重要信息的集合",
"embedding_model": "text-embedding-3-small",
"status": "enabled",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
]
POST /memories
创建新的记忆库。需要管理员权限。
请求体:
{
"name": "我的知识库",
"description": "重要信息的集合",
"embedding_model": "text-embedding-3-small",
"max_tokens_per_chunk": 1024,
"overlap_tokens": 0
}
必填字段:
name- 记忆库名称
可选字段:
embedding_model- 使用的嵌入模型 (默认:集成的默认向量模型)description- 记忆库描述(默认:null)max_tokens_per_chunk- 每个分块的最大令牌数(默认:1024)overlap_tokens- 分块之间的重叠令牌数(默认:0)
响应:
{
"id": "uuid",
"name": "我的知识库",
"description": "重要信息的集合",
"embedding_model": "text-embedding-3-small",
"status": "enabled",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
GET /memories/:memory_id
通过 ID 获取记忆库详情。
响应:
{
"id": "uuid",
"name": "我的知识库",
"description": "重要信息的集合",
"embedding_model": "text-embedding-3-small",
"status": "enabled",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
PUT /memories/:memory_id
更新记忆库。需要管理员权限。
请求体:
{
"name": "更新的知识库",
"description": "更新的描述",
"status": "enabled"
}
响应:
{
"id": "uuid",
"name": "更新的知识库",
"description": "更新的描述",
"embedding_model": "text-embedding-3-small",
"status": "enabled",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
DELETE /memories/:memory_id
删除记忆库。需要管理员权限。
响应:
{
"message": "记忆库删除成功"
}
GET /memories/:memory_id/contents
获取记忆库中的内容列表,支持基础过滤功能。
注意: 如需使用
attrs高级过滤功能,请使用 POST/memories/:memory_id/contents-filter端点。
查询参数:
type(可选)- 按内容类型过滤(精确匹配)keywords(可选)- 在内容中搜索的关键字(不区分大小写)
示例:
# 按内容类型过滤
GET /memories/:memory_id/contents?type=text
# 在内容中搜索(不区分大小写)
GET /memories/:memory_id/contents?keywords=机器学习
# 组合内容类型和搜索
GET /memories/:memory_id/contents?type=text&keywords=人工智能
响应:
[
{
"id": "uuid",
"content": "这是一些文本内容",
"content_type": "text",
"key": "unique_key",
"attrs": {
"source": "document.pdf",
"page": 1,
"type": "document",
"priority": 8,
"status": "published"
},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
]
POST /memories/:memory_id/contents-filter
使用高级过滤功能获取记忆库内容列表(推荐方式)。
请求体:
{
"attrs": {
"type": "document",
"priority": { "$gt": 5, "$lt": 10 },
"status": { "$in": ["published", "draft"] },
"title": { "$contains": "重要" }
},
"content_type": "text",
"content_keywords": "机器学习"
}
所有字段都是可选的:
attrs- 使用支持的操作符进行属性过滤的对象content_type- 按内容类型过滤(精确匹配)content_keywords- 在内容中搜索的关键字(不区分大小写)
支持的过滤操作符(适用于 attrs 字段):
-
比较操作符(自动检测数值/字符串类型):
$gt,$gte,$lt,$lte- 大于、大于等于、小于、小于等于$ne- 不等于
-
数组操作符:
$in- 值在数组中$nin- 值不在数组中
-
字符串操作符:
$contains- 字符串包含子字符串(不区分大小写)$startsWith- 字符串以子字符串开头$endsWith- 字符串以子字符串结尾$regex- 正则表达式匹配
-
字段存在性:
$exists- 字段存在(true)或不存在(false)
请求体示例:
简单过滤:
{
"content_type": "text",
"content_keywords": "人工智能"
}
复杂属性过滤:
{
"attrs": {
"priority": { "$gte": 8 },
"status": { "$in": ["published", "featured"] },
"tags": { "$exists": true },
"title": { "$contains": "教程" }
}
}
组合过滤:
{
"attrs": {
"category": "technology",
"rating": { "$gt": 4.0 }
},
"content_type": "markdown",
"content_keywords": "Python编程"
}
响应:
与 GET 端点相同 - 返回匹配的记忆内容数组。
[
{
"id": "uuid",
"content": "这是一些文本内容",
"content_type": "text",
"key": "unique_key",
"attrs": {
"source": "document.pdf",
"page": 1,
"type": "document",
"priority": 8,
"status": "published"
},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
]
GET /memories/:memory_id/contents/:content_id
获取记忆库中的特定内容。
响应:
{
"id": "uuid",
"content": "这是一些文本内容",
"content_type": "text",
"key": "unique_key",
"attrs": {
"source": "document.pdf",
"page": 1
},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
GET /memories/:memory_id/contents/:content_id/chunks
获取记忆库中特定内容的所有分块。需要管理员权限。
此端点允许您查看内容如何被拆分为分块以进行嵌入处理。
响应:
[
{
"id": "uuid",
"content_id": "uuid",
"chunk_index": 0,
"content": "这是内容的第一个分块",
"token_count": 25,
"embedding_status": "completed",
"created_at": "2024-01-01T00:00:00Z"
},
{
"id": "uuid",
"content_id": "uuid",
"chunk_index": 1,
"content": "这是内容的第二个分块",
"token_count": 30,
"embedding_status": "completed",
"created_at": "2024-01-01T00:00:00Z"
}
]
POST /memories/:memory_id/contents
在记忆库中创建内容。需要管理员权限。
如果提供了 key 并且已存在该键的内容,则会更新现有内容而不是创建新内容。
请求体:
{
"content": "这是一些文本内容",
"content_type": "text",
"key": "unique_key",
"attrs": {
"source": "document.pdf",
"page": 1
}
}
必填字段:
content- 内容文本
可选字段:
content_type- 内容类型(默认:"text")key- 内容的唯一键(默认:null)attrs- 额外属性(默认:null)
响应:
{
"success": true,
"message": "content created",
"content_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
注意: 如果提供了 key 并且已存在该键的内容,则会更新现有内容,响应为:
{
"success": true,
"message": "content updated",
"content_id":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
PUT /memories/:memory_id/contents/:content_id
更新记忆库中的内容。需要管理员权限。
请求体:
{
"content": "更新的文本内容",
"content_type": "text",
"key": "unique_key",
"attrs": {
"source": "document.pdf",
"page": 1
}
}
必填字段:
content- 内容文本
可选字段:
content_type- 内容类型(默认:"text")key- 内容的唯一键(默认:null)attrs- 额外属性(默认:null)
响应:
{
"success": true,
"message": "content updated"
}
DELETE /memories/:memory_id/contents/:content_id
删除记忆库中的内容。需要管理员权限。
如果
:content_id以_开头,则其后内容视为 key,而非内容 ID。
响应:
{
"success": true,
"message": "content deleted"
}
POST /memories/:memory_id/embeddings-search-chunks
使用嵌入相似度搜索分块。
请求体:
{
"query": "机器学习",
"min_similarity": 0.8,
"limit": 5,
"content_filter": {
"content_type": "text",
"content_keywords": "人工智能",
"attrs": {
"type": "document",
"priority": { "$gt": 5, "$lt": 10 },
"status": { "$in": ["published", "draft"] },
"title": { "$contains": "重要" }
}
}
}
必填字段:
query- 搜索查询文本
可选字段:
min_similarity- 最小相似度阈值(默认:0.7)limit- 最大结果数量(默认:10)content_filter- 内容过滤条件content_type- 按内容类型过滤(精确匹配)content_keywords- 在内容中搜索的关键字(不区分大小写)attrs- 使用与/contents-filter相同操作符的高级属性过滤
响应:
[
{
"id": "uuid",
"content_id": "uuid",
"content_type": "text",
"content_key":"key_of_content",
"content_attrs": {"key":"value"},
"chunk_index": 0,
"content": "这个分块包含关于机器学习的信息",
"token_count": 25,
"similarity": 0.85,
"created_at": "2024-01-01T00:00:00Z"
}
]
POST /memories/:memory_id/embeddings-search-contents
使用嵌入相似度搜索内容。
请求体:
{
"query": "机器学习",
"min_similarity": 0.8,
"limit": 5,
"content_filter": {
"content_type": "text",
"content_keywords": "人工智能",
"attrs": {
"type": "document",
"priority": { "$gt": 5, "$lt": 10 },
"status": { "$in": ["published", "draft"] },
"title": { "$contains": "重要" }
}
}
}
必填字段:
query- 搜索查询文本
可选字段:
min_similarity- 最小相似度阈值(默认:0.7)limit- 最大结果数量(默认:10)content_filter- 内容过滤条件content_type- 按内容类型过滤(精确匹配)content_keywords- 在内容中搜索的关键字(不区分大小写)attrs- 使用与/contents-filter相同操作符的高级属性过滤
响应:
[
{
"id": "uuid",
"content": "这是关于机器学习和人工智能的内容",
"content_type": "text",
"key": "ml_article_1",
"attrs": {
"source": "ml_guide.pdf",
"page": 1
},
"similarity": 0.85,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
]
集成示例
基础聊天集成
class DathorClient {
constructor(baseUrl, token) {
this.baseUrl = baseUrl;
this.token = token;
}
async createConversation(title = null, settings = {}) {
const response = await fetch(`${this.baseUrl}/v8/chat/conversations`, {
method: "POST",
headers: {
"Authorization": `Bearer ${this.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ title, settings }),
});
return response.json();
}
async sendMessage(conversationId, content, stream = true, tools = null) {
const response = await fetch(`${this.baseUrl}/v8/chat/conversations/${conversationId}/messages`, {
method: "POST",
headers: {
"Authorization": `Bearer ${this.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ content, stream, tools }),
});
if (stream) {
return this.handleStream(response);
}
return response.json();
}
async handleStream(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") return;
const parsed = JSON.parse(data);
if (parsed.content) {
console.log(parsed.content); // 处理流式内容
}
}
}
}
}
}
// 使用方法
const client = new DathorClient("https://your-dathor-instance.com", yourToken);
const conversation = await client.createConversation("我的聊天");
await client.sendMessage(conversation.id, "你好,你能帮我做什么?");
工具调用示例
// 定义用于函数调用的工具
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "获取指定位置的当前天气",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "城市和省份,例如:北京,北京市"
}
},
required: ["location"]
}
}
},
{
type: "function",
function: {
name: "calculate",
description: "执行数学计算",
parameters: {
type: "object",
properties: {
expression: {
type: "string",
description: "要计算的数学表达式"
}
},
required: ["expression"]
}
}
}
];
// 使用工具的方法
const client = new DathorClient("https://your-dathor-instance.com", yourToken);
const conversation = await client.createConversation("工具聊天");
const response = await client.sendMessage(
conversation.id,
"北京的天气怎么样?",
false, // 非流式模式便于处理工具调用
tools
);
// 处理工具调用
if (response.tool_calls) {
for (const toolCall of response.tool_calls) {
if (toolCall.function.name === "get_weather") {
const args = JSON.parse(toolCall.function.arguments);
// 在这里实现您的天气 API 调用
console.log(`正在获取 ${args.location} 的天气信息`);
}
}
}
React Hook 示例
import { useEffect, useState } from "react";
export function useDathorChat(token, baseUrl) {
const [conversations, setConversations] = useState([]);
const [loading, setLoading] = useState(false);
const client = new DathorClient(baseUrl, token);
const loadConversations = async () => {
setLoading(true);
try {
const response = await fetch(`${baseUrl}/v8/chat/conversations`, {
headers: { "Authorization": `Bearer ${token}` },
});
const data = await response.json();
setConversations(data);
} catch (error) {
console.error("加载对话失败:", error);
} finally {
setLoading(false);
}
};
const sendMessage = async (conversationId, content, tools = null) => {
return client.sendMessage(conversationId, content, true, tools);
};
useEffect(() => {
loadConversations();
}, []);
return {
conversations,
loading,
loadConversations,
sendMessage,
createConversation: client.createConversation.bind(client),
};
}
配置选项
对话设置(settings)
默认值: 创建对话或发送消息时,如果未指定参数,将应用以下默认值:
model: 使用的 AI 模型(默认:"gpt-4o-mini")temperature: 响应随机性 0.0-2.0(默认:0.7)max_tokens: 最大响应长度(默认:4096)top_p: 核采样参数(默认:0)frequency_penalty: 频率惩罚 -2.0 到 2.0(默认:0)presence_penalty: 存在惩罚 -2.0 到 2.0(默认:0)prompt: 系统提示(默认:null)history_messages_count: 上下文中包含的消息数量(默认:10)stream: 启用流式响应(默认:true)
引用设置(reference_settings)
memories.collections: 要使用的记忆/知识库 ID 数组memories.content_filter: 对记忆/知识库内容数据进行预选过滤的条件设置memories.min_similarity: 最小相似度阈值(默认:0.5)memories.limit: 最大记忆/知识库内容匹配数量(默认:5)memories.unmatch_message: 未能匹配记忆/知识库内容时的消息
错误处理
API 返回标准 HTTP 状态码:
200: 成功400: 错误请求(无效参数、缺少必需字段)401: 未授权(无效或过期令牌,缺少认证头)403: 禁止访问(对于仅限管理员的操作权限不足)404: 未找到(对话或消息未找到)500: 内部服务器错误
错误响应包含带有 error 字段的 JSON 对象:
{
"error": "错误消息描述"
}
认证错误响应
缺少认证头:
{
"error": {
"message": "Missing bearer authentication in header",
"type": "invalid_request_error",
"param": null,
"code": null
}
}
无效令牌:
{
"error": {
"message": "Invalid token",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}
权限不足:
{
"error": "unauthorized"
}
最佳实践和建议
- 令牌管理: 令牌有过期时间。实施令牌刷新逻辑。
- 流式传输: 使用流式传输获得实时聊天体验。
- 上下文管理: 限制 history_messages_count 以控制成本和延迟。
- 错误处理: 对网络错误实施适当的重试逻辑。
- 记忆使用: 使用知识库集成获得上下文感知响应。
记忆状态值
记忆库状态
enabled- 记忆库处于活动状态,可供使用disabled- 记忆库处于非活动状态
记忆内容状态
enabled- 内容处于活动状态,可供搜索disabled- 内容处于非活动状态
记忆内容嵌入状态
error- 嵌入处理失败pending- 嵌入正在等待处理processing- 嵌入正在处理中completed- 嵌入已成功处理
记忆内容类型
text- 纯文本内容markdown- Markdown 格式内容