> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aibase.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python 调用

> 使用 requests 完成可运行的 AIBase API 调用，并校验 HTTP 状态、业务 code 和 requestId。

下面的示例调用当前已上线的“AI 对话问题挖掘”服务。示例从环境变量读取 API Key，并同时处理网络错误、HTTP 错误和业务错误。

## 运行要求

* Python 3.9 或更高版本
* `requests` 依赖
* 已创建并保存 AIBase API Key

```bash theme={null}
python -m pip install requests
```

## 设置 API Key

<Tabs>
  <Tab title="PowerShell">
    ```powershell theme={null}
    $env:AIBASE_API_KEY = "AIBase_xxxxxxxxxxxxxxxx"
    ```
  </Tab>

  <Tab title="macOS / Linux">
    ```bash theme={null}
    export AIBASE_API_KEY="AIBase_xxxxxxxxxxxxxxxx"
    ```
  </Tab>
</Tabs>

环境变量只对当前终端会话生效。生产环境应从密钥管理服务读取凭证。

## 完整示例

将以下内容保存为 `aibase_example.py`：

```python theme={null}
import os
import uuid

import requests


API_URL = "https://api.aibase.cn/v1/openapi/tasks"


def discover_questions(keyword: str) -> dict:
    api_key = os.environ.get("AIBASE_API_KEY")
    if not api_key:
        raise RuntimeError("请先设置 AIBASE_API_KEY 环境变量")

    try:
        response = requests.post(
            API_URL,
            headers={
                "AIBase-API-Key": api_key,
                "AIBase-Request-Id": str(uuid.uuid4()),
                "Content-Type": "application/json",
            },
            json={
                "apiCode": "geo.questions_corr_recommend",
                "data": {"keyword": keyword},
            },
            timeout=30,
        )
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(f"AIBase HTTP 请求失败: {exc}") from exc

    try:
        payload = response.json()
    except requests.JSONDecodeError as exc:
        raise RuntimeError("AIBase 返回了非 JSON 响应") from exc

    if payload.get("code") != 200:
        raise RuntimeError(
            f"AIBase 业务错误 {payload.get('code')}: {payload.get('msg')}"
        )

    data = payload.get("data") or {}
    request_id = data.get("requestId")
    print("requestId:", request_id)
    return data.get("result") or {}


if __name__ == "__main__":
    result = discover_questions("多智能体系统")
    print("AI 相关问题:", result.get("aiQuestions", []))
    print("百度相关问题:", result.get("baiduQuestions", []))
```

```bash theme={null}
python aibase_example.py
```

<Note>
  示例中的 30 秒是客户端超时设置示例，不代表平台承诺的响应时限。请结合自身业务调整，并处理超时异常。
</Note>

## 成功检查

程序正常完成时会输出 `requestId` 和两组问题数组。数组可能为空；`hotValue = 0` 也不表示调用失败。

<Columns cols={2}>
  <Card title="查看字段定义" icon="braces" href="/api-reference/question-discovery">
    核对请求和响应对象的完整结构。
  </Card>

  <Card title="调用失败" icon="list-checks" href="/platform/troubleshooting">
    按联调清单定位认证、权限和参数问题。
  </Card>
</Columns>
