API 集成提供了一个 OpenAI 兼容的聊天完成端点,您可以用它来与您的 Pathors 项目进行交互。
聊天完成
路径参数
请求头
使用您的 API 密钥进行 Bearer 令牌认证
会话 ID,用于对话连续性。强烈建议使用此标头传递会话 ID,而不是请求体中的
session_id 参数。
请求体
对话中的消息数组。每条消息都应该有一个 role
(“system”、“user” 或
“assistant”)和 content
。
(deprecated) 会话 ID,用于对话连续性。建议使用 X-Session-ID
标头代替。仅在不支持自定义标头的环境中使用此参数。
可供助手使用的外部工具定义数组。每个工具应该有一个 type
(目前仅支持 “function”)和一个包含 name
、description
和 parameters
(JSON Schema 格式)的 function
对象。
请求示例:
{
"messages": [
{
"role": "user",
"content": "你好!"
}
],
"stream": false
}
带工具的请求示例:
{
"messages": [
{
"role": "user",
"content": "旧金山的天气怎么样?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取当前天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称"
}
},
"required": ["location"]
}
}
}
]
}
响应头
对话的会话 ID。此头部会在响应中返回,可用于后续请求。
choices[].message.tool_calls
助手进行的工具调用数组(当提供并使用工具时)
完成终止的原因。正常完成时为 “stop”,调用工具时为 “tool_calls”。
响应示例:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677858242,
"model": "pathway-default",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "你好!我能帮你什么忙?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": -1,
"completion_tokens": -1,
"total_tokens": -1
},
"session_id": "session-xyz789"
}
带工具调用的响应示例:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677858242,
"model": "pathway-default",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"旧金山\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": -1,
"completion_tokens": -1,
"total_tokens": -1
},
"session_id": "session-xyz789"
}
流式响应
当 stream
设置为 true
时,响应将以服务器发送事件(SSE)的形式流式传输。每个事件包含以下格式的响应块:
{
"id": "chatcmpl-abc123",
"object": "chat.completion.chunk",
"created": 1677858242,
"model": "pathway-default",
"choices": [
{
"index": 0,
"delta": {
"content": "你好"
},
"finish_reason": null
}
],
"session_id": "session-xyz789"
}
最后一个块将有 finish_reason: "stop"
,并跟随 data: [DONE]
。
错误响应
状态码 | 描述 |
---|
400 | 无效的请求体 |
401 | 无效的认证 |
500 | 内部服务器错误 |
使用工具
当您在请求中提供工具时,助手可以在对话中调用它们。在收到带有 tool_calls
的响应后,您应该:
- 使用提供的参数执行请求的工具
- 在后续请求中以 “tool” 角色消息发送工具结果
- 助手然后将使用工具结果来制定其最终响应
工具消息格式
收到工具调用后,发送结果:
{
"messages": [
{"role": "user", "content": "天气怎么样?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"旧金山\"}"
}
}
]
},
{
"role": "tool",
"content": "22°C,晴朗",
"tool_call_id": "call_123",
"name": "get_weather"
}
],
"session_id": "existing_session_id"
}
设置指南
- 在您的 Pathors 项目设置中启用 API 集成
- 在您项目的集成设置中生成 API 密钥
- 在您的请求中使用 API 密钥作为 Authorization 头部
- (可选)使用会话 API创建会话以保持对话连续性
- (可选)定义并提供工具以扩展功能