AITracer Python SDK
AIエージェント/LLMアプリの実行ログ・コスト・パフォーマンスを監視するためのPython SDK。
本番環境
- API エンドポイント:
https://api.aitracer.co - ダッシュボード:
https://app.aitracer.co
SDKはデフォルトで https://api.aitracer.co に接続します。
インストール
pip install aitracer
クイックスタート
基本的な使い方
from aitracer import AITracer
from openai import OpenAI
# AITracerを初期化
tracer = AITracer(
api_key="at-xxxxxxxx",
project="my-chatbot"
)
# OpenAIクライアントをラップ
client = tracer.wrap_openai(OpenAI())
# 普通に使う(自動でログが送信される)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello!"}]
)
Anthropic対応
from aitracer import AITracer
from anthropic import Anthropic
tracer = AITracer(
api_key="at-xxxxxxxx",
project="my-chatbot"
)
# Anthropicクライアントをラップ
client = tracer.wrap_anthropic(Anthropic())
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}]
)
Google Gemini対応
from aitracer import AITracer
import google.generativeai as genai
tracer = AITracer(
api_key="at-xxxxxxxx",
project="my-chatbot"
)
# Geminiを設定
genai.configure(api_key="your-google-api-key")
model = genai.GenerativeModel("gemini-1.5-flash")
# Geminiモデルをラップ
model = tracer.wrap_gemini(model)
response = model.generate_content("Hello!")
print(response.text)
ストリーミングも対応しています:
response = model.generate_content("Write a story...", stream=True)
for chunk in response:
print(chunk.text, end="")
トレース機能
複数のAPI呼び出しをグループ化して追跡できます。
with tracer.trace("user-query-123") as trace:
# この中のAPI呼び出しは同じtrace_idでグループ化される
response1 = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize this..."}]
)
response2 = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Translate to Japanese..."}]
)
# メタデータを追加
trace.set_metadata({
"user_id": "user-456",
"feature": "summarization"
})
# タグを追加
trace.add_tag("production")
# 複数のタグを一括追加
trace.add_tags(["premium", "beta"])
ストリーミング対応
ストリーミングレスポンスも自動的にログされます。
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a story..."}],
stream=True
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
# ストリーム完了後に自動的にログが送信される
設定オプション
tracer = AITracer(
# 必須
api_key="at-xxxxxxxx", # または AITRACER_API_KEY 環境変数
project="my-chatbot", # または AITRACER_PROJECT 環境変数
# オプション
base_url="https://api.aitracer.co", # APIエンドポイント(デフォルト。https 必須)
sync=False, # True: 同期送信(Lambda用)
flush_on_exit=True, # 終了時に未送信ログをフラッシュ
batch_size=10, # バッチサイズ
flush_interval=5.0, # 自動フラッシュ間隔(秒)
enabled=True, # False: ログ無効化(テスト用)
capture_content=True, # False: LLM の入出力の本文を送らない(後述)
pii_detection=False, # True: 送信内容の個人情報をマスク
)
Note:
base_urlはhttps://が必須です。http://は開発用にlocalhost/127.0.0.1/::1のときだけ使えます。それ以外の URL は初期化時にValueErrorになります。
本文を送らない(capture_content=False)
議事録など機密性の高い本文を扱うアプリでは、capture_content=False を指定すると、LLM の入出力の本文を AITracer に送らず、メタ情報だけを送ります。氏名や住所は正規表現によるマスキング(pii_detection)では確実に検出できないため、本文そのものを送らないのが最も確実な対策です。
tracer = AITracer(
api_key="at-xxxxxxxx",
project="minutes-app",
capture_content=False,
)
| 項目 | 送信内容 |
|---|---|
| モデル・プロバイダー、トークン数(キャッシュ分を含む)、レイテンシ、ステータス | そのまま送信 |
| トレース ID・スパン ID・セッション ID・ユーザー ID | そのまま送信 |
ログの metadata(トレースのメタデータ・タグを含む) |
そのまま送信 |
セッションの name / metadata、イベントの event_type / name、フィードバックの種類・スコア |
そのまま送信 |
ログの input / output |
{"redacted": true} に置き換え |
ログの error_message |
例外クラス名(例: RateLimitError)に置き換え。手動 log() で error_type を渡さない場合は送らない |
イベントの data |
{"redacted": true} に置き換え |
フィードバックの comment |
送らない(null) |
- トークン数はプロバイダーの応答(usage)から取得するため、本文を送らなくてもコストは従来どおり計算されます。Whisper のコスト計算に使う
audio_duration_secondsもmetadataで送られます(ファイル名はinputに含まれるため送られません)。 metadata・セッション名・イベント名はそのまま送られるので、本文や個人情報を入れないでください。pii_detection=Trueと併用すると、送られる項目にはマスキングが適用されます。- LLM への入力や、呼び出し元に返る応答は変更されません。ダッシュボードには本文が表示されず、本文を使う機能(リプレイなど)は使えません。
Lambda/サーバーレス環境
サーバーレス環境では sync=True を使用してください。
tracer = AITracer(
api_key="at-xxxxxxxx",
project="my-lambda",
sync=True # 同期送信
)
環境変数
export AITRACER_API_KEY=at-xxxxxxxx
export AITRACER_PROJECT=my-chatbot
# 環境変数から自動で読み込み
tracer = AITracer()
手動ログ
自動ラッパーを使わずに手動でログを送信することもできます。
tracer.log(
model="gpt-4o",
provider="openai",
input_data={"messages": [{"role": "user", "content": "Hello"}]},
output_data={"content": "Hi there!"},
input_tokens=10, # 非キャッシュ入力トークン数(int, 任意)
output_tokens=5, # 出力トークン数(int, 任意)
cache_read_input_tokens=0, # プロンプトキャッシュから読み出した入力トークン数(int, 任意)
cache_creation_input_tokens=0, # プロンプトキャッシュに書き込んだ入力トークン数(int, 任意)
latency_ms=150,
status="success",
metadata={"user_id": "user-123"},
tags=["production"]
)
エラーを記録するときは error_message に加えて error_type(例外クラス名)を渡すと、capture_content=False のときは error_message の代わりに error_type が送られます。
except Exception as e:
tracer.log(..., status="error", error_message=str(e), error_type=type(e).__name__)
Note:
input_tokensは非キャッシュ分の入力トークンに正規化されます。ラッパー(wrap_openai/wrap_anthropic/wrap_gemini)使用時は、プロンプトキャッシュのトークンがcache_read_input_tokens/cache_creation_input_tokensに自動計上されます。
フラッシュとシャットダウン
# 未送信のログを即座に送信
tracer.flush()
# シャットダウン(フラッシュ + リソース解放)
tracer.shutdown()
ライセンス
Copyright (c) 株式会社HARO. All rights reserved.
Metadata
Release files for aitracer 1.8.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| aitracer-1.8.0.tar.gz | 140.2 kB | Without provenance | Details for aitracer-1.8.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| aitracer-1.8.0-py3-none-any.whl | Python 3 | none | any | Details for aitracer-1.8.0-py3-none-any.whl |
Total release size: 170.1 kB
Release files / aitracer-1.8.0.tar.gz
| Download URL | aitracer-1.8.0.tar.gz |
|---|---|
| Size | 140.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ed588e195a9e27df3369cb35e07f209c56184a0624be730f85e9ddfb0618f6e8
|
|
BLAKE2b-256 checksum How to use checksums |
4c60dc79e279a853824f747c14ebe9a18a4fccb19e0600d6621783c0ec916dd3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.2
|
Release files / aitracer-1.8.0-py3-none-any.whl
| Download URL | aitracer-1.8.0-py3-none-any.whl |
|---|---|
| Size | 29.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ebbca5fbe54e4b373fe3c0a764620af91ee7a00061608cba37d60a712d35d239
|
|
BLAKE2b-256 checksum How to use checksums |
23d6a09cf65b9a84559edc5db649b1d0838c13be2c499375d12b28a75b400271
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.2
|
Security for aitracer 1.8.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.