予算超過からの復旧

BudgetExceededは単なるエラーメッセージではなく、復旧に利用できる構造化オブジェクトです。予算、必須項目の合計トークン数、超過量、トークンプロファイルの識別情報とフィンガープリント、項目ごとの累積コスト、予算を超えた項目、除外済み項目、利用可能な方針、部分マニフェストを保持します。

内容を確認して復旧する

次の例では、決定論的な概算プロファイルを使用します。切り詰めが許可されるのは、必須のText項目でtruncatable=Trueを明示しているためです。

import cognoxium as cx

frame = cx.CognitionFrame.from_records([
    {
        "id": "policy",
        "payload": "x" * 60,
        "sources": ["app://policy"],
        "trust": "trusted",
        "retention": "required",
        "truncatable": True,
        "created_at": "2026-01-01T00:00:00Z",
    }
])

try:
    frame.pack(budget=10, token_profile=cx.profiles.approximate())
except cx.BudgetExceeded as error:
    print(error.code)
    print(error.budget, error.required_tokens, error.overflow_tokens)
    print(error.exceeded_at_item_id)
    print(error.item_costs[0].to_dict())
    print(error.available_strategies)

pack = frame.pack(
    budget=10,
    token_profile=cx.profiles.approximate(),
    overflow=cx.Overflow.truncate_truncatable(side="tail"),
)
print(pack.manifest.total_tokens)
print(pack.manifest.truncations[0]["id"])
print(pack.manifest.truncations[0]["removed_tokens"])
CX_BUDGET_001
10 15 5
policy
{'id': 'policy', 'tokens': 15, 'cumulative_tokens': 15, 'retention': 'required', 'priority': 0.0, 'truncatable': True, 'min_tokens': 0}
('error', 'truncate_truncatable')
10
policy
5

復旧方法の選択

  1. 送信先が対応している場合は、予算を増やします

  2. そのコンテンツが必須ではなくなったとアプリケーション側で判断した場合に限り、パッキング前に降格します

  3. 安全に短縮できるTextでは、切り詰めを明示的に有効化します

  4. モデル呼び出しを拒否または延期し、構造化された診断情報を運用担当者へ提示します。

例外を捕捉して、必須項目を黙って削除してはいけません。

切り詰めの制約

  • truncatable=Trueを指定したTextだけが対象です。

  • side="tail"は先頭側を残し、side="head"は末尾側を残します。

  • マーカーもトークン予算に含まれます。

  • min_tokensは、保持するコンテンツの最小トークン数を指定します。

  • JSON、Reference、Binary、およびtruncatable=Falseの項目は、途中まで切り詰められることはありません。

  • 切り詰め可能な項目を短縮しても収まらない場合は、BudgetExceededが再び送出されます。

  • 切り詰めると新しいコンテンツハッシュが生成され、元のハッシュと来歴、およびトークン数の変化がマニフェストへ記録されます。

ローカライズ

取得時のロケールによってstr(error)の表示が固定されます。構造化データを変えずに再表示できます。

print(error.code)
print(error.render("en"))
print(error.render("ja"))

プログラムの分岐には、翻訳済みメッセージではなく、必ずerror.code、属性、partial_manifestを使用してください。