关键:base_url 指向 ThisToken.AI,兼容 OpenAI SDK
client = OpenAI(
api_key=os.environ["THISTOKEN_API_KEY"],
base_url="https://api.thistoken.ai/v1",
)
def chat_and_log(prompt: str, model: str = "gpt-4o-mini"):
resp = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
)
usage = resp.usage
row = {
"time": datetime.now().isoformat(timespec="seconds"),
"model": model,
"prompt_tokens": usage.prompt_tokens,
"completion_tokens": usage.completion_tokens,
"total_tokens": usage.total_tokens,
}
追加写入 CSV,便于后续用任何表格工具分析
with open("usage_log.csv", "a", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=row.keys())
if f.tell() == 0:
writer.writeheader()
writer.writerow(row)
print(f"[已记录] {row['model']} 消耗 {row['total_tokens']} tokens")
return resp.choices[0].message.content
if __name__ == "__main__":
answer = chat_and_log("用一句话解释什么是token计费。")
print(answer)
Run it:
python usage_logger.py
If your terminal prints the response and token count, and `usage_log.csv` appears in the current directory, your first script is working. **Based on my own timeline, going from registration to a working script took less than 15 minutes end to end**—faster than figuring out the dashboard export process of any single vendor.
## From a 15-Minute Script to Daily Automated Reports
Once it's running, I recommend iterating along this path (each step is incremental—no need to do it all at once):
**1. Extract the statistics function.** The code above already breaks out the `usage` object. In a real project, move the logging logic from `chat_and_log` into your call layer, and the consumption of all requests will automatically land in the same CSV.
**2. Add an aggregation layer.** Use pandas to read the CSV once a day, aggregate by model and by date, and you'll have a daily consumption table in ten minutes. In my experience, going from "90 minutes of monthly manual reconciliation" to "10 seconds of daily summary review" took only about two hours of development time—an extremely high return on investment.
**3. Set up scheduled delivery.** On Linux, configure a crontab entry; on Windows, use Task Scheduler, to send the daily summary to your team chat or inbox every morning. From then on, usage data is pushed to you instead of you pulling it.
**4. Set threshold alerts.** Send a notification when daily consumption exceeds a limit you set. Once this is done, you'll know the day a cost anomaly occurs, instead of being shocked by the month-end bill—**the detection delay shrinks from up to 30 days to under 1 day**.
## A Few Practical Tips
- **Don't hardcode your keys**. Environment variables or a .env file plus .gitignore is the lowest-cost security baseline.
- **Log the calling context**. Add a `feature` column to your CSV to note which feature made each call; at month's end, you can see which feature is the cost driver and cut low-value calls.
- **Validate with low volume first**. Before rolling out the script, run it with a low-cost model for a few days, and confirm the statistics methodology is correct before fully integrating.
## Final Thoughts
The cost of putting off usage tracking is hidden: an hour or two of reconciliation each month, budget decisions made by gut feeling, and cost anomalies discovered only at month's end. Turning it into a script is a one-time investment of about two hours, and after that, all it takes is a glance at the summary each month.
The math is simple: **you break even in the first month, then net over an hour every month thereafter, plus real-time cost visibility**. For indie developers and small teams, this might be the highest ROI code you'll ever write.
If you don't have a ThisToken.AI account yet, start by registering here—in 15 minutes, your first row of usage data will land in your own CSV: https://api.thistoken.ai/register
---
Ready to try it yourself? Sign up at https://api.thistoken.ai/register to get your API key and start building.Token.AI を試してみませんか?
プロジェクトレベルの API Key を作成し、コンソールでチャネルを有効にして、ルーティング、予算、監査ログを設定しましょう。
注册 ThisToken.AI 并获取 API Key