> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 在调用模型前估算请求成本

> 在调用模型前，将模型目录中的价格与端点计费单位（如 Token、图片、音频时长或任务数量）结合起来，估算 CometAPI 请求成本。

在调用模型前，将模型目录中的价格与端点的计费单位结合起来估算成本：Token、图片、音频时长或视频任务。将该估算视为预算护栏，然后在请求完成后使用实际用量和计费记录。

## 估算基于 Token 的调用

下面的 Python 示例使用已配置的价格值来估算基于 Token 的请求成本：

```python theme={null}
import math
import os

prompt = "Write a short product description for CometAPI."
max_output_tokens = 200

input_price_per_1m = float(os.environ["MODEL_INPUT_PRICE_PER_1M"])
output_price_per_1m = float(os.environ["MODEL_OUTPUT_PRICE_PER_1M"])

estimated_input_tokens = math.ceil(len(prompt) / 4)

estimated_cost = (
    estimated_input_tokens * input_price_per_1m
    + max_output_tokens * output_price_per_1m
) / 1_000_000

print(f"Estimated maximum cost: ${estimated_cost:.6f}")
```

结果是调用前的估算值：

```text theme={null}
Estimated maximum cost: $0.000123
```

## 设置最大输出预算

下面的请求限制了生成输出，因此估算值具有明确的上限：

```bash theme={null}
curl https://api.cometapi.com/v1/chat/completions \
  -H "Authorization: Bearer $COMETAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "your-model-id",
    "messages": [
      {
        "role": "user",
        "content": "Write a short product description for CometAPI."
      }
    ],
    "max_completion_tokens": 200
  }'
```

响应会在模型调用后包含实际用量：

```json theme={null}
{
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 42,
    "total_tokens": 52
  }
}
```

## 估算基于任务的调用

下面的 JavaScript 示例估算了基于任务的工作流，例如图片或视频生成：

```javascript theme={null}
const taskCount = 3;
const pricePerTask = Number(process.env.MODEL_PRICE_PER_TASK);

const estimatedCost = taskCount * pricePerTask;

console.log(`Estimated maximum cost: $${estimatedCost.toFixed(4)}`);
```

结果就是任务预算：

```text theme={null}
Estimated maximum cost: $0.4500
```

## 常见错误

| Error      | Fix                                     |
| ---------- | --------------------------------------- |
| 使用了错误模型的价格 | 从模型目录中复制相同 model ID 的价格。                |
| 忽略输出 Token | 设置 `max_completion_tokens` 或该端点特定的输出限制。 |
| 将估算当作发票    | 在调用后将估算与实际用量进行比较。                       |
| 缺少任务乘数     | 对于图片、音频和视频，检查计费是按任务、按秒，还是按生成资产计费。       |

## 相关链接

* [定价](https://www.cometapi.com/pricing/)
* [模型目录](https://www.cometapi.com/models/)
* [模型页面](/zh-Hans/overview/models)
* [关于定价](/zh-Hans/pricing/about-pricing)
* [CometAPI 快速开始](/zh-Hans/overview/quick-start)

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "TechArticle",
        "@id": "https://apidoc.cometapi.com/guides/how-to-estimate-cost-before-calling-a-model",
        "headline": "如何在调用模型之前估算成本？",
        "description": "在调用模型之前，结合模型目录定价与输入大小、输出限制或任务数量来估算 CometAPI 请求成本。",
        "url": "https://apidoc.cometapi.com/guides/how-to-estimate-cost-before-calling-a-model",
        "author": {
          "@type": "Organization",
          "name": "CometAPI"
        },
        "publisher": {
          "@type": "Organization",
          "name": "CometAPI",
          "url": "https://www.cometapi.com"
        }
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "CometAPI 文档",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "指南",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "如何在调用模型之前估算成本？",
            "item": "https://apidoc.cometapi.com/guides/how-to-estimate-cost-before-calling-a-model"
          }
        ]
      }
    ]
    }
    `}
</script>
