Skip to content

Commit 8e88079

Browse files
committed
refactor(providers): consolidate compatible replay policies
1 parent f0a963a commit 8e88079

9 files changed

Lines changed: 219 additions & 244 deletions

File tree

‎extensions/baseten/stream.ts‎

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
/** Baseten request payload policy for models with opt-in chat-template reasoning. */
22
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
3-
import { createPayloadPatchStreamWrapper } from "openclaw/plugin-sdk/provider-stream-shared";
3+
import {
4+
createPayloadPatchStreamWrapper,
5+
normalizeOpenAICompatibleReasoningReplay,
6+
} from "openclaw/plugin-sdk/provider-stream-shared";
47
import { usesBasetenChatTemplateThinking } from "./models.js";
58

69
const BASETEN_DEEPSEEK_V4_MODEL_ID = "deepseek-ai/deepseek-v4-pro";
@@ -13,31 +16,6 @@ function isBasetenDeepSeekV4ModelId(modelId: string): boolean {
1316
return modelId.trim().toLowerCase() === BASETEN_DEEPSEEK_V4_MODEL_ID;
1417
}
1518

16-
function patchBasetenDeepSeekV4Replay(
17-
payload: Record<string, unknown>,
18-
thinkingEnabled: boolean,
19-
): void {
20-
if (!Array.isArray(payload.messages)) {
21-
return;
22-
}
23-
for (const message of payload.messages) {
24-
if (!message || typeof message !== "object" || Array.isArray(message)) {
25-
continue;
26-
}
27-
const record = message as Record<string, unknown>;
28-
if (record.role !== "assistant") {
29-
continue;
30-
}
31-
// DeepSeek V4 requires reasoning_content on replayed assistant turns.
32-
// Cross-provider turns lack it, so backfill while thinking is enabled.
33-
if (thinkingEnabled) {
34-
record.reasoning_content ??= "";
35-
} else {
36-
delete record.reasoning_content;
37-
}
38-
}
39-
}
40-
4119
/** Adds Baseten's `chat_template_args.enable_thinking` without dropping caller args. */
4220
export function createBasetenThinkingWrapper(
4321
ctx: ProviderWrapStreamFnContext,
@@ -49,7 +27,11 @@ export function createBasetenThinkingWrapper(
4927
if (isBasetenDeepSeekV4ModelId(model.id)) {
5028
// DeepSeek reasoning defaults on when no level is supplied. Only an
5129
// explicit `off` may remove its required replay metadata.
52-
patchBasetenDeepSeekV4Replay(payload, ctx.thinkingLevel !== "off");
30+
normalizeOpenAICompatibleReasoningReplay(payload, {
31+
thinkingEnabled: ctx.thinkingLevel !== "off",
32+
stripAssistantMessagesOnly: true,
33+
replaceNullReasoningContent: true,
34+
});
5335
}
5436
if (!usesBasetenChatTemplateThinking(model.id)) {
5537
return;

‎extensions/kimi-coding/stream.ts‎

Lines changed: 9 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import {
66
type AssistantMessageEvent,
77
} from "openclaw/plugin-sdk/llm";
88
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
9-
import { streamWithPayloadPatch } from "openclaw/plugin-sdk/provider-stream-shared";
9+
import {
10+
normalizeOpenAICompatibleReasoningReplay,
11+
streamWithPayloadPatch,
12+
} from "openclaw/plugin-sdk/provider-stream-shared";
1013
import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/string-coerce-runtime";
1114
import { isKimiK3ModelId } from "./provider-policy-api.js";
1215

@@ -94,39 +97,6 @@ function ensureKimiAnthropicMaxTokens(
9497
payloadObj.max_tokens = current === undefined ? required : Math.max(current, required);
9598
}
9699

97-
function messageHasOpenAIToolCalls(message: Record<string, unknown>): boolean {
98-
return Array.isArray(message.tool_calls) && message.tool_calls.length > 0;
99-
}
100-
101-
function ensureKimiOpenAIReasoningContent(payloadObj: Record<string, unknown>): void {
102-
if (!Array.isArray(payloadObj.messages)) {
103-
return;
104-
}
105-
for (const message of payloadObj.messages) {
106-
if (!message || typeof message !== "object") {
107-
continue;
108-
}
109-
const record = message as Record<string, unknown>;
110-
if (record.role !== "assistant" || !messageHasOpenAIToolCalls(record)) {
111-
continue;
112-
}
113-
if (!("reasoning_content" in record)) {
114-
record.reasoning_content = "";
115-
}
116-
}
117-
}
118-
119-
function stripKimiOpenAIReasoningContent(payloadObj: Record<string, unknown>): void {
120-
if (!Array.isArray(payloadObj.messages)) {
121-
return;
122-
}
123-
for (const message of payloadObj.messages) {
124-
if (message && typeof message === "object") {
125-
delete (message as Record<string, unknown>).reasoning_content;
126-
}
127-
}
128-
}
129-
130100
function normalizeKimiThinkingType(value: unknown): KimiThinkingType | undefined {
131101
if (typeof value === "boolean") {
132102
return value ? "enabled" : "disabled";
@@ -447,10 +417,12 @@ function createKimiThinkingWrapper(
447417
model.api === "anthropic-messages" ? { ...normalized } : { type: normalized.type };
448418
if (model.api === "anthropic-messages") {
449419
ensureKimiAnthropicMaxTokens(payloadObj, normalized);
450-
} else if (normalized.type === "enabled") {
451-
ensureKimiOpenAIReasoningContent(payloadObj);
452420
} else {
453-
stripKimiOpenAIReasoningContent(payloadObj);
421+
normalizeOpenAICompatibleReasoningReplay(payloadObj, {
422+
thinkingEnabled: normalized.type === "enabled",
423+
shouldBackfillAssistantMessage: (message) =>
424+
Array.isArray(message.tool_calls) && message.tool_calls.length > 0,
425+
});
454426
}
455427
delete payloadObj.reasoning;
456428
delete payloadObj.reasoning_effort;

‎extensions/ollama/index.ts‎

Lines changed: 38 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
type ProviderAuthResult,
1414
type ProviderAugmentModelCatalogContext,
1515
type ProviderCatalogContext,
16+
type ProviderPlugin,
1617
type ProviderReplayPolicy,
1718
type ProviderRuntimeModel,
1819
} from "openclaw/plugin-sdk/plugin-entry";
@@ -28,7 +29,6 @@ import type {
2829
} from "openclaw/plugin-sdk/provider-model-shared";
2930
import {
3031
buildOpenAICompatibleReplayPolicy,
31-
buildProviderReplayFamilyHooks,
3232
selectPreferredLocalModelId,
3333
} from "openclaw/plugin-sdk/provider-model-shared";
3434
import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
@@ -712,6 +712,41 @@ async function augmentConfiguredOllamaCatalogModels(params: {
712712
return entries;
713713
}
714714

715+
// Local and cloud own distinct auth/catalog policy but share native transport and replay rules.
716+
const OLLAMA_SHARED_PROVIDER_HOOKS = {
717+
createStreamFn: ({ config, model, provider }) => {
718+
if (model.api !== "ollama") {
719+
return undefined;
720+
}
721+
return createConfiguredOllamaStreamFn({
722+
model,
723+
providerBaseUrl:
724+
readProviderBaseUrl(
725+
resolveConfiguredOllamaProviderConfig({ config, providerId: provider }),
726+
) ?? (provider === OLLAMA_CLOUD_PROVIDER_ID ? OLLAMA_CLOUD_BASE_URL : undefined),
727+
});
728+
},
729+
buildReplayPolicy: ({ modelApi }) =>
730+
modelApi === "ollama"
731+
? buildNativeOllamaReplayPolicy()
732+
: buildOpenAICompatibleReplayPolicy(modelApi),
733+
resolveReasoningOutputMode: () => "native",
734+
resolveThinkingProfile: resolveOllamaThinkingProfile,
735+
wrapStreamFn: createConfiguredOllamaCompatStreamWrapper,
736+
matchesContextOverflowError: ({ errorMessage }) =>
737+
matchesOllamaContextOverflowError(errorMessage),
738+
classifyFailoverReason: ({ errorMessage }) => classifyOllamaFailoverReason(errorMessage),
739+
} satisfies Pick<
740+
ProviderPlugin,
741+
| "createStreamFn"
742+
| "buildReplayPolicy"
743+
| "resolveReasoningOutputMode"
744+
| "resolveThinkingProfile"
745+
| "wrapStreamFn"
746+
| "matchesContextOverflowError"
747+
| "classifyFailoverReason"
748+
>;
749+
715750
export default definePluginEntry({
716751
id: "ollama",
717752
name: "Ollama Provider",
@@ -793,26 +828,7 @@ export default definePluginEntry({
793828
provider: buildStaticOllamaCloudProvider(),
794829
}),
795830
},
796-
createStreamFn: ({ config, model, provider }) => {
797-
if (model.api !== "ollama") {
798-
return undefined;
799-
}
800-
return createConfiguredOllamaStreamFn({
801-
model,
802-
providerBaseUrl:
803-
readProviderBaseUrl(
804-
resolveConfiguredOllamaProviderConfig({ config, providerId: provider }),
805-
) ?? OLLAMA_CLOUD_BASE_URL,
806-
});
807-
},
808-
...buildProviderReplayFamilyHooks({ family: "openai-compatible" }),
809-
buildReplayPolicy: (ctx) =>
810-
ctx.modelApi === "ollama"
811-
? buildNativeOllamaReplayPolicy()
812-
: buildOpenAICompatibleReplayPolicy(ctx.modelApi),
813-
resolveReasoningOutputMode: () => "native",
814-
resolveThinkingProfile: resolveOllamaThinkingProfile,
815-
wrapStreamFn: createConfiguredOllamaCompatStreamWrapper,
831+
...OLLAMA_SHARED_PROVIDER_HOOKS,
816832
resolveDynamicModel: ({ provider, modelId }) => {
817833
const cloudProvider = buildStaticOllamaCloudProvider();
818834
const model = cloudProvider.models?.find((entry) => entry.id === modelId);
@@ -829,9 +845,6 @@ export default definePluginEntry({
829845
entries: ctx.entries,
830846
resolveProviderApiKey: ctx.resolveProviderApiKey,
831847
}),
832-
matchesContextOverflowError: ({ errorMessage }) =>
833-
matchesOllamaContextOverflowError(errorMessage),
834-
classifyFailoverReason: ({ errorMessage }) => classifyOllamaFailoverReason(errorMessage),
835848
buildUnknownModelHint: () =>
836849
"Ollama Cloud requires an API key. " +
837850
'Set OLLAMA_API_KEY or run "openclaw onboard --auth-choice ollama-cloud". ' +
@@ -971,25 +984,7 @@ export default definePluginEntry({
971984
}
972985
await ensureOllamaModelPulled({ config, model, prompter });
973986
},
974-
createStreamFn: ({ config, model, provider }) => {
975-
if (model.api !== "ollama") {
976-
return undefined;
977-
}
978-
return createConfiguredOllamaStreamFn({
979-
model,
980-
providerBaseUrl: readProviderBaseUrl(
981-
resolveConfiguredOllamaProviderConfig({ config, providerId: provider }),
982-
),
983-
});
984-
},
985-
...buildProviderReplayFamilyHooks({ family: "openai-compatible" }),
986-
buildReplayPolicy: (ctx) =>
987-
ctx.modelApi === "ollama"
988-
? buildNativeOllamaReplayPolicy()
989-
: buildOpenAICompatibleReplayPolicy(ctx.modelApi),
990-
resolveReasoningOutputMode: () => "native",
991-
resolveThinkingProfile: resolveOllamaThinkingProfile,
992-
wrapStreamFn: createConfiguredOllamaCompatStreamWrapper,
987+
...OLLAMA_SHARED_PROVIDER_HOOKS,
993988
augmentModelCatalog: async (ctx) =>
994989
await augmentConfiguredOllamaCatalogModels({
995990
config: ctx.config,
@@ -1012,9 +1007,6 @@ export default definePluginEntry({
10121007
client,
10131008
};
10141009
},
1015-
matchesContextOverflowError: ({ errorMessage }) =>
1016-
matchesOllamaContextOverflowError(errorMessage),
1017-
classifyFailoverReason: ({ errorMessage }) => classifyOllamaFailoverReason(errorMessage),
10181010
resolveSyntheticAuth: ({ provider, providerConfig }) => {
10191011
if (!shouldUseSyntheticOllamaAuth(providerConfig)) {
10201012
return undefined;

‎extensions/openrouter/stream.ts‎

Lines changed: 8 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
33
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
44
import { buildProviderStreamFamilyHooks } from "openclaw/plugin-sdk/provider-stream-family";
5-
import { createPayloadPatchStreamWrapper } from "openclaw/plugin-sdk/provider-stream-shared";
5+
import {
6+
createPayloadPatchStreamWrapper,
7+
normalizeOpenAICompatibleReasoningReplay,
8+
} from "openclaw/plugin-sdk/provider-stream-shared";
69
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
710
import { isOpenRouterDeepSeekV4ModelId } from "./models.js";
811
import {
@@ -165,37 +168,6 @@ function isOpenRouterReasoningPayloadEnabled(payload: Record<string, unknown>):
165168
);
166169
}
167170

168-
function stripOpenRouterDeepSeekV4ReasoningContent(payload: Record<string, unknown>): void {
169-
if (!Array.isArray(payload.messages)) {
170-
return;
171-
}
172-
for (const message of payload.messages) {
173-
if (!message || typeof message !== "object") {
174-
continue;
175-
}
176-
delete (message as Record<string, unknown>).reasoning_content;
177-
}
178-
}
179-
180-
function backfillOpenRouterDeepSeekV4ReasoningContent(payload: Record<string, unknown>): void {
181-
if (!Array.isArray(payload.messages)) {
182-
return;
183-
}
184-
for (const message of payload.messages) {
185-
if (!message || typeof message !== "object") {
186-
continue;
187-
}
188-
const record = message as Record<string, unknown>;
189-
if (
190-
record.role === "assistant" &&
191-
!assistantMessageHasOpenAIToolCalls(record) &&
192-
!("reasoning_content" in record)
193-
) {
194-
record.reasoning_content = "";
195-
}
196-
}
197-
}
198-
199171
function injectOpenRouterRouting(
200172
baseStreamFn: StreamFn | undefined,
201173
providerRouting?: Record<string, unknown>,
@@ -291,11 +263,10 @@ function createOpenRouterDeepSeekV4ReplayWrapper(
291263
({ payload }) => {
292264
delete payload.thinking;
293265
delete payload.reasoning_effort;
294-
if (!applyOpenRouterDeepSeekV4ReasoningEffort(payload, thinkingLevel)) {
295-
stripOpenRouterDeepSeekV4ReasoningContent(payload);
296-
return;
297-
}
298-
backfillOpenRouterDeepSeekV4ReasoningContent(payload);
266+
normalizeOpenAICompatibleReasoningReplay(payload, {
267+
thinkingEnabled: applyOpenRouterDeepSeekV4ReasoningEffort(payload, thinkingLevel),
268+
shouldBackfillAssistantMessage: (message) => !assistantMessageHasOpenAIToolCalls(message),
269+
});
299270
},
300271
{
301272
shouldPatch: ({ model }) => shouldPatchDeepSeekV4OpenRouterPayload(model),

‎extensions/qwen/stream.ts‎

Lines changed: 9 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
66
import {
77
createPayloadPatchStreamWrapper,
88
isOpenAICompatibleThinkingEnabled,
9+
normalizeOpenAICompatibleReasoningReplay,
910
setQwenChatTemplateThinking,
1011
} from "openclaw/plugin-sdk/provider-stream-shared";
1112
import {
@@ -104,28 +105,11 @@ function patchTokenPlanDeepSeekV4Payload(
104105
delete payload.thinking;
105106
if (!enableThinking) {
106107
delete payload.reasoning_effort;
107-
if (Array.isArray(payload.messages)) {
108-
for (const message of payload.messages) {
109-
if (message && typeof message === "object") {
110-
delete (message as Record<string, unknown>).reasoning_content;
111-
}
112-
}
113-
}
108+
normalizeOpenAICompatibleReasoningReplay(payload, { thinkingEnabled: false });
114109
return;
115110
}
116111
payload.reasoning_effort = thinkingLevel === "xhigh" || thinkingLevel === "max" ? "max" : "high";
117-
if (!Array.isArray(payload.messages)) {
118-
return;
119-
}
120-
for (const message of payload.messages) {
121-
if (!message || typeof message !== "object") {
122-
continue;
123-
}
124-
const record = message as Record<string, unknown>;
125-
if (record.role === "assistant" && !("reasoning_content" in record)) {
126-
record.reasoning_content = "";
127-
}
128-
}
112+
normalizeOpenAICompatibleReasoningReplay(payload, { thinkingEnabled: true });
129113
}
130114

131115
function patchTokenPlanKimiPayload(
@@ -134,22 +118,12 @@ function patchTokenPlanKimiPayload(
134118
): void {
135119
delete payload.thinking;
136120
delete payload.reasoning_effort;
137-
if (!enableThinking || !Array.isArray(payload.messages)) {
138-
return;
139-
}
140-
for (const message of payload.messages) {
141-
if (!message || typeof message !== "object") {
142-
continue;
143-
}
144-
const record = message as Record<string, unknown>;
145-
if (
146-
record.role === "assistant" &&
147-
Array.isArray(record.tool_calls) &&
148-
record.tool_calls.length > 0 &&
149-
!("reasoning_content" in record)
150-
) {
151-
record.reasoning_content = "";
152-
}
121+
if (enableThinking) {
122+
normalizeOpenAICompatibleReasoningReplay(payload, {
123+
thinkingEnabled: true,
124+
shouldBackfillAssistantMessage: (message) =>
125+
Array.isArray(message.tool_calls) && message.tool_calls.length > 0,
126+
});
153127
}
154128
}
155129

0 commit comments

Comments
 (0)