Logo
核心能力/智能问答

API 接口

金融投研知识问答 API 接口文档

接口概览

金融投研知识问答 API 采用 OpenAI 兼容格式,可直接使用 OpenAI SDK 调用。

属性说明
接口地址https://api.easylink-ai.com/v1/chat/completions
请求方法POST
内容类型application/json
响应格式application/json 或 SSE(流式)
SDK 兼容OpenAI Python SDK、OpenAI Node.js SDK

认证方式

使用 Bearer Token 认证:

Authorization: Bearer YOUR_API_KEY

或使用 OpenAI SDK 时配置 api_keybase_url


快速开始

Python SDK

from openai import OpenAI

# 初始化客户端(兼容 OpenAI API)
client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.easylink-ai.com/v1"
)

# 标准 Chat Completions 调用
response = client.chat.completions.create(
    model="fin-chat",
    messages=[
        {"role": "user", "content": "比亚迪2024年Q3营收同比增长率?"}
    ],
    stream=True
)

# 流式接收响应
for chunk in response:
    delta = chunk.choices[0].delta

    # 处理文本内容
    if delta.content:
        print(delta.content, end="", flush=True)

    # 处理引用元数据(自定义扩展字段)
    if hasattr(delta, 'annotations') and delta.annotations:
        for annotation in delta.annotations:
            print(f"\n引用: {annotation['file_name']} (P{annotation['page_number']})")

cURL

curl -X POST https://api.easylink-ai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "fin-chat",
    "messages": [
      {"role": "user", "content": "比亚迪2024年Q3营收同比增长率?"}
    ],
    "stream": true
  }' \
  --no-buffer

请求参数

参数名类型必填说明
modelstring模型名称,使用 fin-chat
messagesarray对话消息数组
streamboolean是否启用流式返回,默认 false
temperaturefloat温度参数,范围 0-2,默认 1
max_tokensinteger最大生成 token 数

messages 参数结构

[
  {
    "role": "user",
    "content": "用户问题"
  },
  {
    "role": "assistant",
    "content": "助手回答"
  }
]

支持的 role 值:

  • user: 用户消息
  • assistant: 助手回答
  • system: 系统提示(可选)

响应格式

非流式响应

{
  "id": "resp_7a3f2e1c",
  "object": "chat.completion",
  "created": 1704441600,
  "model": "fin-chat",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "根据比亚迪2024年第三季度财报,营收为XXX亿元,同比增长18.94%。",
      "annotations": [{
        "file_name": "比亚迪2024Q3财报.pdf",
        "url": "https://s3.easyalpha.ai/docs/byd-q3-2024.pdf?signature=...",
        "page_number": 3
      }]
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 128,
    "completion_tokens": 64,
    "total_tokens": 192
  }
}

流式响应(SSE)

响应格式

data: {JSON对象}

data: [DONE]

每条消息以 data: 开头,包含一个 JSON 对象。流结束时发送 data: [DONE]

JSON 对象结构

{
  "id": "resp_df9f33f76ed141d081fc608584d7a2fb",
  "object": "chat.completion.chunk",
  "created": 1762399665,
  "model": "fin-chat",
  "choices": [{
    "index": 0,
    "delta": {
      "role": "assistant",
      "content": "文本内容",
      "refusal": null,
      "annotations": []
    },
    "logprobs": null,
    "finish_reason": null
  }],
  "service_tier": "default",
  "usage": null
}

字段说明

顶层字段

字段类型说明
idstring响应唯一标识符
objectstring对象类型:chat.completionchat.completion.chunk
createdinteger创建时间戳
modelstring使用的模型名称
choicesarray响应选项数组
usageobject/nullToken 使用统计

Choices 对象

字段类型说明
indexinteger选项索引,通常为 0
messageobject完整消息对象(非流式)
deltaobject增量内容对象(流式)
finish_reasonstring/null完成原因:stoplengthcontent_filter

Message/Delta 对象

字段类型说明
rolestring角色:assistant
contentstring生成的文本内容
annotationsarray自定义扩展:文档引用注释数组

Annotations 对象(文档引用)

当响应内容引用文档时,annotations 数组会包含引用信息:

字段类型说明
file_namestring文档文件名
urlstring文档访问 URL(带签名,有时效性)
page_numberinteger引用页码

示例:

{
  "file_name": "航天科技:2024年年度报告.pdf",
  "url": "https://s3.easyalpha.ai/docs/xxx.pdf?signature=...",
  "page_number": 15
}

Usage 对象

字段类型说明
prompt_tokensinteger输入 token 数
completion_tokensinteger输出 token 数
total_tokensinteger总 token 数

流式处理示例

JavaScript/TypeScript

async function callChatAPI(apiUrl, requestData) {
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify(requestData)
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    const lines = chunk.split('\n');

    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = line.slice(6);

        if (data === '[DONE]') {
          console.log('Stream completed');
          return;
        }

        try {
          const json = JSON.parse(data);
          const content = json.choices[0]?.delta?.content;
          const annotations = json.choices[0]?.delta?.annotations;

          if (content) {
            // 处理增量文本内容
            console.log(content);
          }

          if (annotations && annotations.length > 0) {
            // 处理文档引用
            console.log('References:', annotations);
          }
        } catch (e) {
          console.error('Parse error:', e);
        }
      }
    }
  }
}

Python

import requests
import json

def call_chat_api(api_url, request_data):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
    }

    response = requests.post(api_url, json=request_data, headers=headers, stream=True)

    for line in response.iter_lines():
        if line:
            line = line.decode('utf-8')
            if line.startswith('data: '):
                data = line[6:]

                if data == '[DONE]':
                    print('Stream completed')
                    break

                try:
                    json_data = json.loads(data)
                    content = json_data['choices'][0]['delta'].get('content', '')
                    annotations = json_data['choices'][0]['delta'].get('annotations', [])

                    if content:
                        # 处理增量文本
                        print(content, end='', flush=True)

                    if annotations:
                        # 处理文档引用
                        print(f'\nReferences: {annotations}')

                except json.JSONDecodeError as e:
                    print(f'Parse error: {e}')

注意事项

  1. 流式缓冲: 建议禁用客户端缓冲(如 cURL 使用 --no-buffer)以实现真正的流式体验
  2. 错误处理: 流式传输中可能出现 JSON 解析错误,需要妥善处理
  3. URL 时效性: annotations 中的文件 URL 包含签名参数,有有效期限制
  4. 编码格式: 响应采用 UTF-8 编码,支持中文等多语言字符

最佳实践

  1. UI 更新: 逐字显示内容以提供更好的用户体验
  2. 引用处理: 将文档引用以链接或注脚形式展示
  3. 错误重试: 实现指数退避重试机制
  4. Token 管理: 监控 token 使用量,避免超出限制

错误码

HTTP 状态码说明
200请求成功
400请求参数错误
401认证失败
429请求频率超限
500服务器内部错误

错误响应格式:

{
  "error": {
    "message": "错误描述",
    "type": "invalid_request_error",
    "code": "invalid_api_key"
  }
}