跳转到主要内容
ARouter 支持通过在 API 请求中传递 user 字段来追踪每个用户的使用情况。这让您可以将 API 成本归因于应用程序中的具体用户,并在用户级别监控使用模式。

传递用户 ID

在任何聊天补全请求中包含 user 字段:
{
  "model": "openai/gpt-5.4",
  "messages": [{"role": "user", "content": "Hello!"}],
  "user": "user_12345"
}
user 值可以是系统中标识终端用户的任意字符串——数据库 ID、哈希邮箱或会话 ID 均可。ARouter 不验证或解析此值。
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.arouter.ai/v1",
  apiKey: "lr_live_xxxx",
});

async function chatWithUser(userId: string, message: string) {
  const response = await client.chat.completions.create({
    model: "openai/gpt-5.4",
    messages: [{ role: "user", content: message }],
    user: userId,
  });
  return response.choices[0].message.content;
}

隐私注意事项

请勿将个人身份信息(PII)作为 user 值传递。请使用不透明标识符,例如哈希 ID 或数据库主键。
推荐做法:
import hashlib

# 在传递之前对用户邮箱进行哈希处理
user_id = hashlib.sha256(user_email.encode()).hexdigest()[:16]

# 或使用不透明的数据库 ID
user_id = str(user.id)  # 例如 "usr_abc123"

按用户查看使用情况

用户级别的使用数据可在活动导出中获取。每条记录都包含您传递的 user 字段,让您能够:
  • 计算每位用户的 Token 消耗和成本
  • 识别高使用量用户以进行容量规划
  • 检测异常使用模式或滥用行为
  • 为终端用户构建基于使用量的计费

活动导出 API

按用户过滤查询使用记录:
curl "https://api.arouter.ai/v1/activity?user=user_12345&limit=100" \
  -H "Authorization: Bearer lr_live_xxxx"

使用场景

按用户成本分摊

追踪服务每位客户的实际成本:
// 传递客户 ID
const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4.6",
  messages: conversation,
  user: `customer_${customerId}`,
});

// 之后:查询活动导出以获取每位客户的总成本

滥用检测

按用户监控异常使用模式:
# 每位用户使用自己的标识符
response = client.chat.completions.create(
    model="openai/gpt-5.4",
    messages=[{"role": "user", "content": user_message}],
    user=f"app_user_{user.id}",
)

多租户应用

在多租户 SaaS 应用中,传递组织或租户 ID:
const response = await client.chat.completions.create({
  model: "google/gemini-2.5-flash",
  messages: messages,
  user: `org_${organizationId}`,
});

注意事项

  • user 字段是可选的。不包含此字段的请求仍会在 API Key 的聚合使用量下被追踪。
  • 用户 ID 以不透明字符串形式存储。ARouter 不验证、解析或解读其格式。
  • 用户追踪数据包含在活动导出记录中。
  • 团队级别的使用控制请参阅组织管理