Python SDK(官方)

apemind-sdk 基于 ApeMind 公开 OpenAPI 规范自动生成强类型 Pydantic v2 模型与同步 / 异步 httpx 客户端,开箱覆盖知识库管理、文档上传与索引等待、多路混合检索以及 Agent 对话。完整接口字典见 API 参考。

安装与环境要求

# 方式一:通过 PyPI 安装(推荐)
pip install apemind-sdk

# 方式二:安装 GitHub Release 离线 Wheel 包(内网 / 私有化环境推荐)
pip install ./apemind_sdk-<version>-py3-none-any.whl

# 方式三:从源码仓库目录安装
pip install ./sdk/python

认证与客户端初始化

SDK 默认使用 OpenAPI 中定义的 BearerAuth 方案(Authorization: Bearer <API_KEY>),并支持为 OAuth / 组织级接口自动附加 X-ApeMind-Workspace-Id 请求头。凭据选型详见认证、API Key 与工作区上下文。

客户端会自动读取以下环境变量,也可在构造 ApeMindClient / AsyncApeMindClient 时显式覆盖:

环境变量 构造参数 说明
APEMIND_BASE_URL base_url 服务根地址,默认 https://apemind.ai;私有化部署替换为 https://<APEMIND_HOST>
APEMIND_API_KEY api_key 组织服务账号 API Key、成员 API Key、Agent API Key 或 OAuth Access Token
APEMIND_WORKSPACE_ID workspace_id 默认目标组织(工作空间)ID,供声明式建库、Agent 管理与跨库检索复用
同步与异步双客户端

常规脚本与同步服务使用 with ApeMindClient(...) as client:;在 FastAPI、aiohttp 或异步 Agent 编排框架中直接切换为 async with AsyncApeMindClient(...) as client:,资源命名空间与方法名保持一致。

核心能力与代码示例

资源命名空间 覆盖能力 常用方法
client.knowledge_bases 声明式建库/更新、知识库列表与详情、索引汇总、失败重建、删除 create()、list()、get()、patch_config()、get_indexing_status()、rebuild_failed_indexes()
client.documents 单步上传、两步暂存+确认、URL 导入、目录列表、内容读写、原文件下载、索引轮询 upload()、confirm()、create()、list()、download()、wait_until_indexed()
client.search 单知识库三路混合检索、工作区跨库检索、原文 grep / read collection()、workspace()、list_history()、grep()、read()
client.agents 声明式创建、查询、局部修改与删除 Agent create()、list()、get()、patch()、delete()
client.chats 会话管理、原生异步 Turn 问答与引用证据、OpenAI 兼容同步/流式对话 create()、ask()、create_turn()、wait_for_turn()、get_turn_evidence()、stream_chat_completions()
client.api 直接调用全部由 OpenAPI 自动生成的底层强类型方法 所有 65 个已生成 OpenAPI Operation 方法及 apemind.models

1. 创建知识库、上传文档并等待索引完成

from apemind import ApeMindClient

with ApeMindClient(
    base_url="https://apemind.ai",
    api_key="sk-...",
    workspace_id="org_...",
) as client:
    # 声明式创建知识库
    kb = client.knowledge_bases.create(
        title="企业制度知识库",
        description="HR 与合规流程文档",
        spec={"enable_vector": True, "enable_fulltext": True, "enable_knowledge_graph": True},
    )
    kb_id = kb.metadata.id

    # 两步上传确认(推荐大批量导入)
    uploaded = client.documents.upload(kb_id, "./handbook.pdf", path="制度/handbook.pdf")
    client.documents.confirm(kb_id, [uploaded.document_id])

    # 轮询直到解析与索引进入终态
    doc = client.documents.wait_until_indexed(kb_id, uploaded.document_id, timeout=300.0)
    print(doc.id, doc.status, doc.vector_index_status, doc.fulltext_index_status)

2. 知识库混合检索与跨库检索

from apemind import ApeMindClient

with ApeMindClient() as client:
    # 单知识库三路混合检索(向量 + 全文 + 图谱)
    res = client.search.collection(
        collection_id="kb_...",
        query="合同解除的条件有哪些?",
        vector_topk=5,
        fulltext_topk=5,
        graph_topk=5,
    )
    for item in res.items or []:
        print(f"[{item.rank}] score={item.score:.3f} source={item.source}: {item.content[:80]}")

    # 工作区跨知识库检索
    ws_page = client.search.workspace("合同解除条件", knowledge_base_ids=["kb_..."], limit=5)

3. Agent 原生异步 Turn 对话与句级引用证据

from apemind import ApeMindClient, extract_turn_text

with ApeMindClient() as client:
    chat = client.chats.create(agent_id="agent_...")

    # ask() 自动生成 client_idempotency_key、提交 Turn 并轮询直到终态
    turn = client.chats.ask(chat.id, "请总结退换货政策并注明条款出处。", language="zh-CN")
    print(extract_turn_text(turn))

    # 读取结构化句级引用证据
    evidence = client.chats.get_turn_evidence(chat.id, turn.turn_id)
    print("引用句数:", len(evidence.sentences or []))

4. OpenAI 兼容流式对话与异步客户端

import asyncio
from apemind import AsyncApeMindClient

async def main() -> None:
    async with AsyncApeMindClient() as client:
        async for chunk in client.chats.stream_chat_completions(
            agent_id="agent_...",
            messages=[{"role": "user", "content": "请简述 ApeMind 的三路混合检索。"}],
        ):
            choices = chunk.get("choices") or []
            if choices and (text := (choices[0].get("delta") or {}).get("content")):
                print(text, end="", flush=True)

asyncio.run(main())

错误处理与重试

所有非 2xx 响应会映射为结构化异常并附带 status_code、error_code 与服务端 request_id,方便在日志中直接关联排障:

from apemind import ApeMindClient, APIError, AuthenticationError, RateLimitError

with ApeMindClient() as client:
    try:
        user = client.me()
    except AuthenticationError as exc:
        print(f"凭据无效: {exc.message} (request_id={exc.request_id})")
    except RateLimitError as exc:
        print(f"触发限流: code={exc.error_code}, request_id={exc.request_id}")
    except APIError as exc:
        print(f"接口异常 HTTP {exc.status_code}: {exc.message}")

直接调用底层自动生成接口

如果高层资源方法未暴露某个精细参数,可通过 client.api 直接调用全部 65 个从 OpenAPI 自动生成的强类型方法,或从 apemind.models 导入对应 Pydantic v2 模型:

from apemind import ApeMindClient, models

with ApeMindClient() as client:
    req = models.SearchRequest(
        query="合同解除条件",
        vector_search=models.VectorSearchParams(topk=5, similarity=0.6),
        fulltext_search=models.FulltextSearchParams(topk=5),
    )
    result = client.api.retrieval_create_search_view("kb_...", body=req)

OpenAPI 自动生成与版本同步

SDK 的数据模型(apemind._generated.models)与底层接口绑定(apemind._generated.api)均由仓库的 sdk/python/scripts/generate_sdk.py 从公开 OpenAPI 规范(docs/openapi/openapi.json,包含 components.securitySchemes)确定性生成,并在 CI 中执行零漂移门禁。完整可运行脚本见仓库 sdk/python/examples/。

下一步