跳转至

对话 API

客户端通过经过身份验证的 Next.js 网关提问:

POST /api/chat/completions

使用会话 Cookie 或 API token 进行身份验证(参见 authentication.md)。请求和响应模式位于 openapi/auto-ontology-api.json 中。

响应流

响应是一个服务器发送事件流。每个事件的 data: 行包含一个 JSON 对象,流以 data: [DONE] 结束,这是最后一行非 JSON 内容。

type 所携带内容
step 代理步骤的开始或结束(结束时包含 node、phase 和 thought),用于显示进度。
sql 一条已通过验证并即将运行的查询。
result 最终 answer:response(自然语言文本)、sql_code、sql_response_from_db(行)、thoughts(步骤追踪)。
charts 结果对应的图表或表格(content、sql_response)。当查询已运行且请求包含 conversation_id 时,在 result 之后发送。
error 描述运行失败原因的 message。

一次运行会进行多次顺序模型调用,通常需要数十秒,因此请随着流的到达进行读取:

import json
import os

import requests

response = requests.post(
    "https://auto-ontology.example.com/api/chat/completions",
    headers={"x-api-key": os.environ["AUTO_ONTOLOGY_API_TOKEN"]},
    json={"question": "How many orders shipped last week?"},
    stream=True,
    timeout=900,
)
response.raise_for_status()

for line in response.iter_lines(decode_unicode=True):
    if not line or not line.startswith("data:"):
        continue
    payload = line.removeprefix("data:").strip()
    if payload == "[DONE]":
        break
    event = json.loads(payload)
    if event["type"] == "step":
        print("…", event.get("node"), event.get("phase"))
    elif event["type"] == "result":
        answer = event["answer"]
        print(answer["response"])
        print(answer["sql_code"])
    elif event["type"] == "error":
        raise RuntimeError(event["message"])

MCP 服务器的 ask_question 工具封装了同样的调用,并将答案、SQL 和行作为单独字段返回;参见 mcp.md。

对话

conversation_id 是可选的:

  • 省略它以进行无状态的一次性请求。
  • 发送客户端生成的 UUID 来开始或继续对话,并在该线程的每一轮中复用此 UUID。
  • 在发送下一轮之前等待 [DONE]。对同一对话的并发请求会返回 409 Conversation in progress。
{
  "question": "What about last month?",
  "conversation_id": "d61d8aa3-d496-4fa7-97ce-4f831c162e7f"
}

对于对话轮次,后端会加载最近最多五个已完成轮次(上限为 12,000 个字符),并在运行 text-to-SQL 代理之前,将诸如 "What about August?" 这样的上下文追问改写为独立的问题。独立问题会原样通过。只有之前的问题、答案和 SQL 会用于这次改写;代理思考、图表负载、错误和原始结果行都不会包含在内。

对话历史属于已认证用户。通过 API 创建的对话会在 UI 中为拥有它的用户打开,地址为 /chat?focus=<conversation_id>。Web UI 管理自己的对话 ID。

信任边界

调用 Next.js 网关(APP_URL,在 Docker Compose 中为端口 3000)。它会解析用户身份,并将内部的 x-auto-ontology-user-id 请求头转发给 FastAPI(端口 3001)。FastAPI 信任该请求头而不进行验证,因此请将端口 3001 保留在私有网络中。不包含 conversation_id 的直接 FastAPI 请求保持无状态;包含 conversation_id 的请求则需要受信任的身份请求头。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 au/auto-ontology