Polyv Help Center

Help Center

Polyv AI Q&A Assistant API Documentation

Updated: 2025-05-23 11:42:35

Table of Contents

API Overview

API Name API Endpoint Request Method Description
Get Token https://api.polyv.net/live/v3/common/token/get-ai-token POST Obtain access token for AI Q&A Assistant
AI Chat Q&A https://api.polyv.net/ai/v1/chat/question GET Send questions to AI assistant and receive streaming responses

Call Flow

  1. Get Token

    • Call the Get Token API using application information (appId, secretKey)
    • Generate signature and submit the request
    • Retrieve the returned token
  2. Use Token for AI Chat

    • Call the AI Chat API using the token obtained in the previous step
    • Process the streamed data
    • Concatenate the returned content to get the complete answer

API Details

Get Token API

Basic Information

  • API Endpoint: https://api.polyv.net/live/v3/common/token/get-ai-token
  • Request Method: POST
  • Data Format: form-data

Request Parameters

Parameter Type Required Description
appId String Yes Customer's application ID on Polyv
timestamp Long Yes Current timestamp (milliseconds)
viewerId String Yes Viewer/User unique identifier
sign String Yes Request signature

Response Parameters

Parameter Type Description
code Integer Status code, 200 indicates success
message String Response message
status String Response status
data.token String Access token for AI Q&A Assistant
data.userId String User ID
data.validTime Integer Token validity period (seconds)

Response Example

{
  "code": 200,
  "message": "success",
  "status": "success",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "userId": "viewer123456",
    "validTime": 3600
  }
}

AI Chat Q&A API

Basic Information

  • API Endpoint: https://api.polyv.net/ai/v1/chat/question
  • Request Method: GET
  • Response Format: EventStream (streaming response)

Request Parameters

Parameter Type Required Description
question String Yes User's question content
aiId String Yes AI assistant ID
token String Yes Access token obtained from the Get Token API

Response Format

The API returns data in EventStream (Server-Sent Events) format, requiring client support for this format:


event: message
data: {"content":"我可以回答您关于", "done":false}

Response Data Description

Event Type Data Format Description
message JSON Partial AI-generated answer content
done JSON Indicates the answer has ended

Data Field Description

Field Type Description
content String AI-generated answer content
done Boolean Whether the AI-generated answer content is complete

Signature Generation Rules

Steps to generate the sign parameter:

  1. Sort all parameters except sign in ascending order by parameter name ASCII code
  2. Concatenate the sorted parameters in key=value format, joined by &
  3. Prepend and append the secret key (secretKey) to the concatenated string
  4. Perform MD5 encryption on the concatenated string and convert to uppercase

Signature formula:

MD5(secretKey + 排序并拼接后的参数字符串 + secretKey).toUpperCase()

Code Examples

Python Complete Call Flow

import time
import hashlib
import json
import requests
import sseclient  # 需要安装: pip install sseclient-py

POLYV_CONFIG = {
    "app_id": '保利威平台appId',
    "app_secret": '保利威平台appSecret'
}

# 第一步:获取Token
def get_ai_token(viewer_id):
 """获取聊天Token的接口"""

    # 构建请求参数
    if viewerId is None:
        print("viewerId is None")
        viewerId = f"polyvWebscriptViewerId-{uuid.uuid4()}"

    print("最后的viewerId", viewerId)
    form_data = {
        "appId": POLYV_CONFIG["app_id"],
        "timestamp": int(time.time() * 1000),
        "viewerId": viewerId
    }

    # 添加签名
    form_data["sign"] = create_api_sign(POLYV_CONFIG["app_secret"], form_data)

    # 发送请求到保利威API
    response = requests.post(
        "https://api.polyv.net/live/v3/common/token/get-ai-token",
        data=form_data
    )

    print(response.json())
    token = response.json().get('data')
    return token
# 第二步:使用token调用AI聊天接口
def chat_with_ai(token, ai_id, question):
    """向AI助手发送问题并获取回答"""
    # 构建请求URL
    url = f"https://api.polyv.net/ai/v1/chat/question?question={question}&aiId={ai_id}&token={token}"

    # 发送请求
    headers = {
        "Accept": "text/event-stream",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
    }

    response = requests.get(url, headers=headers)
    print(response)
    client = sseclient.SSEClient(response)

    # 处理EventStream响应
    answer = ""
    try:
        for event in client.events():
            data = json.loads(event.data)
            print(data)
            content = data.get("content", "")
            done = data.get("done")
            if not done:
                print(f'过程数据:===>{content}')
                answer += content
                # 处理回答片段
            else:
                answer += content
                print("回答完成")
                break
        return answer
    except Exception as e:
        print(f"处理响应出错: {e}")
        raise

# 使用示例
if __name__ == "__main__":
    # 配置参数
    APP_ID = "你的appId"
    SECRET_KEY = "你的secretKey"
    VIEWER_ID = "用户唯一标识"
    AI_ID = "1159"
    QUESTION = "你好,请介绍一下自己"
    
    try:
        # 注意:实际应用中token获取应在后端进行
        token = get_ai_token(APP_ID, SECRET_KEY, VIEWER_ID)
        print(f"获取token成功: {token}")
        
        # 使用token进行聊天
        answer = chat_with_ai(token, AI_ID, QUESTION)
        print(f"完整回答: {answer}")
    except Exception as e:
        print(f"错误: {e}")

FAQ

  1. Token Security

    • The Get Token API must be called on the server side to avoid exposing the secretKey to the frontend
    • You can encapsulate a Get Token API in your own backend service for frontend calls
  2. Token Validity

    • Token validity is typically 3600 seconds (1 hour)
    • It is recommended to automatically refresh the token before it expires, e.g., set a scheduled task to refresh the token 5-10 minutes before expiration
  3. EventStream Handling

    • Different frontend frameworks may handle EventStream differently
    • All content fields from message events must be correctly concatenated to obtain the complete answer
    • When an event of type done is received, it indicates the current answer has ended
  4. Error Handling

    • It is recommended to add a timeout mechanism to prevent requests from hanging indefinitely due to network issues
    • Add an error retry mechanism to automatically reconnect during network fluctuations
  5. Request Limits

    • API call frequency limit: Maximum 500 requests per second per appId
    • Ensure reasonable control of request frequency to avoid triggering rate limiting
联系客服,在线咨询