mirror of
https://github.com/PX4/PX4-Autopilot.git
synced 2026-11-28 19:21:03 +08:00
feat(ci): show the cost of each AI review on the PR
The review footer now ends with the run's cost, model, number of model calls and wall time, for example "Cost: $7.42 · Claude Opus 5.5 · 12 model call(s) · 22 min"; a refusal notice shows what was spent before the refusal. The cost is Claude Code's own estimate at list prices, which matched a recomputation from token counts on Bedrock. Making the price visible on every review also discourages casual re-runs. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Ramon Roche <mrpollo@gmail.com>
This commit is contained in:
1 parent
87f6f9e9d8
commit
1ca4506927
3 files changed
+68
-11
No files matched your search
@@ -9,6 +9,7 @@ import dataclasses
|
||||
import fnmatch
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
@@ -149,7 +150,8 @@ def run(s: Settings) -> Dict[str, Any]:
|
||||
"""Run the whole pipeline. Returns the report data it also writes."""
|
||||
s.work_dir.mkdir(parents=True, exist_ok=True)
|
||||
pr = context.gather(s.repo, s.pr_number)
|
||||
usage: Dict[str, Any] = {'changed_lines': pr.changed_lines}
|
||||
usage: Dict[str, Any] = {'changed_lines': pr.changed_lines,
|
||||
'started': time.monotonic()}
|
||||
|
||||
# Every PR is reviewed regardless of size; only one made entirely of
|
||||
# generated files (lock files, translations) has nothing to review.
|
||||
@@ -193,6 +195,12 @@ def run(s: Settings) -> Dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def _stamp_wall_time(usage: Dict[str, Any]) -> None:
|
||||
started = usage.pop('started', None)
|
||||
if isinstance(started, float):
|
||||
usage['wall_seconds'] = round(time.monotonic() - started, 1)
|
||||
|
||||
|
||||
def refused(s: Settings, pr: context.PrContext, e: agent.AgentRefusal,
|
||||
usage: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""The reviewer model declined: no review, and say exactly why.
|
||||
@@ -203,8 +211,9 @@ def refused(s: Settings, pr: context.PrContext, e: agent.AgentRefusal,
|
||||
"""
|
||||
usage['refused'] = {'model': e.model, 'category': e.category,
|
||||
'request_id': e.request_id}
|
||||
_stamp_wall_time(usage)
|
||||
artifact = render.write_refusal(s.out_dir, pr.number, pr.head_sha, e,
|
||||
s.model_label)
|
||||
s.model_label, usage)
|
||||
report = render.refusal_report(e, artifact, usage)
|
||||
(s.work_dir / 'report.md').write_text(report, encoding='utf-8')
|
||||
(s.work_dir / 'usage.json').write_text(json.dumps(usage, indent=2))
|
||||
@@ -240,8 +249,10 @@ def finish(s: Settings, pr_number: int, head_sha: str, diff_text: str,
|
||||
head_files = route.load_head_files(
|
||||
s.checkout, sorted({f.path for f, _ in pairs if f.path}))
|
||||
routed = route.route(pairs, diff_map, head_files)
|
||||
_stamp_wall_time(usage)
|
||||
artifact = render.write_artifact(s.out_dir, pr_number, head_sha, routed,
|
||||
model_summary, s.model_label, checklist)
|
||||
model_summary, s.model_label, checklist,
|
||||
usage)
|
||||
usage.update(sandbox_stats(s.work_dir / SANDBOX_LOG))
|
||||
report = render.report_markdown(routed, artifact, usage, checklist)
|
||||
(s.work_dir / 'report.md').write_text(report, encoding='utf-8')
|
||||
|
||||
@@ -87,8 +87,25 @@ def checklist_line(checklist: Dict[str, ChecklistEntry]) -> str:
|
||||
return ' · '.join(cells)
|
||||
|
||||
|
||||
def cost_line(usage: Optional[Dict[str, Any]], model_name: str) -> str:
|
||||
"""'Cost: $1.23 · Claude Opus 5.5 · 4 model calls · 7 min'.
|
||||
|
||||
Claude Code's own estimate at list prices; on Bedrock it matched a
|
||||
recomputation from token counts to the cent.
|
||||
"""
|
||||
if not usage or 'cost_usd' not in usage:
|
||||
return ''
|
||||
parts = [f'Cost: ${usage["cost_usd"]:.2f}', model_name,
|
||||
f'{usage.get("calls", 0)} model call(s)']
|
||||
seconds = usage.get('wall_seconds')
|
||||
if isinstance(seconds, (int, float)):
|
||||
parts.append(f'{max(1, round(seconds / 60))} min')
|
||||
return ' · '.join(parts)
|
||||
|
||||
|
||||
def summary(routed: Routed, model_summary: str, model_name: str,
|
||||
checklist: Optional[Dict[str, ChecklistEntry]] = None) -> str:
|
||||
checklist: Optional[Dict[str, ChecklistEntry]] = None,
|
||||
usage: Optional[Dict[str, Any]] = None) -> str:
|
||||
parts = [f'**Automated review** ({model_name}): {routed.verdict}.']
|
||||
if model_summary.strip():
|
||||
parts += ['', model_summary.strip()]
|
||||
@@ -103,9 +120,11 @@ def summary(routed: Routed, model_summary: str, model_name: str,
|
||||
f'<summary>{len(routed.collapsed)} more finding(s) '
|
||||
'worth checking (lower confidence or outside the '
|
||||
'diff)</summary>', '', items, '', '</details>']
|
||||
cost = cost_line(usage, model_name)
|
||||
parts += ['', f'<sub>Written by an AI model and checked by a second, '
|
||||
f'independent pass. It can be wrong; maintainers decide. '
|
||||
f'[How this review works]({README_URL})</sub>']
|
||||
f'[How this review works]({README_URL})'
|
||||
+ (f'<br>{cost}' if cost else '') + '</sub>']
|
||||
text = '\n'.join(parts)
|
||||
if len(text.encode('utf-8')) > SUMMARY_LIMIT:
|
||||
text = text.encode('utf-8')[:SUMMARY_LIMIT - 200].decode(
|
||||
@@ -127,7 +146,8 @@ def find_leaks(texts: Iterable[str], secrets: Iterable[str]) -> List[str]:
|
||||
|
||||
def write_artifact(out_dir: Path, pr_number: int, commit_sha: str,
|
||||
routed: Routed, model_summary: str, model_name: str,
|
||||
checklist: Optional[Dict[str, ChecklistEntry]] = None
|
||||
checklist: Optional[Dict[str, ChecklistEntry]] = None,
|
||||
usage: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
manifest = {
|
||||
@@ -135,7 +155,8 @@ def write_artifact(out_dir: Path, pr_number: int, commit_sha: str,
|
||||
'marker': MARKER,
|
||||
'event': 'COMMENT',
|
||||
'commit_sha': commit_sha,
|
||||
'summary': summary(routed, model_summary, model_name, checklist),
|
||||
'summary': summary(routed, model_summary, model_name, checklist,
|
||||
usage),
|
||||
# a review with only a summary is still a review; and each run
|
||||
# replaces the previous one instead of piling up
|
||||
'post_without_comments': True,
|
||||
@@ -147,7 +168,8 @@ def write_artifact(out_dir: Path, pr_number: int, commit_sha: str,
|
||||
return {'manifest': manifest, 'comments': body}
|
||||
|
||||
|
||||
def refusal_summary(e: Any, model_name: str) -> str:
|
||||
def refusal_summary(e: Any, model_name: str,
|
||||
usage: Optional[Dict[str, Any]] = None) -> str:
|
||||
"""Review body when the model declined: not a review, with the reason.
|
||||
|
||||
The reason is the model provider's own text, passed through verbatim
|
||||
@@ -163,19 +185,22 @@ def refusal_summary(e: Any, model_name: str) -> str:
|
||||
'This is usually a false positive from the provider\'s safety '
|
||||
'classifier, not a judgement about the PR. A maintainer can '
|
||||
're-run the review or review it by hand.', '',
|
||||
f'<sub>[How this review works]({README_URL})</sub>']
|
||||
f'<sub>[How this review works]({README_URL})'
|
||||
+ (f'<br>{cost_line(usage, model_name)}'
|
||||
if cost_line(usage, model_name) else '') + '</sub>']
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def write_refusal(out_dir: Path, pr_number: int, commit_sha: str, e: Any,
|
||||
model_name: str) -> Dict[str, Any]:
|
||||
model_name: str,
|
||||
usage: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
manifest = {
|
||||
'pr_number': pr_number,
|
||||
'marker': MARKER,
|
||||
'event': 'COMMENT',
|
||||
'commit_sha': commit_sha,
|
||||
'summary': refusal_summary(e, model_name),
|
||||
'summary': refusal_summary(e, model_name, usage),
|
||||
# the notice must reach the PR even though there are no findings
|
||||
'post_without_comments': True,
|
||||
'supersede_previous': True,
|
||||
|
||||
@@ -78,6 +78,27 @@ class TestRender(unittest.TestCase):
|
||||
self.assertEqual(len(comments), 1)
|
||||
|
||||
|
||||
class TestCostLine(unittest.TestCase):
|
||||
|
||||
def test_cost_in_review_footer(self) -> None:
|
||||
usage = {'cost_usd': 7.4239, 'calls': 12, 'wall_seconds': 1290.0}
|
||||
text = render.summary(route.Routed(), '', 'Claude Opus 5.5',
|
||||
usage=usage)
|
||||
self.assertIn('Cost: $7.42 · Claude Opus 5.5 · 12 model call(s) · '
|
||||
'22 min', text)
|
||||
|
||||
def test_no_usage_no_cost_line(self) -> None:
|
||||
self.assertEqual(render.cost_line(None, 'm'), '')
|
||||
self.assertNotIn('Cost:', render.summary(route.Routed(), '', 'm'))
|
||||
|
||||
def test_refusal_shows_what_was_spent(self) -> None:
|
||||
from ai_review import agent
|
||||
e = agent.AgentRefusal('m', 'declined', 'cyber', 'req')
|
||||
text = render.refusal_summary(e, 'm', {'cost_usd': 0.01,
|
||||
'calls': 0})
|
||||
self.assertIn('Cost: $0.01', text)
|
||||
|
||||
|
||||
class TestLeaks(unittest.TestCase):
|
||||
|
||||
def test_detects_secret(self) -> None:
|
||||
|
||||
Reference in new issue
Block a user