Skip to main content

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エンドポイント(デフォルト)
    sync=False,                  # True: 同期送信(Lambda用)
    flush_on_exit=True,          # 終了時に未送信ログをフラッシュ
    batch_size=10,               # バッチサイズ
    flush_interval=5.0,          # 自動フラッシュ間隔(秒)
    enabled=True,                # False: ログ無効化(テスト用)
)

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"]
)

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.7.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aitracer 1.7.1
File Size Uploaded Provenance Actions
aitracer-1.7.1.tar.gz 135.3 kB Without provenance Details for aitracer-1.7.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aitracer 1.7.1
File Interpreter ABI Platform Actions
aitracer-1.7.1-py3-none-any.whl Python 3 none any Details for aitracer-1.7.1-py3-none-any.whl

Total release size: 163.0 kB

Release files / aitracer-1.7.1.tar.gz

Download URL aitracer-1.7.1.tar.gz
Size 135.3 kB
Tags Source
SHA-256 checksum
How to use checksums
77966beec00cbef278447254ccf0f94efbaecfd5463f17e8080763fc0702afc6
BLAKE2b-256 checksum
How to use checksums
3d16b44a6582dd329f331d0dbb8a57d614da8f811b0f11bd8cce5a383c508968
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.7.1-py3-none-any.whl

Download URL aitracer-1.7.1-py3-none-any.whl
Size 27.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8d9c6650cb01eacbac4a56651e2b4830d9a00a1a6572502e6a63f4bbf00695cf
BLAKE2b-256 checksum
How to use checksums
5bebb31ca022764886b94a85e7091f0e8d2b22eb20b97613498443d635ecb5f0
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.7.1

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page