Skip to content

feat(core): per-call model selection via RuntimeContext.modelId - #2097

Merged
jujn merged 2 commits into
agentscope-ai:mainfrom
Buktal:feat/per-session-model-switching
Nov 3, 2026
Merged

jujn merged 2 commits into
agentscope-ai:mainfrom
Buktal:feat/per-session-model-switching

Conversation

@Buktal

@Buktal Buktal commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Per-call model selection via RuntimeContext.modelId

Closes #2085.

Rework of this PR: the earlier iteration put a model_id in AgentState behind
ReActAgent.setModel/getModel. This version replaces it with a per-call modelId
on RuntimeContext, resolved through ModelRegistry — no persisted state, no
agent-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_id inside AgentState creates a second source of truth that can silently
diverge 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:

  • No AgentState field, no agent-level setter. A single immutable field on the
    per-call context is the whole mechanism: nothing to migrate, no cross-thread
    visibility race, no mid-run switch.
  • Session-level stickiness stays an application concern. Apps that want the
    choice remembered store it in their own session record and stamp it onto each
    request's context — one source of truth.
  • Server-driven cases (platform-assigned tenant models, headless sessions) work
    the same way
    : whatever process builds the RuntimeContext for the run stamps
    the id. "The platform picks the model" is just the app layer making the choice.

Usage

// Register once at startup (identical on every cluster node):
ModelRegistry.register("prod", openAiModel);
ModelRegistry.registerFactory("deepseek:.*", id -> deepseekModel(id));

// Each request carries the caller's choice:
RuntimeContext ctx = RuntimeContext.builder()
        .userId("alice")
        .sessionId("s-001")
        .modelId("deepseek:deepseek-v4")   // null = the agent's default model
        .build();
Msg result = agent.call(List.of(new UserMessage("Hi")), ctx).block();

A singleton immutable agent now serves sessions that need different models — no
reflection, no per-tenant agent instances.

Semantics

  • Fail-fast, never silent fallback. A set-but-blank or unresolvable id fails
    the call (IllegalArgumentException surfaced as an error event) instead of
    quietly using the default model — in multi-tenant setups the wrong model usually
    means the wrong credentials and the wrong bill. null (unset) simply means the
    agent's default model.
  • Selection is run-level and deterministic. The id is carried by the immutable
    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.
  • Provider runtime failures still failover. A selected model that fails at
    runtime hands over to the configured fallbackModel as before — failover governs
    availability; the selection itself is honored.
  • Aux calls follow the effective model; dedicated config wins. Compaction and
    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.
  • Subagents do not inherit. Both spawn boundaries (DefaultAgentManager,
    SubAgentTool) clear the caller's modelId: a subagent's model is its
    build-time contract (SubagentDeclaration.getModel()); a caller's runtime
    selection must not silently change a worker's model or its cost profile.
  • No allowlist mechanism is added. The ModelRegistry itself is the governed
    surface: an application registers exactly the models it is willing to serve,
    registerFactory covers families, and any id outside that surface fails loudly
    at call time. A per-agent deny-by-default list would duplicate that gate and add
    a config axis that can drift from the registry.
  • Not tool-visible; distinct from GenerateOptions.getModelName(). modelId
    is a first-class context field, not an attribute (not projected into tool
    execution context). getModelName() remains a provider-side routing hint and
    does not participate in selection.

Changes

  • core
    • RuntimeContext: first-class modelId — builder().modelId(...),
      getModelId(), copied by from() so the agent's internal per-run derivations
      keep it.
    • ReActAgent.getModel(RuntimeContext): resolves the per-call model;
      modelForCall routes every purpose through the effective model while keeping
      fallback semantics.
    • SubAgentTool: strips the caller's modelId before handing the context to a
      subagent.
    • Structured-output capability probing, pre/post-reasoning hook payloads and the
      empty-reply warning report the effective (per-call) model, not the build-time
      default.
  • harness
    • DefaultAgentManager: clears modelId on derived subagent contexts;
      AgentSession clears it on the session snapshot (a durable session spans many
      runs — a caller's per-call choice must not stick to every future turn).
    • AgentTraceMiddleware attributes the per-call model in traces.
    • CompactionMiddleware / MemoryFlushMiddleware: effective model resolves as
      dedicated config > agent's per-call model; HarnessAgent passes the dedicated
      config model only (may be null) so the middlewares resolve per-call at
      execution time.
  • docs — EN/ZH building-blocks/context.md: getModelId() reference row and a
    "Per-call model selection" section.
  • tests — RuntimeContextModelIdTest (field semantics, derivation,
    not-an-attribute), ReActAgentPerCallModelTest (routing, isolation, fail-fast,
    fallback interaction), MemoryFlushMiddlewareEffectiveModelTest,
    CompactionMiddlewareTest per-call case.

Compatibility

Additive only: no AgentState or serialization change, no removed API. Agents that
never set modelId behave exactly as before.

@Buktal
Buktal requested a review from a team July 10, 2026 03:38
@codecov

codecov Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 — modelId field with JSON round-trip and backward-compatible deserialization (missing field → null). Clean.
  • [Info] ReActAgent.java:348-364 — Resolution via ModelRegistry.namedMaps.get(modelId) with fallback to default is correct. apiKey never touches AgentState — 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

@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/agent Agent runtime, pipeline, hooks, plan labels Jul 11, 2026
AgentScopeJavaBot

This comment was marked as abuse.

@yaxxer

yaxxer commented Jul 14, 2026

Copy link
Copy Markdown

Will this feature be updated in version 2.0.1?

@Buktal

Buktal commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

Will this feature be updated in version 2.0.1?

@chickenlj

@oss-maintainer

This comment was marked as abuse.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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"

@ethanzhl

Copy link
Copy Markdown

使用动态代理创建Model是否会更好呢?

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 getModel resolving a persisted id through ModelRegistry.resolve(mid) with an empty ModelCreationContext (line 4268 — the lookup can reach user factories/SPI and construct a client from ambient credentials rather than being a pure name lookup) and on setModel accepting 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 on AgentState.modelId being 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

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

[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 model convention of LLM APIs. Persisting a model_id in AgentState creates a second source of truth that can silently diverge from the client's (missed setModel, CAS overwrite on cluster conflict, node drift), and since getModel reads state only, callers following the natural architecture are forced into a write-then-read dance (setModel + store write + version churn on every message) just to express "use model X for this call".

Suggestion: RuntimeContext.builder().modelId(...), resolved and validated once at call start in modelForCall(rc), failing fast on unresolvable ids. This also makes the model deterministic for the whole call (no mid-call switch, no cross-thread visibility race) and removes the need for an agent-level setter entirely.

Persisted model_id remains useful only for narrow server-driven cases (platform-assigned tenant models, headless sessions, out-of-band ops switching). If kept, treat it strictly as a lower-priority fallback (ctx > state > default) and document it as such.

Think about @jujn (In summary, conceptually adding setXxx to a ReActAgent at runtime is highly inappropriate.)

@jujn jujn added the TBD To Be Discuss label Oct 9, 2026
@xzxiaoshan

Copy link
Copy Markdown
Collaborator

需求方向上是合理的,感觉这块是需要好好思考一下如何更友好的实现。

在企业应用中,开发好的 Agent 可能限定了部分模型,也可能不做任何限制。
如果 ReActAgent 自身设置了可选模型列表,则运行态提供的 modelId 则必须校验是其列表名单之一,如果 ReActAgent 未做任何列表限定,需要思考默认是禁止,还是需要支持 * 等简单的匹配模型id格式。

思考:运行态(例如 RuntimeContext 或其他运行态方式) + 单例不可变的 ReActAgent 。
同时思考:模型的热切换是要支持到 run 级别(完整loop) ,还是在一次 run 过程中的每次 llm 调用级别。

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
@Buktal
Buktal force-pushed the feat/per-session-model-switching branch from 17f3e22 to f3a791d Compare October 9, 2026 09:08
@Buktal Buktal changed the title feat(core): support per-session runtime model switching feat(core): per-call model selection via RuntimeContext.modelId Oct 9, 2026

@CryoThrust CryoThrust left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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.

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

@Buktal 修一下冲突

@jujn

jujn commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

@Buktal 修一下冲突

我来吧

@mintlify

mintlify Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 1f535e8.

Approve preview

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
@jujn
jujn force-pushed the feat/per-session-model-switching branch from 6342e16 to 1f535e8 Compare November 3, 2026 09:38
@jujn
jujn merged commit cffb729 into agentscope-ai:main Nov 3, 2026
7 checks passed
xzxiaoshan added a commit to xzxiaoshan/agentscope-java that referenced this pull request Nov 4, 2026
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.
jujn pushed a commit that referenced this pull request Nov 10, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/agent Agent runtime, pipeline, hooks, plan enhancement New feature or request TBD To Be Discuss

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: HarnessAgent 单实例时,如何动态切换模型?好像不支持

8 participants