Skip to content

feat(agent,model): universal forced tool calling for Light, 1-retry & validation - #806

Open
Razor573 wants to merge 8 commits into
wangzan101:mainfrom
Razor573:pr/light-forced-tool-calling
Open

Razor573 wants to merge 8 commits into
wangzan101:mainfrom
Razor573:pr/light-forced-tool-calling

Conversation

@Razor573

Copy link
Copy Markdown
Contributor

Summary

Implements universal forced tool calling for Light-role steps across all upstream model adapters, with a 200-token Light output cap, single-line no-tool retry, permissive tool-call validation (LightCallValidator), upfront Main routing, and Light rejection telemetry/metrics.

What's included

  • Per-call forced tool options (ChatModel.kt): Added CallOptions (LIGHT_TOOL_ONLY, LIGHT_MAX_OUTPUT_TOKENS = 200) and LightPrompt (tool-call-only system instruction + 1-line retry reminder).
  • Provider adapter support:
    • GeminiModel: sends tool_config.function_calling_config.mode = "ANY" and generationConfig.maxOutputTokens when forced.
    • OpenAiCompatModel: sends tool_choice = "required" and max_tokens (only on forced Light calls via ProviderStore), with 400/422 graceful fallback stripping unsupported tool_choice/max_tokens.
    • ResponsesModel: sends tool_choice = "required" and max_output_tokens (skipped for ChatGPT plan, only on forced Light calls via ProviderStore), with 400/422 fallback.
    • AnthropicModel: sends tool_choice = {"type": "any"} (disabling thinking when forced so Anthropic accepts forced tool choice) and max_tokens, with 400/422 fallback.
  • Upfront Main routing & 1-retry validation (ModelRouter.kt, ModelCaller.kt, LightCallValidator.kt, ConfirmDecision.kt):
    • Routes privileged tools, final summaries, and steer/review turns directly to Main before calling Light.
    • Retries once with LightPrompt.RETRY_REMINDER if Light returns prose without a tool call.
    • Validates Light tool calls via LightCallValidator (accepting valid offered non-privileged calls, auto-filling snapshotId when ref matches current snapshot, rejecting missing targets / invalid args / irreversible actions).
  • Telemetry & Run Metrics (RunEvent.kt, RunMetrics.kt, RunStore.kt, RunMetricsUi.kt, strings_metrics.xml across all 12 UI languages):
    • Records reason, decisionScore, validatorReason, lightTool, lightOutputTokens, and lightRetried on light_rejected replies.
    • Surfaces Light rejection counts and rate in run breakdown and stats UI.

Upstream adaptations

  • Rebased cleanly on wangzan101/Mika:main (9c7aabd8).
  • Preserved upstream's ModelPool routing, RateLimitGovernor, OpenAiServiceTier, keySupplier/onKeyRejected key rotation in GeminiModel/OpenAiCompatModel, and MeteredModel.counted(system, messages, tools).
  • Included follow-up fix so maxOutputTokens is only forwarded to Chat Completions / Responses adapters on forced Light calls (never on probes or regular Main calls).
  • Added metrics_light_rejected to values-tr/strings_metrics.xml to satisfy all 12 upstream UI locales.
  • Removed fork-only references (VertexModel, Antigravity) and replaced a local file path in AgentLoopLightTest with File.createTempFile.

How to test

python3 tools/i18n/translations.py check
./gradlew :core:test --tests "*AgentLoopLightTest*" --tests "*ModelRouterTest*" --tests "*RunMetricsTest*" --tests "*AgentLoopTest*" --tests "*GeminiModelTest*" --tests "*OpenAiCompatModelTest*" --tests "*ResponsesModelTest*" --tests "*AnthropicModelTest*"
./gradlew :app:testDebugUnitTest --tests "*RunStoreTest*" --tests "*RunMetricsCopyTest*" --tests "*ProviderStoreLightTest*"

Verified locally: translations.py check passed (3,933 resources across 12 UI languages) and all listed :core:test suites passed.

Copilot AI balanced review requested due to automatic review settings November 22, 2026 14:58
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T15:04:09.182473Z 01f6e9c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 01f6e9c5fa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1107 to +1110
UsagePurpose.Light -> roleEffort to CallOptions.LIGHT_MAX_OUTPUT_TOKENS
else -> roleEffort to null
}
val forceToolCall = purpose == UsagePurpose.Light

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope forced Light prompting to tool calls

When modelFor(ModelRole.Light) is used outside ModelCaller.routed, as AppAccessScreen.refresh does for AppClassifier and TeachRuntime.build does for Teach.draft, this sets the forced-tool flag and 200-token cap on the entire client. Those callers invoke complete with no tools, but the adapters still inject LightPrompt whenever the model flag is set, so they cannot produce the text those callers parse; app classification falls back to Main and Teach falls back to local assembly. Keep these constraints on routed tool calls rather than every Light-role model.

Useful? React with 👍 / 👎.

val finalLight = finalAttempt?.first
val usedLight = finalAttempt?.second ?: firstAttempt?.second ?: picked
when (val v = validation) {
is LightValidation.Accepted -> return v.reply to usedLight

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the first attempt's usage when a retry succeeds

When the first Light response has no tool and the retry returns an accepted tool call, this branch returns only the retry's ModelReply; unlike the rejection path below, it never includes firstLight usage. AgentLoop therefore records only the second attempt, so RunMetrics.tokens and the displayed run totals undercount the first request's billed input and output tokens, even if the separate model-call tally retains aggregate usage. Aggregate both attempts or record the first attempt separately.

Useful? React with 👍 / 👎.

if (reply == null) {
return LightValidation.Rejected("light_error", "model_error", null)
}
val call = reply.parts.filterIsInstance<Part.ToolCall>().firstOrNull()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the first actionable Light call

When a Light response puts the supported task_progress pseudo-call before a safe offered action, this selects the pseudo-call and the offered-name check rejects the whole response because task_progress is not a declared tool. ReplyCalls intentionally skips that pseudo-call and handles the real action, so this new validation discards an otherwise usable Light response and re-asks the step on Main. Validate the first non-progress action while leaving progress parsing to ReplyCalls.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants