Repository navigation
feat: add opt-in agent run details section (model, tokens, time, AI calls) - #2587
Conversation
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…rove Co-authored-by: Cursor <cursoragent@cursor.com>
Replace the helper-based self-test with assertions against the real review, description, and improve output paths so the tests fail if any production insertion is removed. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Count successful OpenAI and LangChain completions in run metadata, and move fallback-model telemetry into the success-only else branch. This keeps AI call counts visible across handlers and prevents telemetry from triggering a fallback retry path. Co-authored-by: Cursor <cursoragent@cursor.com>
Lock in ContextVar accumulation and isolation under asyncio.gather, assert the renderer omits zero AI calls and formats time cost with one decimal, and share one test fixture for run-metadata isolation. Co-authored-by: Cursor <cursoragent@cursor.com>
Document that /improve only appends run metadata when it publishes a summary comment, and that repeated /describe runs with description markers accumulate blocks because the existing description is preserved. Co-authored-by: Cursor <cursoragent@cursor.com>
Count langchain calls without token usage: it reports input_tokens/ output_tokens, which the collector does not read, so passing it through rendered a misleading "0 in / 0 out" line instead of omitting tokens. Move the langchain import to module level to match the other handlers, and place the openai import in isort order within its group. The rest of each file's import disorder predates this branch and is left untouched. Co-authored-by: Cursor <cursoragent@cursor.com>
/improve was a confusing choice for the example command, since the notes right below it explain when /improve omits the section. Co-authored-by: Cursor <cursoragent@cursor.com>
"Metadata" reads as data about the PR, but what the section reports is how this particular run went: which model answered, tokens spent, wall time, and how many LLM calls it took. Rename the user-visible surface -- section title "Agent run details" and the config flag output_run_details -- and carry the same name through the module, dataclass, helpers, ContextVar and tests, so the feature does not end up half renamed. The anchor in changing_a_model.md moves with the docs heading; _record_completion_metadata in the litellm handler deliberately keeps its name, since it reads metadata off a completion response, which is a different and accurate use of the word. Co-authored-by: Cursor <cursoragent@cursor.com>
Mutation testing survived two breakages, meaning nothing guarded them. Nothing covered chat_completion actually calling the recorder, so the default handler could stop counting and every figure would silently read zero; drive the real method with a stubbed _get_completion, and also pin that a failed call is not counted (fallback runs would otherwise inflate the totals) and that concurrent calls accumulate, which is how /improve fans out its chunks. The reviewer test built the tool by hand and called _prepare_pr_review directly, skipping run() and therefore init_run_details(). Drive run() like the describe and improve tests do, and seed through the tool's own init hook, so removing that call makes the section unrenderable and the test red. Co-authored-by: Cursor <cursoragent@cursor.com>
PR Summary by QodoAdd opt-in agent run details section (model/tokens/time/AI calls) to PR outputs
AI Description
Diagram
High-Level Assessment
Files changed (19)
|
Code Review by Qodo
1. Time cost not AI-only
|
PR Reviewer Guide 🔍(Review updated until commit f09e51d)Here are some key observations to aid the review process:
⚙️ Agent run details
|
CodeQL flagged the fixture import in six test files as an unused import, which it is: the name is never referenced, it only has to exist in the module namespace for pytest to register the autouse fixture. That is what conftest.py is for, so define the fixture there and drop both the helper module and the six imports. The fixture now applies to every test under tests/unittest, which costs a ContextVar set and reset per test and keeps future tests from leaking run details as well. Also pass _FakeSettings directly instead of wrapping it in a zero-argument lambda, which CodeQL flagged separately. Co-authored-by: Cursor <cursoragent@cursor.com>
A provider that reports only total_tokens rendered as "0 in / 0 out / N total", claiming two figures it had never sent. Build the line from the components that are actually present instead. Zero is a safe stand-in for absent here: these are cumulative counters, so any component still at zero after a successful call means nothing was reported for it. That avoids threading Optional or seen-flags through the collector for a distinction that cannot arise. Co-authored-by: Cursor <cursoragent@cursor.com>
"Langchain does expose usage, only under its own key names" was read by a reviewer as a sentence missing a "not". Say plainly that langchain reports usage under key names the collector does not read, which is what makes forwarding it render zeros. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Persistent review updated to latest commit f09e51d |
|
Code review by qodo was updated up to the latest commit f09e51d |
|
Both bot findings look unreachable, in case it saves a rewrite.
ContextVar is the right choice and the docstring explains why — shared by reference into child tasks, so the gather aggregates while concurrent requests stay isolated. |
|
@naorpeled |
|
Hey @victorljii, |
# Conflicts: # pr_agent/tools/pr_reviewer.py
|
Code review by qodo was updated up to the latest commit dec08f8 |
done @naorpeled |
The review-coverage footer reads self.remaining_files_list, which is normally set in _prepare_prediction. Since the wiring test mocks out retry_with_fallback_models, that attribute was never assigned and run() raised AttributeError before storing the artifact. Seed it explicitly in the hand-built PRReviewer object. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Code review by qodo was updated up to the latest commit b47467d |
|
Thanks @victorljii ! |
|
@victorljii Thanks a lot for working on this — having the actual model, token usage, timing, and AI call count available in the output is really useful! One small thought: for models/providers that expose it, would it also make sense to collect and optionally show I think it could be particularly useful for reasoning models, where the visible output tokens alone may not tell the whole story about token usage/cost. Thanks again for the great work! |
@edwinyoo44 Just for context: on providers like OpenAI, reasoning tokens are already included in Would this be what you had in mind? The parenthetical would only appear when the provider reports |
@victorljii Yes, exactly — this looks great. Thanks! |
… run-details collector Two changes prompted by review feedback on The-PR-Agent#2532: - dict(data) is shallow, so structured_data["review"] aliased data["review"], which _prepare_pr_review mutates right after the hook fires. Harmless for PlainDiffGitProvider (serializes immediately) but the hook is provider-neutral, so publish a deep-copied snapshot instead. Caught by @IsmaelMartinez. - Drop the handler-side last_usage capture entirely. The-PR-Agent#2587 (merged) already accumulates per-call token usage in the ContextVar-backed run-details collector; keeping a second capture path would drift. The structured publisher now reads prompt/completion/total tokens from get_run_details(), which also means multi-call runs report the full accumulated usage rather than only the last call's. Suggested by @IsmaelMartinez. Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
… run-details collector Two changes prompted by review feedback on The-PR-Agent#2532: - dict(data) is shallow, so structured_data["review"] aliased data["review"], which _prepare_pr_review mutates right after the hook fires. Harmless for PlainDiffGitProvider (serializes immediately) but the hook is provider-neutral, so publish a deep-copied snapshot instead. Caught by @IsmaelMartinez. - Drop the handler-side last_usage capture entirely. The-PR-Agent#2587 (merged) already accumulates per-call token usage in the ContextVar-backed run-details collector; keeping a second capture path would drift. The structured publisher now reads prompt/completion/total tokens from get_run_details(), which also means multi-call runs report the full accumulated usage rather than only the last call's. Suggested by @IsmaelMartinez. Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
Summary
/review,/describeand/improvecan optionally append a short sectionreporting how the run went: which model answered (and whether it was a fallback),
tokens consumed, time taken, and how many LLM calls it made. Off by default,
enabled with
config.output_run_details.What it looks like
A collapsible
<details>block where GFM is supported, matching the existing🛠️ Relevant configurationssection, and the same lines as plain text elsewhere.Fields the provider does not report are omitted rather than shown as zero.
How it works
A new
pr_agent/algo/run_details.pyholds aRunDetailsdataclass in aContextVar:init_run_details()at the top ofrun(), installing a freshcollector for that run.
retry_with_fallback_modelsrecords the model that produced the successfulprediction, marked as a fallback when it was not the first attempt.
the provider reports one. Parallel calls, such as
/improve's chunks,accumulate into the same collector.
show_run_details()renders the section, and the three tools append it whenthe flag is on.
Caveats
/improveappends the section only when it publishes a summary comment, not withcommitable_code_suggestions. Withuse_description_markers=true, repeated/describeruns accumulate one block per run. Streaming responses and thelangchain handler do not expose usage in a form the collector reads, so the
Tokensline is omitted there while the call itself is still counted.Tests
34 new unit tests covering the collector, the fallback recording, both AI
handlers, the renderer, and the wiring into all three tools. The wiring tests
drive each tool's real
run()with the git provider stubbed, so they fail if theproduction call sites disappear.
Docs
a new section in
usage-guide/additional_configurations.md, cross-referencedfrom
changing_a_model.md. No new dependencies.Closes #2514