API文档

FASTPASS AI 智能题库系统接口文档

搜索接口

GET/POST
/api/search
搜索问题答案

请求参数

参数名 类型 必需 说明 示例
title string 问题内容 什么是人工智能?
type string 问题类型:single/multiple/judgement/completion/others single
options string 选项内容(JSON格式或文本) ["选项A", "选项B", "选项C"]
provider string 指定AI提供商:deepseek/alibaba/openai/google deepseek
token string 访问令牌(如果配置了安全访问) your-access-token
cache boolean 是否使用缓存(默认true) true

响应格式

{
  "code": 1,
  "question": "搜索的问题内容",
  "answer": "AI返回的答案",
  "provider": "使用的AI提供商",
  "source": "数据来源(db或ai)",
  "process_time": "25.34ms"
}

请求示例

// GET请求示例
// 直接在浏览器地址栏或使用fetch API

// 示例1:简单搜索
fetch('/api/search?title=什么是人工智能')
  .then(response => response.json())
  .then(data => console.log(data));

// 示例2:完整参数
fetch('/api/search?title=什么是人工智能&type=single&provider=deepseek')
  .then(response => response.json())
  .then(data => console.log(data));
// POST请求示例
// 使用JSON格式提交数据

fetch('/api/search', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: '什么是人工智能?',
    type: 'single',
    options: '["机器学习", "深度学习", "自然语言处理"]',
    provider: 'deepseek'
  })
})
.then(response => response.json())
.then(data => console.log(data));
# cURL GET请求
curl "http://localhost:8681/api/search?title=什么是人工智能"

# cURL POST请求
curl -X POST "http://localhost:8681/api/search" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "什么是人工智能?",
    "type": "single",
    "provider": "deepseek"
  }'
POST
/api/batch-search
批量搜索问题答案

请求参数(JSON格式)

{
  "questions": [
    {
      "title": "问题1",
      "type": "single",
      "options": "选项内容"
    },
    {
      "title": "问题2",
      "type": "multiple"
    }
  ],
  "batch_size": 10,
  "provider": "deepseek",
  "cache": true
}

提供商接口

GET
/api/providers
获取AI提供商列表和状态

响应格式

{
  "providers": ["deepseek", "alibaba", "openai", "google"],
  "default": "deepseek",
  "provider_details": {
    "deepseek": {
      "name": "DeepSeek",
      "is_available": true,
      "model": "deepseek-chat",
      "api_key": "sk-...",
      "base_url": "https://api.deepseek.com/v1"
    },
    "alibaba": {
      "name": "阿里百炼",
      "is_available": true,
      "model": "qwen-turbo",
      "api_key": "sk-...",
      "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1"
    }
  }
}
POST
/api/providers/switch/{provider_name}
切换默认AI提供商

请求示例

// 切换到阿里百炼提供商
fetch('/api/providers/switch/alibaba', {
  method: 'POST'
})
.then(response => response.json())
.then(data => console.log(data));
POST
/api/providers/cache/clear
清除所有AI提供商的缓存

系统接口

GET
/api/system/stats
获取系统统计信息

响应格式

{
  "name": "FASTPASS AI",
  "version": "2.0.0",
  "total_questions": 12458,
  "default_provider": "deepseek",
  "cache_enabled": true,
  "available_providers": ["deepseek", "alibaba", "openai", "google"],
  "database_status": "connected",
  "model_stats": {
    "single": 5689,
    "multiple": 3210,
    "judgement": 1854,
    "completion": 1250,
    "others": 455
  },
  "uptime": 86400
}
GET
/api/system/health
系统健康检查

响应格式

{
  "status": "ok",
  "message": "AI题库服务运行正常",
  "version": "2.0.0",
  "cache_enabled": true,
  "default_provider": "deepseek",
  "available_providers": ["deepseek", "alibaba"],
  "database_status": "connected",
  "timestamp": "2025-01-04T21:29:24.123Z"
}
GET
/api/system/info
获取系统基本信息

使用示例

JavaScript 使用示例

浏览器端使用

class FastpassAI {
  constructor(baseUrl = 'http://localhost:8681') {
    this.baseUrl = baseUrl;
  }

  // 搜索问题
  async searchQuestion(question, type = '', options = '', provider = '') {
    const params = new URLSearchParams({ title: question });
    if (type) params.append('type', type);
    if (options) params.append('options', options);
    if (provider) params.append('provider', provider);

    const response = await fetch(`${this.baseUrl}/api/search?${params}`);
    return await response.json();
  }

  // 批量搜索
  async batchSearch(questions, provider = '') {
    const response = await fetch(`${this.baseUrl}/api/batch-search`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ questions, provider })
    });
    return await response.json();
  }

  // 获取提供商信息
  async getProviders() {
    const response = await fetch(`${this.baseUrl}/api/providers`);
    return await response.json();
  }
}

// 使用示例
const ai = new FastpassAI();

// 单次搜索
ai.searchQuestion('什么是人工智能?', 'single')
  .then(result => {
    if (result.code === 1) {
      console.log('答案:', result.answer);
    }
  });

// 批量搜索
ai.batchSearch([
  { title: '问题1', type: 'single' },
  { title: '问题2', type: 'multiple' }
]).then(results => {
  console.log('批量结果:', results);
});

Python 使用示例

Python客户端

import requests
import json

class FastpassAIClient:
    def __init__(self, base_url="http://localhost:8681"):
        self.baseUrl = base_url
    
    def search(self, title, question_type="", options="", provider=""):
        """搜索问题答案"""
        params = {"title": title}
        if question_type:
            params["type"] = question_type
        if options:
            params["options"] = options
        if provider:
            params["provider"] = provider
        
        response = requests.get(f"{self.baseUrl}/api/search", params=params)
        return response.json()
    
    def batch_search(self, questions, provider=""):
        """批量搜索"""
        data = {
            "questions": questions,
            "provider": provider
        }
        
        response = requests.post(
            f"{self.baseUrl}/api/batch-search",
            json=data,
            headers={"Content-Type": "application/json"}
        )
        return response.json()
    
    def get_providers(self):
        """获取提供商列表"""
        response = requests.get(f"{self.baseUrl}/api/providers")
        return response.json()

# 使用示例
if __name__ == "__main__":
    client = FastpassAIClient()
    
    # 单次搜索
    result = client.search("什么是人工智能?", "single")
    if result.get("code") == 1:
        print(f"答案: {result['answer']}")
    
    # 批量搜索
    questions = [
        {"title": "什么是机器学习?", "type": "single"},
        {"title": "深度学习的应用有哪些?", "type": "multiple"}
    ]
    batch_result = client.batch_search(questions)
    print(f"批量搜索结果: {batch_result}")
    
    # 获取提供商
    providers = client.get_providers()
    print(f"可用提供商: {providers.get('providers', [])}")

常见问题

Q: API请求返回错误码0是什么原因?

A: 错误码0表示请求失败,可能的原因有:问题内容为空、AI提供商不可用、网络连接问题等。请检查请求参数和服务器状态。

Q: 如何设置访问令牌?

A: 在config.yaml中配置security.access_token,然后在API请求中添加token参数或X-Access-Token请求头。

Q: 支持哪些AI提供商?

A: 目前支持DeepSeek、阿里百炼、OpenAI、Google Studio。需要在config.yaml中配置相应的API密钥。

Q: 响应中的source字段是什么意思?

A: source字段表示答案来源:'db'表示来自数据库缓存,'ai'表示来自AI实时生成。