gateledger 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gateledger/pipeline.py ADDED
@@ -0,0 +1,391 @@
1
+ """Pipeline: ステージを順に呼び、各ステージの出力にゲートを掛けて分岐するだけの薄い物。
2
+
3
+ 並列・途中からの再開・スケジュールは持たない (オーケストレーターは作らない)。
4
+ ゲートを飛ばす引数は無い。通さずに進める時は `waive(ステージ, ゲート, 理由)` を書き、記録に必ず残る。
5
+ ゲートは機械的な点検を先に、採点役を後に掛ける (足した順にかかわらず)。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+ from typing import Any, Literal
15
+
16
+ from .calibration import advisory_reason
17
+ from .gate import Gate, GateBlocked
18
+ from .judge import Judge
19
+ from .ledger import Ledger, RunWriter
20
+ from .prices import PriceTable, UnknownModelError, Usage
21
+ from .providers import Completion, Provider
22
+ from .records import (
23
+ CalibrationRef,
24
+ CallRecord,
25
+ Finding,
26
+ GateRecord,
27
+ Judgment,
28
+ Reason,
29
+ StageRecord,
30
+ Verdict,
31
+ fingerprint,
32
+ )
33
+
34
+ StageFn = Callable[["StageContext", Any], Any]
35
+
36
+
37
+ @dataclass
38
+ class _Stage:
39
+ name: str
40
+ fn: StageFn
41
+ model: str | None
42
+ gates: list[Gate] = field(default_factory=list)
43
+ waivers: dict[str, str] = field(default_factory=dict)
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class RunResult:
48
+ run_id: str
49
+ status: str # ok / blocked
50
+ output: Any
51
+ verdicts: list[GateRecord]
52
+ cost: float # USD。料金表で計算できた呼び出しの合計
53
+
54
+
55
+ class RecordedLLM:
56
+ """`ctx.llm`。受け口を呼び、呼び出しを 1 件ずつ記録する薄い包み。"""
57
+
58
+ def __init__(self, ctx: StageContext, provider: Provider) -> None:
59
+ self._ctx = ctx
60
+ self._provider = provider
61
+
62
+ def complete(self, messages: list[dict[str, Any]], *, model: str | None = None, **kwargs: Any) -> Completion:
63
+ model = model or self._ctx.model
64
+ if model is None:
65
+ raise ValueError(
66
+ f"ステージ {self._ctx.stage!r} にモデルがありません。stage(model=...) か model= で渡してください"
67
+ )
68
+ self._ctx._prices.require(model) # 料金表に無いモデルは、払う前にエラー
69
+ started = time.perf_counter()
70
+ completion = self._provider.complete(model, messages, **kwargs)
71
+ self._ctx.record_call(
72
+ model=model,
73
+ served=completion.model_served,
74
+ usage=completion.usage,
75
+ latency_ms=_ms_since(started),
76
+ stop_reason=completion.stop_reason,
77
+ )
78
+ if completion.stop_reason == "refusal": # 記録を書いた後なので、払ったトークンは残る
79
+ raise RuntimeError(
80
+ f"ステージ {self._ctx.stage!r} の呼び出しが {completion.model_served} に断られました (stop_reason=refusal)。"
81
+ "本文は空です。依頼文を見直すか、振り替え (fallbacks) のあるモデルを使ってください"
82
+ )
83
+ return completion
84
+
85
+
86
+ class StageContext:
87
+ """ステージの関数が受け取る 1 つ目の引数。
88
+
89
+ - `llm`: 記録つきで LLM を呼ぶ口
90
+ - `record_call(...)`: 受け口を通さずに呼んだ LLM を手で記録する
91
+ - `attempt` / `reason`: 1 回目は initial、ゲートの指摘でやり直す 2 回目は repair
92
+ - `findings`: やり直しの時、落ちたゲートの指摘 ({"gate": 名前, "findings": [...]} の列)
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ *,
98
+ writer: RunWriter,
99
+ prices: PriceTable,
100
+ provider: Provider | None,
101
+ stage: str,
102
+ model: str | None,
103
+ attempt: int,
104
+ findings: list[dict[str, Any]],
105
+ ) -> None:
106
+ self._writer = writer
107
+ self._prices = prices
108
+ self._provider = provider
109
+ self.run_id = writer.run_id
110
+ self.stage = stage
111
+ self.model = model
112
+ self.attempt = attempt
113
+ self.findings = findings
114
+ self._gate: str | None = None # 採点役の呼び出しの時だけ、ゲートの名前
115
+ self._reason: Reason | None = None # 採点のし直し (rejudge) の時だけ
116
+
117
+ @property
118
+ def reason(self) -> Reason:
119
+ if self._reason is not None:
120
+ return self._reason
121
+ return "initial" if self.attempt == 1 else "repair"
122
+
123
+ @property
124
+ def llm(self) -> RecordedLLM:
125
+ if self._provider is None:
126
+ raise RuntimeError("Pipeline(llm=...) に受け口が渡されていません")
127
+ return RecordedLLM(self, self._provider)
128
+
129
+ def record_call(
130
+ self,
131
+ *,
132
+ model: str,
133
+ served: str,
134
+ usage: Usage,
135
+ latency_ms: int = 0,
136
+ stop_reason: str | None = None,
137
+ reason: Reason | None = None,
138
+ ) -> CallRecord:
139
+ """呼び出しを 1 件記録する。金額は応えたモデル (served) の単価で出す。
140
+
141
+ 応えたモデルが料金表に無い時は、金額を空 (None) にした記録を残してから UnknownModelError を投げる。
142
+ """
143
+ try:
144
+ cost: float | None = self._prices.cost(served, usage)
145
+ except UnknownModelError:
146
+ cost = None
147
+ record = CallRecord(
148
+ run_id=self.run_id,
149
+ stage=self.stage,
150
+ attempt=self.attempt,
151
+ reason=reason or self.reason,
152
+ model_requested=model,
153
+ model_served=served,
154
+ usage=usage,
155
+ cost_usd=cost,
156
+ latency_ms=latency_ms,
157
+ stop_reason=stop_reason,
158
+ gate=self._gate,
159
+ )
160
+ self._writer.write(record)
161
+ if cost is None:
162
+ raise UnknownModelError(served, self._prices.as_of)
163
+ return record
164
+
165
+
166
+ class Pipeline:
167
+ def __init__(
168
+ self,
169
+ name: str,
170
+ *,
171
+ ledger: Ledger,
172
+ prices: str | Path | PriceTable,
173
+ llm: Provider | None = None,
174
+ allow_panel_calibration: bool = False,
175
+ ) -> None:
176
+ self.name = name
177
+ self.ledger = ledger
178
+ # True の時だけ、モデルの合議のラベル (人のラベルでない) の校正でも採点役が止められる
179
+ self.allow_panel_calibration = allow_panel_calibration
180
+ self.prices = prices if isinstance(prices, PriceTable) else PriceTable.load(prices)
181
+ self.llm = llm
182
+ self._stages: dict[str, _Stage] = {}
183
+
184
+ def stage(self, name: str, *, model: str | None = None) -> Callable[[StageFn], StageFn]:
185
+ """ステージを足す飾り。モデルが料金表に無ければ、ここで (お金を使う前に) エラーにする。"""
186
+ if name in self._stages:
187
+ raise ValueError(f"ステージ {name!r} は既にあります")
188
+ if model is not None:
189
+ self.prices.require(model)
190
+
191
+ def register(fn: StageFn) -> StageFn:
192
+ self._stages[name] = _Stage(name, fn, model)
193
+ return fn
194
+
195
+ return register
196
+
197
+ def gate(self, stage: str, gate: Gate) -> None:
198
+ """ゲートを足す。採点役のモデルが料金表に無ければ、ここで (お金を使う前に) エラーにする。"""
199
+ st = self._stage(stage)
200
+ if any(g.name == gate.name for g in st.gates):
201
+ raise ValueError(f"ステージ {stage!r} にゲート {gate.name!r} は既にあります")
202
+ if isinstance(gate.check, Judge):
203
+ self.prices.require(gate.check.model)
204
+ st.gates.append(gate)
205
+ st.gates.sort(key=lambda g: isinstance(g.check, Judge)) # 機械的な点検を先に (同じ種類の中は足した順)
206
+
207
+ def waive(self, stage: str, gate: str, reason: str) -> None:
208
+ """ゲートを 1 つ、理由つきで通さずに進める。実行のたびに waived として記録に残る。"""
209
+ st = self._stage(stage)
210
+ if not any(g.name == gate for g in st.gates):
211
+ raise KeyError(f"ステージ {stage!r} にゲート {gate!r} がありません")
212
+ if not reason.strip():
213
+ raise ValueError("waive には理由が要ります")
214
+ st.waivers[gate] = reason
215
+
216
+ def run(self, input: Any) -> RunResult:
217
+ writer = self.ledger.open_run(self.name, self.prices)
218
+ verdicts: list[GateRecord] = []
219
+ value = input
220
+ try:
221
+ for st in self._stages.values():
222
+ value = self._run_stage(writer, st, value, verdicts)
223
+ except GateBlocked as e:
224
+ writer.end("blocked", error=str(e))
225
+ e.result = RunResult(writer.run_id, "blocked", None, verdicts, writer.cost_usd)
226
+ raise
227
+ except Exception as e:
228
+ writer.end("error", error=f"{type(e).__name__}: {e}")
229
+ raise
230
+ writer.end("ok")
231
+ return RunResult(writer.run_id, "ok", value, verdicts, writer.cost_usd)
232
+
233
+ def _stage(self, name: str) -> _Stage:
234
+ try:
235
+ return self._stages[name]
236
+ except KeyError:
237
+ raise KeyError(f"ステージ {name!r} がありません") from None
238
+
239
+ def _run_stage(self, writer: RunWriter, st: _Stage, stage_input: Any, verdicts: list[GateRecord]) -> Any:
240
+ output = self._attempt(writer, st, stage_input, attempt=1, findings=[])
241
+ failed = self._check(writer, st, output, stage_input, 1, verdicts)
242
+ to_repair = [{"gate": g.name, "findings": f} for g, f in failed if g.on_fail == "repair"]
243
+ if to_repair:
244
+ output = self._attempt(writer, st, stage_input, attempt=2, findings=to_repair)
245
+ self._check(writer, st, output, stage_input, 2, verdicts) # 残った指摘は記録して進む
246
+ return output
247
+
248
+ def _context(
249
+ self, writer: RunWriter, st: _Stage, model: str | None, attempt: int, findings: list[dict[str, Any]]
250
+ ) -> StageContext:
251
+ return StageContext(
252
+ writer=writer,
253
+ prices=self.prices,
254
+ provider=self.llm,
255
+ stage=st.name,
256
+ model=model,
257
+ attempt=attempt,
258
+ findings=findings,
259
+ )
260
+
261
+ def _attempt(
262
+ self, writer: RunWriter, st: _Stage, stage_input: Any, attempt: int, findings: list[dict[str, Any]]
263
+ ) -> Any:
264
+ ctx = self._context(writer, st, st.model, attempt, findings)
265
+ started = time.perf_counter()
266
+ input_fp = fingerprint(stage_input)
267
+
268
+ def stage_record(output_fp: str | None, status: Literal["ok", "error"]) -> StageRecord:
269
+ return StageRecord(
270
+ run_id=writer.run_id,
271
+ stage=st.name,
272
+ attempt=attempt,
273
+ model=st.model,
274
+ input_fp=input_fp,
275
+ output_fp=output_fp,
276
+ latency_ms=_ms_since(started),
277
+ status=status,
278
+ )
279
+
280
+ try:
281
+ output = st.fn(ctx, stage_input)
282
+ except Exception:
283
+ writer.write(stage_record(None, "error"))
284
+ raise
285
+ writer.write(stage_record(fingerprint(output), "ok"))
286
+ return output
287
+
288
+ def _check(
289
+ self, writer: RunWriter, st: _Stage, output: Any, stage_input: Any, attempt: int, verdicts: list[GateRecord]
290
+ ) -> list[tuple[Gate, list[Finding]]]:
291
+ """ゲートを機械的な点検・採点役の順に掛ける。block が止める権限つきで落ちたら、その場で止める。
292
+
293
+ 落ちて止めなかったゲート (repair・record・止める権限の無い採点役の block) を返す。
294
+ """
295
+ artifact_fp = fingerprint(output)
296
+ failed: list[tuple[Gate, list[Finding]]] = []
297
+ for g in st.gates:
298
+ waive_reason = st.waivers.get(g.name)
299
+ findings: list[Finding] = []
300
+ verdict: Verdict = "waived"
301
+ judgment: Judgment | None = None
302
+ if waive_reason is None:
303
+ if isinstance(g.check, Judge):
304
+ ok, findings, judgment = self._judge(writer, st, g, g.check, output, stage_input, attempt)
305
+ else:
306
+ ok, findings = g.evaluate(output, stage_input)
307
+ verdict = "pass" if ok else "fail"
308
+ record = GateRecord(
309
+ run_id=writer.run_id,
310
+ stage=st.name,
311
+ gate=g.name,
312
+ on_fail=g.on_fail,
313
+ attempt=attempt,
314
+ artifact_fp=artifact_fp,
315
+ verdict=verdict,
316
+ findings=findings,
317
+ waive_reason=waive_reason,
318
+ judge=judgment,
319
+ )
320
+ writer.write(record)
321
+ verdicts.append(record)
322
+ if record.verdict == "fail":
323
+ if g.on_fail == "block" and (judgment is None or judgment.can_block):
324
+ raise GateBlocked(st.name, g.name, record.findings)
325
+ failed.append((g, record.findings))
326
+ return failed
327
+
328
+ def _judge(
329
+ self, writer: RunWriter, st: _Stage, g: Gate, judge: Judge, output: Any, stage_input: Any, attempt: int
330
+ ) -> tuple[bool, list[Finding], Judgment | None]:
331
+ """採点役のゲートを評価する。同じ見せた物と基準の版の判定があれば、払わずに再利用する。
332
+
333
+ - view が None を返したら、見せる物が無い (主張が無い回答など)。採点せず (払わず) 合格にし、判定は残さない。
334
+
335
+ - 止める根拠に使える判定 (校正済み・頼んだモデルが応えた) を先に選ぶ。
336
+ - block のゲートで、前の判定が参考扱いしか無く、頼むモデルが校正済みなら、採点し直す (rejudge)。
337
+ 頼むモデルも校正していなければ、採点し直しても参考扱いのままなので、前の判定を使う。
338
+ """
339
+ rubric = judge.rubric.id
340
+ shown = judge.view(output, stage_input)
341
+ if shown is None:
342
+ return True, [], None
343
+ judged_fp = fingerprint(shown)
344
+
345
+ def why_advisory(requested: str, served: str) -> str | None:
346
+ cal = self.ledger.calibration(rubric, served)
347
+ return advisory_reason(cal, requested, served, self.allow_panel_calibration)
348
+
349
+ def snapshot(served: str) -> CalibrationRef | None:
350
+ cal = self.ledger.calibration(rubric, served)
351
+ return cal.ref() if cal else None
352
+
353
+ past = [r for r in self.ledger.judgments(rubric, judged_fp=judged_fp) if r.judge is not None]
354
+ usable = [r for r in past if r.judge and why_advisory(r.judge.model_requested, r.judge.model_served) is None]
355
+ source = usable[0] if usable else (past[0] if past else None)
356
+ wants_authority = g.on_fail == "block" and why_advisory(judge.model, judge.model) is None
357
+ if source is not None and source.judge is not None and (usable or not wants_authority):
358
+ j = source.judge
359
+ reused = j.model_copy(
360
+ update={
361
+ "cost_usd": 0.0,
362
+ "reused_from": source.run_id,
363
+ "saved_usd": j.cost_usd,
364
+ "calibration": snapshot(j.model_served),
365
+ "advisory_reason": why_advisory(j.model_requested, j.model_served),
366
+ }
367
+ )
368
+ return source.verdict == "pass", list(source.findings), reused
369
+
370
+ ctx = self._context(writer, st, judge.model, attempt, [])
371
+ ctx._gate = g.name
372
+ if source is not None:
373
+ ctx._reason = "rejudge"
374
+ completion = ctx.llm.complete(judge.messages(shown), system=judge.rubric.text)
375
+ reply = judge.parse(completion.text, completion.model_served)
376
+ served = completion.model_served
377
+ judgment = Judgment(
378
+ rubric=rubric,
379
+ judged_fp=judged_fp,
380
+ model_requested=judge.model,
381
+ model_served=served,
382
+ score=reply.score,
383
+ cost_usd=self.prices.cost(served, completion.usage),
384
+ calibration=snapshot(served),
385
+ advisory_reason=why_advisory(judge.model, served),
386
+ )
387
+ return reply.verdict == "pass", list(reply.findings), judgment
388
+
389
+
390
+ def _ms_since(started: float) -> int:
391
+ return round((time.perf_counter() - started) * 1000)
@@ -0,0 +1,68 @@
1
+ # Claude の一次の API (Anthropic) の料金。単位は 100 万トークンあたりの USD。
2
+ # 出典: Anthropic の料金表 (2026-11-03 時点)。入力・出力・キャッシュ読みは表の値。
3
+ # キャッシュ書き込みは 5 分キャッシュの値 (入力の 1.25 倍) を倍率から計算した。
4
+ # Haiku 5.5 のキャッシュ読みは表に値が無いため、入力の 0.1 倍を倍率から計算した。
5
+ # Amazon Bedrock・Vertex AI の料金は別建てで、この表には入れていない。
6
+ as_of = "2026-11-03"
7
+ source = "Anthropic API pricing (first-party), 2026-11-03"
8
+
9
+ [models."claude-opus-5-5"]
10
+ input = 4.00
11
+ output = 20.00
12
+ cache_read = 0.20
13
+ cache_write = 5.00
14
+
15
+ [models."claude-sonnet-5-5"]
16
+ input = 2.00
17
+ output = 10.00
18
+ cache_read = 0.10
19
+ cache_write = 2.50
20
+
21
+ [models."claude-haiku-5-5"]
22
+ input = 0.10
23
+ output = 0.50
24
+ cache_read = 0.01
25
+ cache_write = 0.125
26
+
27
+ # Haiku 5.5 はプロンプトが 10 万トークンを超えると単価が上がる (入力 $0.50 / 出力 $2.50)。
28
+ # キャッシュの 2 つは上と同じ倍率で計算した。
29
+ [models."claude-haiku-5-5".long]
30
+ above_prompt_tokens = 100_000
31
+ input = 0.50
32
+ output = 2.50
33
+ cache_read = 0.05
34
+ cache_write = 0.625
35
+
36
+ # 前の世代。サーバー側の振り替え (fallbacks) で応えることがあるので入れておく。
37
+ # Opus 5.5・Fable 5.2 の既定 ("default") の振り替え先は Opus 4.8 と Opus 5 (サイバーの分類で断られた時は Opus 4.8)。
38
+ # Opus 5・Sonnet 5・Opus 4.8 のキャッシュ読みは入力の 0.1 倍、キャッシュ書き込みは入力の 1.25 倍を倍率から計算した。
39
+ [models."claude-opus-5"]
40
+ input = 5.00
41
+ output = 25.00
42
+ cache_read = 0.50
43
+ cache_write = 6.25
44
+
45
+ [models."claude-sonnet-5"]
46
+ input = 2.00
47
+ output = 10.00
48
+ cache_read = 0.20
49
+ cache_write = 2.50
50
+
51
+ [models."claude-fable-5-2"]
52
+ input = 8.00
53
+ output = 40.00
54
+ cache_read = 0.20
55
+ cache_write = 10.00
56
+
57
+ # Fable 5.1 のキャッシュ読みは表の値 (入力の 0.025 倍)。
58
+ [models."claude-fable-5-1"]
59
+ input = 10.00
60
+ output = 50.00
61
+ cache_read = 0.25
62
+ cache_write = 12.50
63
+
64
+ [models."claude-opus-4-8"]
65
+ input = 5.00
66
+ output = 25.00
67
+ cache_read = 0.50
68
+ cache_write = 6.25
@@ -0,0 +1 @@
1
+ """同梱の料金表 (TOML) の置き場。"""
gateledger/prices.py ADDED
@@ -0,0 +1,108 @@
1
+ """日付つきの料金表から、1 回の呼び出しの金額を出す。
2
+
3
+ 決まり: 料金表に無いモデルはエラーにする。0 円として記録すると費用が見えなくなるため。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import tomllib
9
+ from importlib import resources
10
+ from pathlib import Path
11
+
12
+ from pydantic import BaseModel, ConfigDict, NonNegativeInt
13
+
14
+ _PER_TOKEN = 1 / 1_000_000 # 料金表の単価は 100 万トークンあたり
15
+
16
+
17
+ class UnknownModelError(LookupError):
18
+ """料金表に無いモデルで料金を出そうとした。"""
19
+
20
+ def __init__(self, model: str, as_of: str) -> None:
21
+ super().__init__(f"料金表 ({as_of}) に {model!r} がありません。料金表に足してから呼んでください")
22
+ self.model = model
23
+
24
+
25
+ class Usage(BaseModel):
26
+ """1 回の呼び出しのトークン数。"""
27
+
28
+ model_config = ConfigDict(frozen=True, extra="forbid")
29
+
30
+ input: NonNegativeInt = 0
31
+ output: NonNegativeInt = 0
32
+ cache_read: NonNegativeInt = 0
33
+ cache_write: NonNegativeInt = 0
34
+
35
+ @property
36
+ def prompt(self) -> int:
37
+ """プロンプト側の合計 (キャッシュの読み書きを含む)。"""
38
+ return self.input + self.cache_read + self.cache_write
39
+
40
+ def __add__(self, other: Usage) -> Usage:
41
+ return Usage(
42
+ input=self.input + other.input,
43
+ output=self.output + other.output,
44
+ cache_read=self.cache_read + other.cache_read,
45
+ cache_write=self.cache_write + other.cache_write,
46
+ )
47
+
48
+
49
+ class _Rates(BaseModel):
50
+ model_config = ConfigDict(extra="forbid")
51
+
52
+ input: float
53
+ output: float
54
+ cache_read: float
55
+ cache_write: float
56
+
57
+ def cost(self, usage: Usage) -> float:
58
+ return _PER_TOKEN * (
59
+ usage.input * self.input
60
+ + usage.output * self.output
61
+ + usage.cache_read * self.cache_read
62
+ + usage.cache_write * self.cache_write
63
+ )
64
+
65
+
66
+ class _LongRates(_Rates):
67
+ above_prompt_tokens: int
68
+
69
+
70
+ class ModelPrice(_Rates):
71
+ """1 モデルの単価。長いプロンプトで単価が上がるモデルは `long` を持つ。"""
72
+
73
+ long: _LongRates | None = None
74
+
75
+ def cost(self, usage: Usage) -> float:
76
+ if self.long is not None and usage.prompt > self.long.above_prompt_tokens:
77
+ return self.long.cost(usage)
78
+ return super().cost(usage)
79
+
80
+
81
+ class PriceTable(BaseModel):
82
+ """日付つきの料金表。`as_of` は記録に残り、どの料金で計算したかが後から分かる。"""
83
+
84
+ model_config = ConfigDict(extra="forbid", frozen=True)
85
+
86
+ as_of: str
87
+ source: str = ""
88
+ models: dict[str, ModelPrice]
89
+
90
+ @classmethod
91
+ def load(cls, path: str | Path) -> PriceTable:
92
+ with open(path, "rb") as f:
93
+ return cls.model_validate(tomllib.load(f))
94
+
95
+ @classmethod
96
+ def bundled(cls, name: str = "2026-11") -> PriceTable:
97
+ """パッケージに同梱した料金表を読む。"""
98
+ data = resources.files("gateledger.price_tables").joinpath(f"{name}.toml").read_bytes()
99
+ return cls.model_validate(tomllib.loads(data.decode("utf-8")))
100
+
101
+ def require(self, model: str) -> ModelPrice:
102
+ try:
103
+ return self.models[model]
104
+ except KeyError:
105
+ raise UnknownModelError(model, self.as_of) from None
106
+
107
+ def cost(self, model: str, usage: Usage) -> float:
108
+ return self.require(model).cost(usage)
@@ -0,0 +1,105 @@
1
+ """LLM の受け口。ライブラリが知る必要があるのは、応えたモデルとトークン数だけ。
2
+
3
+ 実装は 2 つ:
4
+ - FakeProvider: 決まった応答を順に返す (テストとデモ用)
5
+ - AnthropicProvider: Anthropic の Python SDK で呼ぶ (`pip install gateledger[anthropic]`)
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterable
11
+ from dataclasses import dataclass
12
+ from typing import Any, Protocol
13
+
14
+ from pydantic import BaseModel, Field
15
+
16
+ from .prices import Usage
17
+
18
+
19
+ class Completion(BaseModel):
20
+ text: str
21
+ model_served: str # 応答の側に書いてあったモデル。頼んだモデルと違うことがある
22
+ usage: Usage
23
+ stop_reason: str | None = None
24
+ raw: Any = Field(default=None, exclude=True, repr=False)
25
+
26
+
27
+ class Provider(Protocol):
28
+ def complete(self, model: str, messages: list[dict[str, Any]], **kwargs: Any) -> Completion: ...
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class FakeReply:
33
+ text: str
34
+ usage: Usage
35
+ served: str | None = None # None なら頼んだモデルが応えたことにする
36
+ stop_reason: str = "end_turn"
37
+
38
+
39
+ class FakeProvider:
40
+ """渡した応答を、呼ばれた順に 1 つずつ返す。受けた依頼は `requests` に残る。"""
41
+
42
+ def __init__(self, replies: Iterable[FakeReply]) -> None:
43
+ self._replies = list(replies)
44
+ self.requests: list[dict[str, Any]] = []
45
+
46
+ def complete(self, model: str, messages: list[dict[str, Any]], **kwargs: Any) -> Completion:
47
+ if len(self.requests) >= len(self._replies):
48
+ raise RuntimeError(f"FakeProvider の応答を使い切りました ({len(self._replies)} 件)")
49
+ reply = self._replies[len(self.requests)]
50
+ self.requests.append({"model": model, "messages": messages, **kwargs})
51
+ return Completion(
52
+ text=reply.text, model_served=reply.served or model, usage=reply.usage, stop_reason=reply.stop_reason
53
+ )
54
+
55
+
56
+ # 安全の判定で断られた時に、サーバー側で別のモデルへ振り替えられるモデル (2026-11 の SDK の説明による)
57
+ _SERVER_FALLBACK_MODELS = frozenset(
58
+ {"claude-fable-5-2", "claude-fable-5-1", "claude-opus-5-5", "claude-opus-5", "claude-sonnet-5-5"}
59
+ )
60
+ _FALLBACK_BETA = "server-side-fallback-2026-07-01"
61
+
62
+
63
+ class AnthropicProvider:
64
+ """Anthropic の Messages API で呼ぶ。
65
+
66
+ `fallbacks` (既定 "default") は、安全の判定で断られた時にサーバー側で別のモデルへ振り替える設定。
67
+ 振り替えが起きると、応答の `model` が頼んだモデルと違う値になり、そのまま記録に残る。
68
+ 注意: 振り替えの前に途中まで出た分は元のモデルの単価で請求されるが、ここでは応答の合計の
69
+ トークンを応えたモデルの単価で計算する (週 1 の範囲の近似)。振り替えを使わない時は None を渡す。
70
+ """
71
+
72
+ def __init__(
73
+ self, client: Any = None, *, max_tokens: int = 16_000, fallbacks: str | list[dict[str, Any]] | None = "default"
74
+ ) -> None:
75
+ if client is None:
76
+ try:
77
+ import anthropic
78
+ except ImportError as e:
79
+ raise ImportError("AnthropicProvider には `pip install gateledger[anthropic]` が要ります") from e
80
+ client = anthropic.Anthropic() # 鍵は環境 (ANTHROPIC_API_KEY など) から SDK が読む
81
+ self.client = client
82
+ self.max_tokens = max_tokens
83
+ self.fallbacks = fallbacks
84
+
85
+ def complete(self, model: str, messages: list[dict[str, Any]], **kwargs: Any) -> Completion:
86
+ kwargs.setdefault("max_tokens", self.max_tokens)
87
+ if self.fallbacks is not None and model in _SERVER_FALLBACK_MODELS:
88
+ resp = self.client.beta.messages.create(
89
+ model=model, messages=messages, betas=[_FALLBACK_BETA], fallbacks=self.fallbacks, **kwargs
90
+ )
91
+ else:
92
+ resp = self.client.messages.create(model=model, messages=messages, **kwargs)
93
+ u = resp.usage
94
+ return Completion(
95
+ text="".join(block.text for block in resp.content if block.type == "text"),
96
+ model_served=resp.model,
97
+ usage=Usage(
98
+ input=u.input_tokens,
99
+ output=u.output_tokens,
100
+ cache_read=u.cache_read_input_tokens or 0,
101
+ cache_write=u.cache_creation_input_tokens or 0,
102
+ ),
103
+ stop_reason=resp.stop_reason,
104
+ raw=resp,
105
+ )
gateledger/py.typed ADDED
File without changes