Back to Blog
AI Technology

AI检测API怎么接?手把手教你,开发者必看

AI检测API怎么接入?完整开发教程,包含Python/Node.js示例代码,企业必备

Unfox AI

Unfox AI

Content Team

10 min read
AI检测ai detection api文本检测接口

上周朋友的公司接了一个需求:每天要检测上万条用户生成内容(UGC),靠人工根本忙不过来。

他们问我:"能不能用程序自动检测?"

我说能,API接入就行。

结果他一脸懵:"API是什么?怎么接?"

好吧,这篇文章就是给不懂API的开发者写的。手把手,从零开始,教你把AI检测能力集成到自己的系统里。


一、API是什么?(小白入门)

1.1 通俗解释

API = 告诉别人"我想干什么,别人帮你干"

举个例子:

你去餐厅吃饭,菜单就是API。你告诉服务员(API):"我要一份宫保鸡丁"。后厨(服务端)做好了,服务员端上来(返回结果)。

你不需要知道宫保鸡丁怎么做,只需要告诉服务员你要什么。

AI检测API就是这个道理:你把文本发给UnFox AI,它帮你检测,返回结果。

1.2 为什么要用API?

场景 不用API 用API
检测1篇文章 手动复制粘贴 API调用
检测100篇文章 手动复制100次 API循环调用
检测10000条 不可能手动完成 API批量处理

API的价值:让机器代替人工,提升效率。

1.3 REST API基本概念

AI检测API通常是RESTful风格,基于HTTP协议。

概念 说明
URL 接口地址,如 https://api.unfox.cn/detect
Method 请求方法,常用 GET/POST
Headers 请求头,如认证信息
Body 请求体,要发送的数据
Response 响应结果,JSON格式

二、准备工作

2.1 获取API Key

使用UnFox AI API之前,需要获取API Key。

  1. 注册UnFox AI账号
  2. 进入开发者中心
  3. 创建应用,获取API Key

注意:API Key要保密,泄露了别人可以用你的额度。

2.2 开发环境要求

语言 版本要求 依赖库
Python 3.7+ requests
Node.js 14+ axios
Java 8+ HttpClient
Go 1.16+ net/http
PHP 7.4+ cURL

2.3 API基础信息

项目 内容
API地址 https://api.unfox.cn/v1/detect
请求方式 POST
返回格式 JSON
认证方式 Bearer Token
限流 根据套餐

三、Python接入教程

3.1 安装依赖

pip install requests

3.2 基础调用

import requests

def detect_ai_text(text: str, api_key: str):
    """
    调用UnFox AI API检测文本

    Args:
        text: 要检测的文本
        api_key: API密钥

    Returns:
        dict: 检测结果
    """
    url = "https://api.unfox.cn/v1/detect"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    payload = {
        "text": text,
        "lang": "zh"  # 中文
    }

    response = requests.post(url, headers=headers, json=payload)

    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"API调用失败: {response.status_code}")

# 使用示例
api_key = "your_api_key_here"
result = detect_ai_text("这是一段要检测的文本内容。", api_key)
print(result)

3.3 返回结果解析

{
    "code": 200,
    "message": "success",
    "data": {
        "ai_rate": 0.968,           # AI率,0-1之间
        "is_ai": true,              # 是否判定为AI
        "confidence": 0.968,        # 置信度
        "model_scores": {           # 各模型得分
            "chatgpt": 0.982,
            "claude": 0.956,
            "ernie": 0.988
        }
    }
}

3.4 批量检测

import time

def batch_detect(texts: list, api_key: str, delay: float = 0.1):
    """
    批量检测文本

    Args:
        texts: 文本列表
        api_key: API密钥
        delay: 每次请求间隔(秒),防止限流

    Returns:
        list: 检测结果列表
    """
    results = []

    for text in texts:
        try:
            result = detect_ai_text(text, api_key)
            results.append(result)

            # 防止触发限流
            if delay > 0:
                time.sleep(delay)

        except Exception as e:
            print(f"检测失败: {e}")
            results.append({"error": str(e)})

    return results

# 使用示例
texts = [
    "第一段文本内容",
    "第二段文本内容",
    "第三段文本内容"
]
results = batch_detect(texts, api_key)

3.5 完整示例

import requests
import json
from typing import List, Dict

class UnFoxAIClient:
    """UnFox AI API客户端"""

    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.unfox.cn/v1"

    def detect(self, text: str) -> Dict:
        """检测单条文本"""
        url = f"{self.base_url}/detect"

        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        payload = {
            "text": text[:10000]  # 限制长度
        }

        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()

        return response.json()

    def batch_detect(self, texts: List[str]) -> List[Dict]:
        """批量检测"""
        return [self.detect(text) for text in texts]

    def get_usage(self) -> Dict:
        """获取API使用量"""
        url = f"{self.base_url}/usage"

        headers = {
            "Authorization": f"Bearer {self.api_key}"
        }

        response = requests.get(url, headers=headers)
        response.raise_for_status()

        return response.json()

# 使用示例
if __name__ == "__main__":
    client = UnFoxAIClient("your_api_key_here")

    # 检测单条
    result = client.detect("要检测的文本内容")
    print(f"AI率: {result['data']['ai_rate']:.2%}")

    # 批量检测
    texts = ["文本1", "文本2", "文本3"]
    results = client.batch_detect(texts)

    # 获取使用量
    usage = client.get_usage()
    print(f"今日已用: {usage['data']['used']}")
    print(f"额度上限: {usage['data']['limit']}")

四、Node.js接入教程

4.1 安装依赖

npm install axios

4.2 基础调用

const axios = require('axios');

async function detectAIText(text, apiKey) {
    const url = 'https://api.unfox.cn/v1/detect';

    try {
        const response = await axios.post(url, {
            text: text,
            lang: 'zh'
        }, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        return response.data;
    } catch (error) {
        console.error('API调用失败:', error.message);
        throw error;
    }
}

// 使用示例
const apiKey = 'your_api_key_here';
const result = await detectAIText('要检测的文本内容', apiKey);
console.log(`AI率: ${(result.data.ai_rate * 100).toFixed(2)}%`);

4.3 批量检测

async function batchDetect(texts, apiKey, delay = 100) {
    const results = [];

    for (const text of texts) {
        try {
            const result = await detectAIText(text, apiKey);
            results.push(result);

            // 防止限流
            if (delay > 0) {
                await new Promise(resolve => setTimeout(resolve, delay));
            }
        } catch (error) {
            results.push({ error: error.message });
        }
    }

    return results;
}

4.4 Express集成示例

const express = require('express');
const axios = require('axios');

const app = express();
app.use(express.json());

const API_KEY = 'your_api_key_here';

app.post('/api/detect', async (req, res) => {
    const { text } = req.body;

    if (!text) {
        return res.status(400).json({ error: '文本不能为空' });
    }

    try {
        const result = await axios.post('https://api.unfox.cn/v1/detect', {
            text: text,
            lang: 'zh'
        }, {
            headers: {
                'Authorization': `Bearer ${API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        res.json(result.data);
    } catch (error) {
        res.status(500).json({ error: '检测失败' });
    }
});

app.listen(3000, () => {
    console.log('服务已启动: http://localhost:3000');
});

五、错误处理与最佳实践

5.1 错误码说明

错误码 说明 处理方式
200 成功 正常处理
400 参数错误 检查请求参数
401 认证失败 检查API Key
429 请求过于频繁 增加请求间隔
500 服务器错误 重试或联系客服
503 服务不可用 稍后重试

5.2 重试机制

import time
from requests.exceptions import RequestException

def detect_with_retry(text, api_key, max_retries=3):
    """带重试机制的检测"""

    for attempt in range(max_retries):
        try:
            result = detect_ai_text(text, api_key)
            return result

        except RequestException as e:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # 指数退避
                print(f"请求失败,{wait_time}秒后重试...")
                time.sleep(wait_time)
            else:
                raise Exception(f"重试{max_retries}次后仍失败: {e}")

5.3 限流处理

from collections import deque
import time

class RateLimiter:
    """简单的限流器"""

    def __init__(self, max_requests: int, window_seconds: int):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.requests = deque()

    def wait_if_needed(self):
        """如果超限则等待"""
        now = time.time()

        # 清理过期的请求记录
        while self.requests and self.requests[0] < now - self.window_seconds:
            self.requests.popleft()

        # 如果已达上限,等待
        if len(self.requests) >= self.max_requests:
            sleep_time = self.requests[0] + self.window_seconds - now
            if sleep_time > 0:
                time.sleep(sleep_time)
                self.requests.popleft()

        self.requests.append(time.time())

# 使用
limiter = RateLimiter(max_requests=10, window_seconds=1)  # 每秒10次

for text in texts:
    limiter.wait_if_needed()
    result = detect_ai_text(text, api_key)

5.4 最佳实践清单

实践 说明
✅ 使用HTTPS 保障数据安全
✅ 错误处理 捕获异常,避免程序崩溃
✅ 重试机制 网络不稳时自动重试
✅ 限流控制 避免触发API限流
✅ 日志记录 记录请求和响应,便于排查
✅ 参数校验 发请求前检查参数合法性
✅ 结果缓存 相同文本避免重复检测
✅ 异步处理 大批量时使用异步提高效率

六、常见问题

Q1:API免费额度是多少?

UnFox AI企业版提供不同的套餐:

套餐 额度 价格
基础版 1000次/天 免费
专业版 10000次/天 按量计费
企业版 无限 定制

具体以官网为准:https://unfox.cn/

Q2:请求超时怎么办?

建议设置合理的超时时间:

response = requests.post(url, headers=headers, json=payload, timeout=30)

Q3:如何处理长文本?

UnFox AI API对单次请求有长度限制(约10000字)。

处理长文本的方法:

  1. 分段检测:把长文本拆成多段,分别检测,取平均
  2. 截断检测:只检测前10000字(可能影响准确率)
def detect_long_text(text, api_key, max_length=10000):
    """处理长文本"""
    if len(text) <= max_length:
        return detect_ai_text(text, api_key)

    # 分段检测
    segments = [text[i:i+max_length] for i in range(0, len(text), max_length)]
    results = [detect_ai_text(seg, api_key) for seg in segments]

    # 取平均AI率
    avg_rate = sum(r['data']['ai_rate'] for r in results) / len(results)

    return {'ai_rate': avg_rate}

七、总结

7.1 接入流程

1. 获取API Key
      ↓
2. 阅读API文档
      ↓
3. 安装SDK/依赖
      ↓
4. 编写代码调用
      ↓
5. 错误处理
      ↓
6. 测试上线

7.2 示例代码汇总

语言 示例代码位置
Python 见上文3.1-3.5
Node.js 见上文4.1-4.4
Java 参考Python逻辑
Go 参考Python逻辑

7.3 资源链接

7.4 注意事项

  1. API Key要保密
  2. 注意请求限流
  3. 做好错误处理
  4. 保护用户隐私

有问题可以查看官方文档或联系技术支持。


API接入有疑问可参考官方文档,或联系UnFox AI技术支持。

Unfox AI

Written by Unfox AI

Content Team

Passionate about creating exceptional content and sharing knowledge with the community.

Related Articles

Ready to start your next project?

Join thousands of developers who are already building amazing applications with our platform.