Repository navigation
feat(core): per-call model selection via RuntimeContext.modelId - #2097
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Adds per-session runtime model switching for singleton-scoped HarnessAgent, enabling multi-tenant isolation without redeployment. Mirrors the existing setPermissionMode pattern.
Findings
- [Info]
AgentState.java—modelIdfield with JSON round-trip and backward-compatible deserialization (missing field → null). Clean. - [Info]
ReActAgent.java:348-364— Resolution viaModelRegistry.namedMaps.get(modelId)with fallback to default is correct.apiKeynever touchesAgentState— good security practice. - [Info]
CompactionMiddleware.java/MemoryFlushMiddleware.java— Dedicated models still take priority over per-session model. Correct precedence. - [Info] Tests are comprehensive: per-session isolation, cluster drift reload, clear→revert, unresolvable-id fallback, end-to-end call routing.
Verdict
Well-designed feature with thorough test coverage. The approach of persisting only the model id (not the model instance or apiKey) is the right call for cluster safety. LGTM.
Automated review by github-manager
|
Will this feature be updated in version 2.0.1? |
|
This comment was marked as abuse.
This comment was marked as abuse.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Adds per-session runtime model switching: a persisted model_id on AgentState resolved through ModelRegistry on every call, with setModel/clearModel on ReActAgent/HarnessAgent, and compaction/memory-flush now honoring a dedicated model before falling back to the per-session model. Well-structured change with good test coverage (persistence, cluster rebirth, per-session isolation, routing, JSON round-trip, blank normalization). Overall direction looks right; main concerns are resolution semantics for session ids (SPI/fallback construction) and eager validation. Note: the PR currently has conflicts with main and needs a rebase before it can be merged, so this review is submitted as comments.
Automated review by github-manager-bot"
|
使用动态代理创建Model是否会更好呢? |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the new head 17f3e22d. The only thing that moved since my cb809c7b review is a Merge upstream/main into feat/per-session-model-switching commit — none of the seven files this PR owns gained author changes in between (ReActAgent.java and ReActAgentPerSessionStateTest.java differ only through the upstream merge). Two consequences:
- The blocker I flagged last time is gone: the PR is now
mergeable: true/mergeStateStatus: clean, and CI is green on this head (build (ubuntu-latest),build (windows-latest),Check License,Check Module Sync,codecov/patch), CLA signed. So the rebase request is satisfied and nothing about the merge needs further action from you. - Because the implementation is unchanged, the four points from my previous review still stand and I am deliberately not restating them: the two Warnings on
getModelresolving a persisted id throughModelRegistry.resolve(mid)with an emptyModelCreationContext(line 4268 — the lookup can reach user factories/SPI and construct a client from ambient credentials rather than being a pure name lookup) and onsetModelaccepting an unresolvable id eagerly-persisted with only a warn-log fallback later (line 4684), plus the two Info notes on per-call resolution cost on the hot path and onAgentState.modelIdbeing mutable where the other fields are final.
No new issues found in the merged code. Keeping this as comments rather than an approval, since the ModelRegistry.resolve credential-resolution question is what I would want answered before this is merged — a ModelRegistry lookup that can construct a provider from ambient env state turns a persisted model_id into something a session can use to reach credentials it does not own, which matters specifically because the stated goal is multi-tenant isolation on a singleton agent.
Automated review by github-manager-bot
|
[Design suggestion] Model selection is a per-call parameter — consider RuntimeContext instead of persisted state + agent setter For the interactive use case motivating this PR (#2085), the source of truth for the model choice is the client/business layer (the UI selector needs it anyway, and it's typically mirrored in the business DB), so every chat request naturally carries the modelId — the per-request Suggestion: Persisted Think about @jujn (In summary, conceptually adding setXxx to a ReActAgent at runtime is highly inappropriate.) |
|
需求方向上是合理的,感觉这块是需要好好思考一下如何更友好的实现。 在企业应用中,开发好的 Agent 可能限定了部分模型,也可能不做任何限制。 思考:运行态(例如 RuntimeContext 或其他运行态方式) + 单例不可变的 ReActAgent 。 |
Single immutable agents can now serve sessions that need different models: callers stamp a model id on the per-call RuntimeContext and every model call of the run (reasoning, summarization, compaction, memory flush) resolves it through ModelRegistry, failing fast on unresolvable ids instead of silently falling back. Subagents and durable sessions do not inherit the caller's choice. Closes agentscope-ai#2085
17f3e22 to
f3a791d
Compare
CryoThrust
left a comment
There was a problem hiding this comment.
Checked the rewritten per-call selection on f3a791df. A public two-round ReAct call reproduces a mid-run switch when the registered instance is replaced. I added three controls in test-only d639f961 for author adoption; production code is unchanged.
mvn -B -ntp -T1 -pl agentscope-core -am -Dtest=ReActAgentPerCallModelTest,RuntimeContextModelIdTest test runs 13 cases: the new in-flight-binding regression fails, the other 12 pass. Both stable-registry/two-round and later-call/replacement controls pass. Formatting passes. A broader Core run excluding that new regression ran 2,602 cases, with nine skips and one failure in GracefulShutdownTest.defaultConfig (100ms instead of null); the shutdown class passes all 51 cases when run alone. I am not claiming the full reactor is green.
| public Model getModel(RuntimeContext ctx) { | ||
| String modelId = ctx != null ? ctx.getModelId() : null; | ||
| if (modelId != null) { | ||
| return ModelRegistry.resolve(modelId); |
There was a problem hiding this comment.
[P2] Bind the selected model once per call execution
An immutable model ID does not make the resolved model stable: this getter performs a new registry lookup on each access, and ModelRegistry.register(id, model) can replace a named entry. I reproduced this through agent.call(...): register A as test:turn, let A emit a tool call, have that tool register B under the same ID, then resume reasoning with the unchanged context. A is called once and B produces the final answer; the regression expecting A for both rounds fails. An ordinary concurrent registration between rounds has the same effect. This contradicts the documented whole-run/no-mid-run-switch contract, and hooks/compaction/memory can resolve a different model too. Please resolve and retain the selection in the execution-owned scope, then share it with consumers of that run; a later execution should still see B. Avoid caching it on the singleton agent or on a caller-reused RuntimeContext. The test-only commit includes stable-registry and later-execution controls.
|
@Buktal 修一下冲突 |
我来吧 |
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Resolve conflicts in ReActAgent and CompactionMiddleware to integrate per-call model selection (RuntimeContext.modelId) with upstream's refactored modelForCall and CompactionMiddleware.prepareCandidate: - ReActAgent: keep per-call model (callModel) for structured output routing; adopt upstream's log.debug line - CompactionMiddleware overflowRecovery: adopt upstream's isRequestProjection filtering and initialState tracking - CompactionMiddleware prepareCandidate: keep PR's compactModel (per-call model resolution) for ConversationCompactor; adopt upstream's 4-arg constructor with token counters and sameSerializedHistory for canCommit
6342e16 to
1f535e8
Compare
Follow-up to agentscope-ai#2097: rename the per-call model selection to modelIdentity, formalize the model identifier vocabulary (providerId, modelId, modelCreationContextId, modelInstanceId, modelIdentity), and harden ModelRegistry. Consumer layer: - RuntimeContext.modelId -> modelIdentity; ReActAgent.Builder.model(String) becomes a lazy per-call reference instead of resolving at build time (priority: ctx.modelIdentity > agent identity > Model instance; unresolvable identities fail the call instead of silently falling back) - New composite identity form contextId@modelId (e.g. mytokenplan01@dashscope:qwen-plus): the credentials pairing travels with the identity string, so cross-provider per-call switching needs no agent-level context assumption - Two configuration forms for an agent's model: a fixed Model instance or a registry-managed modelIdentity reference (one slot, last setter wins) ModelRegistry: - resolve(String) is the single identity entry: composite dispatch first, then registered instances (explicit pins outrank pattern routing and the cache), then derivation; the two-argument resolve(modelId, context) is purely the derivation path and never consults registered instances, closing the cross-tenant credentials shadowing; canResolve mirrors both - Named creation contexts: registerCreationContext / getCreationContext / unregisterCreationContext; re-registering a contextId rotates credentials by evicting explicit:<contextId> entries, effective for resolutions that start afterwards (residual window documented) - Cache identity coherence: ENABLED contexts without standard fields share the legacy bucket; length-prefixed fingerprints (no separator collisions); explicit-cacheId drift warning while the cacheId stays authoritative - SPI determinism: multiple providers claiming one id fail listing all candidates; the not-found message lists installed provider ids; reloadProviders evicts SPI-derived cache entries - API hygiene: register/unregister/getRegistered trim and reject blank or '@'-containing ids; '@' is reserved for the composite identity syntax; evictResolvedCache gained a string-keyed (contextId, modelId) overload Docs: concept dictionary and matching-rules table in ModelRegistry javadoc; modelId vs modelIdentity distinction in building-blocks/model.md and integration/model/index.md; per-call selection guide in building-blocks/context.md — EN/ZH aligned.
…y(PR #2097 perfected) (#3965) Follow-up to #2097. The original goal still stands: one singleton agent serving many sessions that need different models, without reflection or per-tenant agent instances. Along the way this PR also straightens out the model identifier vocabulary and makes `ModelRegistry` safe under concurrent rotation. The description below reflects the final shape after two rounds of review; the design did move during review, so if you reviewed an earlier iteration, skim the per-call section again. ## Two ways to give a ReActAgent its model Either you build the model yourself and hand it over, or you hand over a string and let the registry do the work: ```java ReActAgent.builder().model(myModelInstance) // fixed instance ReActAgent.builder().model("mytokenplan01@dashscope:qwen-plus") // registry-managed reference ``` The two overloads are one configuration slot, last setter wins. An identity string is held as a lazy reference and resolved once per run, at run entry, on a boundedElastic scheduler, so a slow factory never sits on the caller's thread (which may well be an event loop). The resolved instance is memoized into the run's context: the model is decided once and never switches mid-response. Re-registering an instance, factory, or creation context affects runs that start afterwards, not runs in flight. An identity that cannot be resolved fails the run at entry instead of quietly falling back to some other model.
Per-call model selection via
RuntimeContext.modelIdCloses #2085.
Rework of this PR: the earlier iteration put a
model_idinAgentStatebehindReActAgent.setModel/getModel. This version replaces it with a per-callmodelIdon
RuntimeContext, resolved throughModelRegistry— no persisted state, noagent-level setter.
Why per-call context, not persisted state
For the interactive use case in #2085 (a UI model selector), the source of truth for
the choice is the client/business layer — the selector needs it anyway, and it is
typically mirrored in the business DB. Every chat request naturally carries the
model, which matches the per-request model convention of LLM APIs. Persisting a
model_idinsideAgentStatecreates a second source of truth that can silentlydiverge from the client's (missed
setModel, CAS overwrite on cluster conflict,node drift), and forces a write-then-read dance (set + store write + version churn)
on every message just to express "use model X for this call".
So persisted model selection is dropped entirely:
AgentStatefield, no agent-level setter. A single immutable field on theper-call context is the whole mechanism: nothing to migrate, no cross-thread
visibility race, no mid-run switch.
choice remembered store it in their own session record and stamp it onto each
request's context — one source of truth.
the same way: whatever process builds the
RuntimeContextfor the run stampsthe id. "The platform picks the model" is just the app layer making the choice.
Usage
A singleton immutable agent now serves sessions that need different models — no
reflection, no per-tenant agent instances.
Semantics
the call (
IllegalArgumentExceptionsurfaced as an error event) instead ofquietly using the default model — in multi-tenant setups the wrong model usually
means the wrong credentials and the wrong bill.
null(unset) simply means theagent's default model.
context for the whole run: every model call of that run (reasoning,
summarization, compaction, memory flush) resolves it. No mid-run switching, no
cross-call leakage.
runtime hands over to the configured
fallbackModelas before — failover governsavailability; the selection itself is honored.
memory flush use the resolved model (compaction thresholds derive from the
effective model's context window) unless a dedicated model is configured
(
CompactionConfig.getModel()/MemoryConfig.model()), which keeps precedence.Overflow recovery summarizes through the dedicated or build-time default model —
never the per-call model that just overflowed.
DefaultAgentManager,SubAgentTool) clear the caller'smodelId: a subagent's model is itsbuild-time contract (
SubagentDeclaration.getModel()); a caller's runtimeselection must not silently change a worker's model or its cost profile.
ModelRegistryitself is the governedsurface: an application registers exactly the models it is willing to serve,
registerFactorycovers families, and any id outside that surface fails loudlyat call time. A per-agent deny-by-default list would duplicate that gate and add
a config axis that can drift from the registry.
GenerateOptions.getModelName().modelIdis a first-class context field, not an attribute (not projected into tool
execution context).
getModelName()remains a provider-side routing hint anddoes not participate in selection.
Changes
RuntimeContext: first-classmodelId—builder().modelId(...),getModelId(), copied byfrom()so the agent's internal per-run derivationskeep it.
ReActAgent.getModel(RuntimeContext): resolves the per-call model;modelForCallroutes every purpose through the effective model while keepingfallback semantics.
SubAgentTool: strips the caller'smodelIdbefore handing the context to asubagent.
empty-reply warning report the effective (per-call) model, not the build-time
default.
DefaultAgentManager: clearsmodelIdon derived subagent contexts;AgentSessionclears it on the session snapshot (a durable session spans manyruns — a caller's per-call choice must not stick to every future turn).
AgentTraceMiddlewareattributes the per-call model in traces.CompactionMiddleware/MemoryFlushMiddleware: effective model resolves asdedicated config > agent's per-call model;
HarnessAgentpasses the dedicatedconfig model only (may be null) so the middlewares resolve per-call at
execution time.
building-blocks/context.md:getModelId()reference row and a"Per-call model selection" section.
RuntimeContextModelIdTest(field semantics, derivation,not-an-attribute),
ReActAgentPerCallModelTest(routing, isolation, fail-fast,fallback interaction),
MemoryFlushMiddlewareEffectiveModelTest,CompactionMiddlewareTestper-call case.Compatibility
Additive only: no
AgentStateor serialization change, no removed API. Agents thatnever set
modelIdbehave exactly as before.