开发文档 · SDK 示例

SDK 示例

Python、Java、JavaScript 全流程示例与 SDK 生成。

完整调用示例

以下示例覆盖「上传 → 提交 → 轮询 → 取结果」全流程,可直接用于项目集成。各语言要点相同:统一携带 X-Aistrong-Key,先判断 success,异步任务按 poll_after_ms 轮询。

import time
import requests


class DocuClient:
    def __init__(self, base_url: str, api_key: str, timeout: int = 60):
        self.base = base_url.rstrip("/") + "/open/v1"
        self.session = requests.Session()
        self.session.headers["X-Aistrong-Key"] = api_key
        self.timeout = timeout

    def _unwrap(self, response: requests.Response) -> dict:
        payload = response.json()
        if not payload.get("success"):
            error = payload.get("error") or {}
            raise RuntimeError(f"{response.status_code} {error.get('code')}: {error.get('message')}")
        return payload["data"]

    def upload(self, path: str, client_request_id: str) -> int:
        with open(path, "rb") as fh:
            response = self.session.post(f"{self.base}/documents", files={"file": fh},
                                         data={"client_request_id": client_request_id}, timeout=self.timeout)
        return self._unwrap(response)["doc_id"]

    def submit(self, action: str, body: dict) -> str:
        response = self.session.post(f"{self.base}/{action}", json=body, timeout=self.timeout)
        return self._unwrap(response)["job_id"]

    def wait(self, job_id: str, max_seconds: int = 600) -> dict:
        deadline = time.monotonic() + max_seconds
        while time.monotonic() < deadline:
            job = self._unwrap(self.session.get(f"{self.base}/job/{job_id}", timeout=self.timeout))
            if job["status"] == "succeeded":
                return self._unwrap(self.session.get(f"{self.base}/job/{job_id}/result", timeout=self.timeout))
            if job["status"] in ("failed", "cancelled"):
                raise RuntimeError(job["error"])
            time.sleep(job["poll_after_ms"] / 1000)
        raise TimeoutError(job_id)


client = DocuClient("https://<host>", "<API Key>")
doc_a = client.upload("a.pdf", "upload-a")
doc_b = client.upload("b.pdf", "upload-b")
job_id = client.submit("documents:merge", {"doc_ids": [doc_a, doc_b], "client_request_id": "merge-0001"})
print(client.wait(job_id))

生成 SDK

OpenAPI 3 文档可直接导入 Postman / Apifox,或用 openapi-generator 生成任意语言的客户端:

curl -o docu-open-v1.json 'https://<host>/v3/api-docs/open-v1'
openapi-generator-cli generate -i docu-open-v1.json -g python -o ./docu-sdk