refactor(models): rebuild vendor integration on protocol + catalog + vendor layers (#3470)
把集中式的 OpenAI 方言客户端重建为三层:协议层 internal/models/api/<protocol>(OpenAI Chat Completions / OpenAI Responses / Anthropic Messages / Google GenAI),目录层 internal/models/catalog,厂商层 internal/models/vendors/<id>(27 家,go:embed)。27 家厂商逐条对照官方文档核验,厂商事实以数据声明,协议层不出现厂商名。 既有行的运行时行为会变的四处: 1. extra_config.api 变为保留的协议选择器,非法取值被拒绝; 2. Azure 未填 api_version 的行改走 /openai/v1 GA 数据面; 3. api.openai.com 的一方流量改走 Responses 协议(中转/网关不受影响); 4. 7 家厂商的输出上限字段按文档纠正。 不需要数据库迁移。详见 PR 描述与 website-docs/03-features/06-models.md。main
parent
50bbf9ad5f
commit
c40a9dd194
18
Makefile
18
Makefile
|
|
@ -44,6 +44,11 @@ help:
|
|||
@echo " docs 生成 Swagger API 文档"
|
||||
@echo " install-swagger 安装 swag 工具"
|
||||
@echo ""
|
||||
@echo "模型厂商目录:"
|
||||
@echo " model-catalog-check 校验厂商目录(不变量 + 新旧行为对照 + 厂商测试)"
|
||||
@echo " model-catalog-diff 对比 models.dev,输出模型元数据差异报告(需人工审阅)"
|
||||
@echo " 可选: make model-catalog-diff VENDOR=deepseek"
|
||||
@echo ""
|
||||
@echo "环境检查:"
|
||||
@echo " check-env 检查环境配置"
|
||||
@echo " list-containers 列出运行中的容器"
|
||||
|
|
@ -107,6 +112,19 @@ run: build
|
|||
test:
|
||||
go test -v ./...
|
||||
|
||||
# Vendor catalog: invariants, legacy-behaviour parity and vendor facts.
|
||||
# Run this after adding a vendor or editing any models.json.
|
||||
.PHONY: model-catalog-check
|
||||
model-catalog-check:
|
||||
go test ./internal/models/parity/ ./internal/models/vendors/ ./internal/models/catalog/ ./internal/models/api/...
|
||||
|
||||
# Vendor catalog: report where our model metadata differs from models.dev.
|
||||
# Development aid only — nothing is fetched at runtime and nothing is written
|
||||
# automatically; review each line against the vendor's own documentation.
|
||||
.PHONY: model-catalog-diff
|
||||
model-catalog-diff:
|
||||
@python3 scripts/model_catalog_diff.py $(if $(VENDOR),--vendor $(VENDOR),)
|
||||
|
||||
# Clean build artifacts
|
||||
clean:
|
||||
go clean
|
||||
|
|
|
|||
|
|
@ -75,3 +75,14 @@ builtin_models: []
|
|||
# api_key: ${OPENAI_API_KEY}
|
||||
# provider: openai
|
||||
# context_window: 200000 # optional; omit to use the 200K default
|
||||
# # Optional catalog overrides for chat models. `api` forces the wire
|
||||
# # protocol; `compat` is the flat protocol object documented in
|
||||
# # internal/models/catalog/compat.go; `thinking_levels` maps the
|
||||
# # off/auto/minimal/low/medium/high/xhigh/max ladder to vendor values.
|
||||
# # spec:
|
||||
# # api: openai-completions
|
||||
# # compat:
|
||||
# # max_tokens_field: max_tokens
|
||||
# # thinking_format: thinking-type
|
||||
# # thinking_levels:
|
||||
# # xhigh: high
|
||||
|
|
|
|||
|
|
@ -0,0 +1,61 @@
|
|||
{
|
||||
"_comment": [
|
||||
"config/models.json — deployment overlay for the model catalog.",
|
||||
"Copy to config/models.json (or point MODELS_CONFIG at a custom path).",
|
||||
"Same idea as pi's ~/.pi/agent/models.json: 'providers' is keyed by vendor id.",
|
||||
"A known id (see GET /api/v1/models/providers) patches the built-in vendor;",
|
||||
"a new id declares a vendor. String values accept ${ENV} / $ENV interpolation.",
|
||||
"Unknown keys are rejected at startup so typos surface immediately.",
|
||||
"'models' upserts by id: an id that already exists keeps every field you",
|
||||
"did not write (reasoning, thinking_levels, compat, input); a new id is created.",
|
||||
"'icon' is an inline <svg ...> string or an .svg path under this file's own",
|
||||
"directory — no absolute paths, no escaping it, 256 KB max: icons are served",
|
||||
"as a data: URI to everyone who can open the model pages.",
|
||||
"Per-model 'compat' keys depend on the protocol; see internal/models/catalog/compat.go."
|
||||
],
|
||||
"providers": {
|
||||
"openai": {
|
||||
"base_url": "https://gateway.example.com/openai/v1",
|
||||
"api_key": "${OPENAI_API_KEY}",
|
||||
"headers": {"X-Gateway-Team": "rag"},
|
||||
"model_overrides": {
|
||||
"gpt-5.5": {"context_window": 200000, "max_output_tokens": 32000}
|
||||
}
|
||||
},
|
||||
"aliyun": {
|
||||
"models": [
|
||||
{"id": "qwen3.9-plus", "reasoning": true, "input": ["text", "image"],
|
||||
"context_window": 1000000, "max_output_tokens": 65536,
|
||||
"compat": {"thinking_always_send": true, "thinking_disable_on_non_stream": true}}
|
||||
]
|
||||
},
|
||||
"lab-vllm": {
|
||||
"name": "Lab vLLM",
|
||||
"names": {"zh-CN": "实验室 vLLM"},
|
||||
"description": "Self-hosted vLLM cluster",
|
||||
"api": "openai-completions",
|
||||
"base_url": "http://vllm.lab.internal:8000/v1",
|
||||
"requires_auth": false,
|
||||
"model_types": ["chat", "embedding"],
|
||||
"url_patterns": ["vllm.lab.internal"],
|
||||
"icon": "icons/lab-vllm.svg",
|
||||
"compat": {"thinking_format": "chat-template-kwargs", "max_tokens_field": "max_tokens"},
|
||||
"models": [
|
||||
{"id": "Qwen/Qwen3-32B", "reasoning": true, "context_window": 131072, "max_output_tokens": 16384},
|
||||
{"id": "BAAI/bge-m3", "type": "Embedding", "dimension": 1024}
|
||||
]
|
||||
},
|
||||
"claude-proxy": {
|
||||
"name": "Claude via proxy",
|
||||
"api": "anthropic-messages",
|
||||
"base_url": "https://claude-proxy.example.com/v1",
|
||||
"auth": "x-api-key",
|
||||
"api_key": "${CLAUDE_PROXY_KEY}",
|
||||
"models": [
|
||||
{"id": "claude-sonnet-5", "reasoning": true, "input": ["text", "image"],
|
||||
"context_window": 200000, "max_output_tokens": 64000,
|
||||
"compat": {"thinking_mode": "adaptive", "supports_effort": true}}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -56,6 +56,9 @@ services:
|
|||
# to config/builtin_models.yaml, edit it for your deployment, then
|
||||
# uncomment the line below. See docs/BUILTIN_MODELS.md.
|
||||
# - ./config/builtin_models.yaml:/app/config/builtin_models.yaml:ro
|
||||
# Optional: model catalog overlay (extra vendors / model overrides).
|
||||
# Copy config/models.json.example to config/models.json, then
|
||||
# - ./config/models.json:/app/config/models.json:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
|
||||
interval: 30s
|
||||
|
|
|
|||
|
|
@ -47,6 +47,9 @@ export interface CustomAgentConfig {
|
|||
temperature?: number;
|
||||
max_completion_tokens?: number; // 0 = 跟随系统默认(快速问答 2048;智能推理 4096,绑沙箱可写文件时 24576)。大于 0 为自定义上限
|
||||
thinking?: boolean; // 是否启用思考模式(支持扩展思考的模型)
|
||||
// 思考强度:off | auto | minimal | low | medium | high | xhigh | max。
|
||||
// 为空时退回 thinking 布尔值(true == auto,false == off)。
|
||||
reasoning_effort?: string;
|
||||
citation_enabled?: boolean; // 是否在最终回答中输出知识库/网页来源引用(默认开启)
|
||||
|
||||
// ===== Agent模式设置 =====
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { get, post, put } from '../../utils/request';
|
||||
import i18n from '@/i18n'
|
||||
import type { ModelCapabilities, ReasoningEffortLevel } from '../model'
|
||||
|
||||
const t = (key: string) => i18n.global.t(key)
|
||||
|
||||
|
|
@ -579,28 +580,163 @@ export function fabriTag(request: FabriTagRequest): Promise<FabriTagResponse> {
|
|||
});
|
||||
}
|
||||
|
||||
// 模型厂商信息类型
|
||||
export interface ModelProviderOption {
|
||||
value: string; // provider 标识符
|
||||
label: string; // 显示名称
|
||||
description: string; // 描述
|
||||
defaultUrls: Record<string, string>; // 按模型类型区分的默认 URL
|
||||
modelTypes: string[]; // 支持的模型类型
|
||||
// 厂商额外配置字段(Azure api_version、LKEAP secret_key 等)。
|
||||
// Mirrors internal/models/catalog.ExtraField.
|
||||
export interface ModelProviderExtraFieldOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
// 获取模型厂商列表
|
||||
/**
|
||||
* Renames the primary credential input for vendors whose API does not take a
|
||||
* plain API key. LKEAP and Volcengine sign their rerank requests with a
|
||||
* CAM / IAM key pair, so the first field is a SecretId / Access Key ID.
|
||||
* The vendor declares the wording so the editor needs no vendor table.
|
||||
*/
|
||||
export interface ModelProviderCredentialLabel {
|
||||
label: string;
|
||||
labels?: Record<string, string>;
|
||||
placeholder?: string;
|
||||
placeholders?: Record<string, string>;
|
||||
hint?: string;
|
||||
hints?: Record<string, string>;
|
||||
// Backend model types ("KnowledgeQA", "Rerank", ...); empty = all.
|
||||
model_types?: string[];
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelProviderExtraField {
|
||||
key: string;
|
||||
label: string;
|
||||
labels?: Record<string, string>;
|
||||
type: 'string' | 'number' | 'boolean' | 'select' | 'password' | string;
|
||||
required?: boolean;
|
||||
default?: string;
|
||||
placeholder?: string;
|
||||
options?: ModelProviderExtraFieldOption[];
|
||||
// Backend model types ("KnowledgeQA", "Embedding", "Rerank", "VLLM", "ASR"); empty = all.
|
||||
model_types?: string[];
|
||||
// Secret values are never echoed back; they are stored as the app_secret credential.
|
||||
secret?: boolean;
|
||||
}
|
||||
|
||||
// 厂商内置模型目录条目。Mirrors handler.ModelCatalogEntryDTO.
|
||||
export interface ModelCatalogEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
api?: string;
|
||||
reasoning?: boolean;
|
||||
input?: string[];
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
dimension?: number;
|
||||
thinking_levels?: ReasoningEffortLevel[];
|
||||
cost?: Record<string, unknown>;
|
||||
// Vendor page these facts came from, for the "read the docs" link.
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface ModelProviderThinking {
|
||||
format: string;
|
||||
levels: ReasoningEffortLevel[];
|
||||
}
|
||||
|
||||
// 模型厂商信息类型。Mirrors handler.ModelProviderDTO — the frontend keeps no
|
||||
// vendor table of its own; everything rendered for a vendor comes from here.
|
||||
export interface ModelProviderOption {
|
||||
value: string; // provider 标识符
|
||||
label: string; // 显示名称(英文 / 默认)
|
||||
labels?: Record<string, string>; // 按 locale 的显示名称
|
||||
description: string; // 描述
|
||||
descriptions?: Record<string, string>;
|
||||
website?: string;
|
||||
icon?: string; // data:image/svg+xml;base64,... 可直接用于 <img src>
|
||||
api?: string;
|
||||
auth?: string;
|
||||
requiresAuth?: boolean;
|
||||
defaultUrls: Record<string, string>; // 按模型类型区分的默认 URL
|
||||
modelTypes: string[]; // 支持的模型类型
|
||||
extraFields?: ModelProviderExtraField[];
|
||||
credentialLabels?: ModelProviderCredentialLabel[];
|
||||
models?: ModelCatalogEntry[];
|
||||
thinking?: ModelProviderThinking;
|
||||
order?: number;
|
||||
}
|
||||
|
||||
// 获取模型厂商列表。
|
||||
//
|
||||
// 失败时 reject(不再吞成空数组):唯一的调用方 stores/modelProviders 需要
|
||||
// 区分「后端真的没有厂商」和「这次请求挂了」——把失败当成空列表缓存下来,
|
||||
// 会让厂商下拉在整个会话里一直空着,直到用户刷新页面。
|
||||
export function listModelProviders(modelType?: string): Promise<ModelProviderOption[]> {
|
||||
const url = modelType
|
||||
? `/api/v1/models/providers?model_type=${encodeURIComponent(modelType)}`
|
||||
: '/api/v1/models/providers';
|
||||
return get(url).then((response: any) => {
|
||||
const data = response?.data;
|
||||
// Reject rather than coerce: the store distinguishes "this vendor list
|
||||
// is genuinely empty" (cacheable) from "the request did not produce a
|
||||
// list" (retry on the next mount). Returning [] here would make a
|
||||
// malformed 200 look like the former and blank the vendor dropdown and
|
||||
// every card icon for the rest of the session.
|
||||
if (!Array.isArray(data)) {
|
||||
return Promise.reject(new Error('model providers response is not a list'));
|
||||
}
|
||||
return data as ModelProviderOption[];
|
||||
});
|
||||
}
|
||||
|
||||
export interface ResolveModelCatalogParams {
|
||||
provider: string;
|
||||
model?: string;
|
||||
base_url?: string;
|
||||
model_type?: string;
|
||||
api?: string;
|
||||
thinking_control?: string;
|
||||
remote_model_name?: string;
|
||||
// Vendor-declared non-secret extra fields (Azure api_version, ...) are
|
||||
// forwarded by key so the preview resolves the same request the runtime
|
||||
// will make. The backend only accepts keys the vendor declares.
|
||||
[extraField: string]: string | undefined;
|
||||
}
|
||||
|
||||
// 目录解析结果。Mirrors handler.ResolveModelCatalog response data.
|
||||
export interface ResolvedModelCatalog {
|
||||
provider: string;
|
||||
api: string;
|
||||
// base_url and url are only returned to callers who may configure
|
||||
// integrations; a viewer gets the capability answer without the endpoint.
|
||||
base_url?: string;
|
||||
// url is the endpoint the row will actually call, and only vendors that
|
||||
// compute their own URL report one (Azure, whose api_version picks
|
||||
// between the v1 data plane and the dated deployments path).
|
||||
url?: string;
|
||||
remote_model: string;
|
||||
cataloged: boolean;
|
||||
model: Record<string, unknown>;
|
||||
capabilities: ModelCapabilities;
|
||||
}
|
||||
|
||||
// 解析模型的有效接入配置(协议、思考等级、上下文窗口等),供编辑器实时展示。
|
||||
export function resolveModelCatalog(params: ResolveModelCatalogParams): Promise<ResolvedModelCatalog> {
|
||||
const query = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value !== undefined && value !== null && String(value).trim() !== '') {
|
||||
query.set(key, String(value).trim());
|
||||
}
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = modelType
|
||||
? `/api/v1/models/providers?model_type=${encodeURIComponent(modelType)}`
|
||||
: '/api/v1/models/providers';
|
||||
get(url)
|
||||
get(`/api/v1/models/catalog/resolve?${query.toString()}`)
|
||||
.then((response: any) => {
|
||||
resolve(response.data || []);
|
||||
if (response?.success && response?.data) {
|
||||
resolve(response.data as ResolvedModelCatalog);
|
||||
} else {
|
||||
reject(new Error(response?.message || 'resolve failed'));
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error('Failed to list model providers:', error);
|
||||
resolve([]); // 失败时返回空数组,前端可以回退到默认值
|
||||
reject(error?.error || error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,45 @@ export * from './modelUsage'
|
|||
|
||||
const t = (key: string) => i18n.global.t(key)
|
||||
|
||||
// Protocol-neutral thinking level. Mirrors internal/models/api.ReasoningEffort.
|
||||
export type ReasoningEffortLevel =
|
||||
| 'off'
|
||||
| 'auto'
|
||||
| 'minimal'
|
||||
| 'low'
|
||||
| 'medium'
|
||||
| 'high'
|
||||
| 'xhigh'
|
||||
| 'max'
|
||||
|
||||
// Catalog view of a saved chat/VLM model. Mirrors internal/models/catalog.Capabilities.
|
||||
// thinking_levels: empty array = the model cannot be asked to think.
|
||||
export interface ModelCapabilities {
|
||||
provider: string;
|
||||
api: string;
|
||||
cataloged: boolean;
|
||||
reasoning: boolean;
|
||||
thinking_levels: ReasoningEffortLevel[];
|
||||
thinking_format: string;
|
||||
input?: string[];
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
max_tokens_field?: string;
|
||||
}
|
||||
|
||||
// Per-row override of a catalog entry. Mirrors internal/types.ModelSpecOverride.
|
||||
// compat is the flat, protocol-specific object documented in
|
||||
// internal/models/catalog/compat.go (free-form JSON).
|
||||
export interface ModelSpecOverride {
|
||||
api?: string;
|
||||
reasoning?: boolean;
|
||||
input?: string[];
|
||||
context_window?: number;
|
||||
max_output_tokens?: number;
|
||||
thinking_levels?: Record<string, string | null>;
|
||||
compat?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// 模型类型定义
|
||||
export interface ModelConfig {
|
||||
id?: string;
|
||||
|
|
@ -43,7 +82,12 @@ export interface ModelConfig {
|
|||
// kept on the type so create-mode payloads can still carry them in the
|
||||
// initial POST body.
|
||||
app_secret?: string;
|
||||
// Per-model catalog override (protocol, limits, protocol compat knobs).
|
||||
spec?: ModelSpecOverride;
|
||||
};
|
||||
// Catalog view (chat / VLM remote models only): protocol, thinking levels,
|
||||
// context window. Computed by the backend from provider + name + overrides.
|
||||
capabilities?: ModelCapabilities;
|
||||
is_default?: boolean;
|
||||
is_builtin?: boolean;
|
||||
status?: string;
|
||||
|
|
@ -171,6 +215,8 @@ export interface ModelDebugOptions {
|
|||
top_p?: number
|
||||
max_tokens?: number
|
||||
thinking?: boolean
|
||||
// Graded thinking level; takes precedence over the boolean when set.
|
||||
reasoning_effort?: ReasoningEffortLevel | string
|
||||
}
|
||||
|
||||
export interface ModelDebugResult {
|
||||
|
|
|
|||
|
|
@ -21,6 +21,16 @@
|
|||
border-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
// .wk-popover clips to its rounded corners with overflow:hidden, which also
|
||||
// cancels the overflow-y:auto TDesign puts on a select's list — the options
|
||||
// past the first screenful become unreachable rather than merely unseen.
|
||||
// Restore vertical scrolling for any select wearing this skin; the horizontal
|
||||
// axis stays clipped, which is what the rounded corners needed.
|
||||
.t-select__dropdown.wk-popover .t-popup__content {
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
// A quiet option surface, with the brand accent reserved for the small check.
|
||||
.t-select-option.t-is-selected:not(.t-is-disabled),
|
||||
.t-select-option.t-is-selected:not(.t-is-disabled):hover {
|
||||
|
|
|
|||
|
|
@ -138,12 +138,24 @@
|
|||
:autosize="{ minRows: 2, maxRows: 4 }"
|
||||
/>
|
||||
</div>
|
||||
<!-- 思考强度:由模型 capabilities.thinking_levels 决定;不能思考的模型不显示 -->
|
||||
<div v-if="supportsThinking" class="form-item">
|
||||
<label class="form-label">{{ $t('modelSettings.debug.thinking') }}</label>
|
||||
<div class="switch-field">
|
||||
<t-switch v-model="thinking" />
|
||||
<span class="form-desc form-desc--inline">{{ $t('modelSettings.debug.thinkingDesc') }}</span>
|
||||
</div>
|
||||
<label class="form-label">{{ $t('modelSettings.debug.reasoningEffort') }}</label>
|
||||
<t-select v-model="reasoningEffort" :popup-props="{ overlayClassName: 'reasoning-level-select-popup' }">
|
||||
<t-option v-for="level in reasoningOptions" :key="level" :value="level" :label="$t(levelLabelKey(level))"
|
||||
:show-overflow-tooltip="false">
|
||||
<div class="reasoning-level-option">
|
||||
<span class="reasoning-level-option__title">{{ $t(levelLabelKey(level)) }}</span>
|
||||
<span class="reasoning-level-option__hint">{{ $t(levelDescriptionKey(level)) }}</span>
|
||||
</div>
|
||||
</t-option>
|
||||
</t-select>
|
||||
<p class="form-desc">
|
||||
{{ $t('modelSettings.debug.reasoningEffortDesc') }}
|
||||
<template v-if="selectedModel.capabilities?.thinking_format">
|
||||
· <code>{{ selectedModel.capabilities.thinking_format }}</code>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
@ -204,7 +216,16 @@ import { copyWithToast } from '@/utils/clipboard'
|
|||
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
|
||||
import { debugModel, type ModelConfig, type ModelDebugResult } from '@/api/model'
|
||||
import { fileSizeVerification } from '@/utils'
|
||||
import { modelSupportsThinking } from '@/utils/thinkingControl'
|
||||
import { useModelProvidersStore } from '@/stores/modelProviders'
|
||||
import {
|
||||
clampLevel,
|
||||
levelDescriptionKey,
|
||||
levelEnablesThinking,
|
||||
levelLabelKey,
|
||||
modelCanThink,
|
||||
supportedLevels,
|
||||
type ReasoningLevel,
|
||||
} from '@/utils/reasoningEffort'
|
||||
import {
|
||||
formatContextWindow,
|
||||
modelHasContextWindow,
|
||||
|
|
@ -219,7 +240,8 @@ const emit = defineEmits<{
|
|||
(e: 'update:visible', value: boolean): void
|
||||
}>()
|
||||
|
||||
const { t, te } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
const providersStore = useModelProvidersStore()
|
||||
const drawerVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: value => emit('update:visible', value),
|
||||
|
|
@ -233,7 +255,7 @@ const input = ref('')
|
|||
const documentsText = ref('')
|
||||
const file = ref<File | null>(null)
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
const thinking = ref(false)
|
||||
const reasoningEffort = ref<ReasoningLevel>('off')
|
||||
const temperature = ref(0.7)
|
||||
const topP = ref(1)
|
||||
const maxTokens = ref(1024)
|
||||
|
|
@ -251,7 +273,10 @@ let runSequence = 0
|
|||
const selectedModel = computed(() => props.models.find(model => model.id === selectedModelId.value))
|
||||
const filteredModels = computed(() => props.models.filter(model => model.type === selectedModelType.value))
|
||||
const isChat = computed(() => selectedModel.value?.type === 'KnowledgeQA')
|
||||
const supportsThinking = computed(() => selectedModel.value ? modelSupportsThinking(selectedModel.value) : false)
|
||||
// Thinking is offered only when the catalog says the model can think
|
||||
// (remote chat models carry `capabilities` computed by the backend).
|
||||
const supportsThinking = computed(() => modelCanThink(selectedModel.value?.capabilities))
|
||||
const reasoningOptions = computed(() => supportedLevels(selectedModel.value?.capabilities))
|
||||
const needsFile = computed(() => ['VLLM', 'ASR'].includes(selectedModel.value?.type || ''))
|
||||
const documents = computed(() => documentsText.value.split('\n').map(item => item.trim()).filter(Boolean))
|
||||
const canRun = computed(() => {
|
||||
|
|
@ -289,8 +314,8 @@ const vendorLabel = (model: ModelConfig) => {
|
|||
const provider = model.parameters.provider || ''
|
||||
if (model.source === 'local') return 'Ollama'
|
||||
if (provider === 'generic') return t('modelSettings.source.custom')
|
||||
const key = `model.editor.providers.${provider}.label`
|
||||
return te(key) ? t(key) : provider || model.source
|
||||
if (!provider) return model.source
|
||||
return providersStore.labelFor(provider, String(locale.value || '')) || provider
|
||||
}
|
||||
|
||||
const inputLabel = computed(() => {
|
||||
|
|
@ -321,6 +346,9 @@ const formattedResult = computed(() => {
|
|||
})
|
||||
|
||||
const OBSERVATION_LABELS: Record<string, string> = {
|
||||
api: 'modelSettings.debug.metrics.api',
|
||||
thinking_format: 'modelSettings.debug.metrics.thinkingFormat',
|
||||
requested_reasoning_effort: 'modelSettings.debug.metrics.requestedReasoningEffort',
|
||||
dimension: 'modelSettings.debug.metrics.dimension',
|
||||
result_count: 'modelSettings.debug.metrics.resultCount',
|
||||
answer_characters: 'modelSettings.debug.metrics.answerChars',
|
||||
|
|
@ -332,7 +360,16 @@ const OBSERVATION_LABELS: Record<string, string> = {
|
|||
|
||||
const resultMetrics = computed(() => {
|
||||
if (!result.value?.observations) return []
|
||||
const obs = result.value.observations
|
||||
// Flatten the nested capabilities object the backend attaches so the
|
||||
// effective thinking encoding shows up next to the protocol.
|
||||
const raw = result.value.observations
|
||||
const caps = raw.capabilities as { thinking_format?: unknown } | undefined
|
||||
const obs: Record<string, unknown> = {
|
||||
...raw,
|
||||
...(caps && typeof caps === 'object' && caps.thinking_format !== undefined
|
||||
? { thinking_format: caps.thinking_format }
|
||||
: {}),
|
||||
}
|
||||
const keys = Object.keys(OBSERVATION_LABELS).filter(key => obs[key] !== undefined && obs[key] !== null)
|
||||
return keys.map(key => ({
|
||||
key,
|
||||
|
|
@ -345,6 +382,9 @@ const formatMetricValue = (key: string, value: unknown) => {
|
|||
if (typeof value === 'boolean') {
|
||||
return value ? t('common.yes') : t('common.no')
|
||||
}
|
||||
if (key === 'requested_reasoning_effort' && typeof value === 'string' && value) {
|
||||
return t(levelLabelKey(value))
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
|
|
@ -364,7 +404,10 @@ const ensureDefaultSelection = () => {
|
|||
}
|
||||
|
||||
watch(() => props.visible, visible => {
|
||||
if (visible) ensureDefaultSelection()
|
||||
if (visible) {
|
||||
ensureDefaultSelection()
|
||||
void providersStore.ensureLoaded('').catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
watch(availableModelTypes, () => {
|
||||
|
|
@ -372,8 +415,8 @@ watch(availableModelTypes, () => {
|
|||
})
|
||||
|
||||
watch(() => selectedModel.value?.id, () => {
|
||||
if (!supportsThinking.value) thinking.value = false
|
||||
})
|
||||
reasoningEffort.value = clampLevel(reasoningEffort.value, reasoningOptions.value)
|
||||
}, { immediate: true })
|
||||
|
||||
watch(() => selectedModel.value?.type, () => {
|
||||
file.value = null
|
||||
|
|
@ -417,9 +460,9 @@ const formatBytes = (bytes: number) => {
|
|||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
const historyLabel = (thinkingValue: boolean) => {
|
||||
if (supportsThinking.value) {
|
||||
return thinkingValue ? t('modelSettings.debug.thinkOn') : t('modelSettings.debug.thinkOff')
|
||||
const historyLabel = (level: ReasoningLevel | null) => {
|
||||
if (level) {
|
||||
return `${t('modelSettings.debug.reasoningEffort')}: ${t(levelLabelKey(level))}`
|
||||
}
|
||||
return t('modelSettings.debug.runLabel', { n: runSequence })
|
||||
}
|
||||
|
|
@ -428,7 +471,7 @@ const runDebug = async () => {
|
|||
if (!selectedModel.value?.id || !canRun.value || running.value) return
|
||||
running.value = true
|
||||
try {
|
||||
const thinkingValue = supportsThinking.value ? thinking.value : false
|
||||
const level: ReasoningLevel | null = supportsThinking.value ? reasoningEffort.value : null
|
||||
const nextResult = await debugModel(selectedModel.value.id, {
|
||||
input: input.value.trim(),
|
||||
documents: documents.value,
|
||||
|
|
@ -438,13 +481,14 @@ const runDebug = async () => {
|
|||
temperature: temperature.value,
|
||||
top_p: topP.value,
|
||||
max_tokens: maxTokens.value,
|
||||
thinking: thinkingValue,
|
||||
// reasoning_effort is authoritative; the boolean keeps older backends working.
|
||||
...(level ? { reasoning_effort: level, thinking: levelEnablesThinking(level) } : { thinking: false }),
|
||||
} : {},
|
||||
})
|
||||
result.value = nextResult
|
||||
history.value.unshift({
|
||||
id: ++runSequence,
|
||||
label: historyLabel(thinkingValue),
|
||||
label: historyLabel(level),
|
||||
result: nextResult,
|
||||
})
|
||||
history.value = history.value.slice(0, 6)
|
||||
|
|
@ -571,11 +615,9 @@ onBeforeUnmount(() => {
|
|||
}
|
||||
}
|
||||
|
||||
.switch-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 32px;
|
||||
.form-desc code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
|
||||
.file-picker {
|
||||
|
|
@ -714,3 +756,37 @@ onBeforeUnmount(() => {
|
|||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- 非 scoped:t-select popup 渲染到 body 下 -->
|
||||
<style lang="less">
|
||||
.reasoning-level-select-popup {
|
||||
padding: 4px;
|
||||
|
||||
.t-select-option {
|
||||
height: auto !important;
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
margin: 2px 0;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
|
||||
.reasoning-level-option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
line-height: 1.35;
|
||||
min-width: 0;
|
||||
|
||||
&__title {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&__hint {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -31,12 +31,25 @@ async function fixture(options: {
|
|||
edit?: boolean
|
||||
check?: (payload: any) => Promise<Result>
|
||||
save?: (payload: any) => Promise<void>
|
||||
providers?: any[]
|
||||
resolve?: (params: any) => Promise<any>
|
||||
} = {}) {
|
||||
const requests: any[] = []
|
||||
const saves: any[] = []
|
||||
const resolves: any[] = []
|
||||
const providers: any[] = options.providers || []
|
||||
const providersStore = {
|
||||
ensureLoaded: async () => providers,
|
||||
providersFor: () => providers,
|
||||
isLoading: () => false,
|
||||
providerById: (id: string) => providers.find((p) => p.value === id),
|
||||
iconFor: () => '',
|
||||
labelFor: (id: string) => id,
|
||||
descriptionFor: () => '',
|
||||
}
|
||||
const toasts: string[] = []
|
||||
const visibility: boolean[] = []
|
||||
const props = reactive({
|
||||
const props = reactive<{ visible: boolean; modelType: string; modelData: any }>({
|
||||
visible: false,
|
||||
modelType: options.type || 'chat',
|
||||
modelData: options.edit ? {
|
||||
|
|
@ -50,12 +63,12 @@ async function fixture(options: {
|
|||
}
|
||||
const exports: any = {}
|
||||
runInNewContext(compiled, {
|
||||
exports, URL, setInterval, clearInterval,
|
||||
exports, URL, setInterval, clearInterval, setTimeout, clearTimeout, JSON,
|
||||
window: { addEventListener() {}, removeEventListener() {} },
|
||||
console: { error() {}, debug() {}, log() {} },
|
||||
require(name: string) {
|
||||
if (name === 'vue') return require('vue')
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key, te: () => false }) }
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key, te: () => false, locale: { value: 'en-US' } }) }
|
||||
if (name === '@/stores/ui') return { useUIStore: () => ({}) }
|
||||
if (name === 'tdesign-vue-next') return {
|
||||
MessagePlugin: Object.fromEntries(['success', 'error', 'warning', 'info'].map(key => [key, (text: string) => toasts.push(text)])),
|
||||
|
|
@ -63,8 +76,14 @@ async function fixture(options: {
|
|||
if (name === '@/api/initialization') return {
|
||||
checkRemoteModel: check, testEmbeddingModel: check, checkRerankModel: check, checkASRModel: check,
|
||||
listModelProviders: async () => [], checkOllamaStatus: async () => ({ available: false }),
|
||||
resolveModelCatalog: async (params: any) => { resolves.push(params); return options.resolve ? options.resolve(params) : {
|
||||
provider: params.provider, api: 'openai-completions', base_url: params.base_url, remote_model: params.model,
|
||||
cataloged: false, model: {}, capabilities: { provider: params.provider, api: 'openai-completions', cataloged: false, reasoning: false, thinking_levels: [], thinking_format: 'none' },
|
||||
} },
|
||||
}
|
||||
if (name === '@/utils/thinkingControl') return require('../utils/thinkingControl.ts')
|
||||
if (name === '@/stores/modelProviders') return { useModelProvidersStore: () => providersStore }
|
||||
if (name === '@/stores/modelProvidersState') return require('../stores/modelProvidersState.ts')
|
||||
if (name === '@/utils/reasoningEffort') return require('../utils/reasoningEffort.ts')
|
||||
if (name === '@/utils/contextWindow') return require('../utils/contextWindow.ts')
|
||||
if (name === '@/components/modelEditorSourceState') return require('./modelEditorSourceState.ts')
|
||||
return { default: {} }
|
||||
|
|
@ -92,7 +111,7 @@ async function fixture(options: {
|
|||
Object.assign(vm.formData, { modelName: 'draft-model', baseUrl: 'https://example.com/v1', apiKey: options.edit ? '' : 'draft-key' })
|
||||
vm.formRef = { validate: async () => true }
|
||||
await nextTick()
|
||||
return { vm, props, requests, saves, toasts, visibility, close: () => app.unmount() }
|
||||
return { vm, props, requests, saves, toasts, visibility, resolves, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
for (const type of ['chat', 'embedding', 'rerank', 'vllm', 'asr']) {
|
||||
|
|
@ -323,3 +342,473 @@ for (const edit of [false, true]) {
|
|||
assert.equal(calls, 1, 'invalid drafts must not reach persistence')
|
||||
})
|
||||
}
|
||||
|
||||
// --- Catalog-driven editor behaviour -------------------------------------
|
||||
|
||||
// Objects built inside the vm context carry that realm's Object.prototype, so
|
||||
// strict deepEqual against literals fails; compare their JSON shape instead.
|
||||
const plain = (value: unknown) => JSON.parse(JSON.stringify(value))
|
||||
|
||||
const catalogProviders = [{
|
||||
value: 'lkeap', label: 'Tencent Cloud LKEAP', labels: { 'zh-CN': '腾讯云 LKEAP' }, description: '', order: 1,
|
||||
icon: 'data:image/svg+xml;base64,PHN2Zy8+',
|
||||
defaultUrls: { chat: 'https://api.lkeap.cloud.tencent.com/v1', rerank: 'https://lkeap.tencentcloudapi.com' },
|
||||
modelTypes: ['chat', 'rerank'],
|
||||
extraFields: [
|
||||
{ key: 'secret_key', label: 'Secret Key', type: 'password', required: true, model_types: ['Rerank'], secret: true },
|
||||
{ key: 'region', label: 'Region', type: 'string', default: 'ap-guangzhou', model_types: ['Rerank'] },
|
||||
{ key: 'api_version', label: 'API Version', type: 'string', default: '2024-10-21' },
|
||||
],
|
||||
models: [
|
||||
{ id: 'deepseek-v3.1', name: 'DeepSeek V3.1', type: 'chat', reasoning: true, input: ['text', 'image'], context_window: 128000, max_output_tokens: 8192, thinking_levels: ['off', 'auto'] },
|
||||
],
|
||||
thinking: { format: 'thinking.type', levels: ['off', 'auto'] },
|
||||
}]
|
||||
|
||||
test('vendor extra fields: defaults are pre-filled per model type, secrets go to app_secret, and both reach the connection test', async () => {
|
||||
const f = await fixture({ type: 'rerank', providers: catalogProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
f.vm.handleProviderChange('lkeap')
|
||||
await nextTick()
|
||||
assert.equal(f.vm.formData.baseUrl, 'https://lkeap.tencentcloudapi.com')
|
||||
assert.deepEqual(f.vm.plainExtraFields.map((x: any) => x.key), ['region', 'api_version'])
|
||||
assert.equal(f.vm.secretExtraField.key, 'secret_key')
|
||||
assert.equal(f.vm.formData.extraConfig.region, 'ap-guangzhou')
|
||||
assert.equal(f.vm.formData.extraConfig.api_version, '2024-10-21')
|
||||
assert.equal(f.vm.credentialFields.some((x: any) => x.key === 'app_secret'), true)
|
||||
|
||||
f.vm.formData.modelName = 'lke-reranker-base'
|
||||
f.vm.formData.appSecret = ' sk-secret '
|
||||
f.vm.setExtraConfig('region', ' ap-beijing ')
|
||||
await f.vm.checkRemoteAPI()
|
||||
assert.equal(f.requests[0].appSecret, 'sk-secret')
|
||||
assert.deepEqual(plain(f.requests[0].extraConfig), { region: 'ap-beijing', api_version: '2024-10-21' })
|
||||
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 1)
|
||||
assert.deepEqual(plain(f.saves[0].extraConfig), { region: 'ap-beijing', api_version: '2024-10-21' })
|
||||
assert.equal(f.saves[0].appSecret, ' sk-secret ')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('required vendor extra fields block saving until filled', async () => {
|
||||
const f = await fixture({ type: 'rerank', providers: catalogProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
f.vm.handleProviderChange('lkeap')
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'lke-reranker-base'
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 0, 'missing required secret_key must not save')
|
||||
assert.equal(f.toasts.length, 1)
|
||||
f.vm.formData.appSecret = 'sk'
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 1)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('picking a catalog model fills blank capability fields only', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
await nextTick()
|
||||
assert.deepEqual(f.vm.catalogModelOptions.map((o: any) => o.value), ['draft-model', 'deepseek-v3.1'])
|
||||
f.vm.formData.contextWindow = 32000
|
||||
f.vm.formData.modelName = 'deepseek-v3.1'
|
||||
f.vm.handleCatalogModelChange('deepseek-v3.1')
|
||||
assert.equal(f.vm.formData.contextWindow, 32000, 'user value wins')
|
||||
assert.equal(f.vm.formData.maxOutputTokens, 8192)
|
||||
assert.equal(f.vm.formData.supportsVision, true)
|
||||
f.vm.handleCatalogModelCreate(' my-custom-model ')
|
||||
assert.equal(f.vm.formData.modelName, 'my-custom-model')
|
||||
assert.equal(f.vm.catalogModelOptions[0].value, 'my-custom-model', 'free text stays selectable')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('resolve panel is refreshed once per 400ms burst of edits and ignored while hidden', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders })
|
||||
try {
|
||||
f.resolves.length = 0
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'deepseek-v3'
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'deepseek-v3.1'
|
||||
await nextTick()
|
||||
assert.equal(f.resolves.length, 0, 'debounced')
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
assert.equal(f.resolves.length, 1)
|
||||
assert.equal(f.resolves[0].model, 'deepseek-v3.1')
|
||||
assert.equal(f.resolves[0].model_type, 'chat')
|
||||
assert.equal(f.vm.resolved.api, 'openai-completions')
|
||||
f.props.visible = false
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'other'
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
assert.equal(f.resolves.length, 1, 'no resolve while the drawer is closed')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
for (const type of ['embedding', 'rerank', 'asr']) {
|
||||
test(`${type}: the catalog diagnosis panel is hidden and never fetched`, async () => {
|
||||
const f = await fixture({ type, providers: catalogProviders })
|
||||
try {
|
||||
f.resolves.length = 0
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'whatever'
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
assert.equal(f.vm.showResolvedPanel, false, 'protocol / thinking levels are meaningless here')
|
||||
assert.equal(f.vm.resolved, null)
|
||||
assert.equal(f.resolves.length, 0, 'no request for a panel that is not rendered')
|
||||
} finally { f.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test('vllm keeps the catalog diagnosis panel', async () => {
|
||||
const f = await fixture({ type: 'vllm', providers: catalogProviders })
|
||||
try {
|
||||
f.resolves.length = 0
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
await nextTick()
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
assert.equal(f.vm.showResolvedPanel, true)
|
||||
assert.equal(f.resolves.length, 1)
|
||||
assert.equal(f.resolves[0].model_type, 'vllm')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('an out-of-order resolve response cannot overwrite a newer one', async () => {
|
||||
const pendings: Array<ReturnType<typeof deferred<any>>> = []
|
||||
const f = await fixture({
|
||||
type: 'chat', providers: catalogProviders,
|
||||
resolve: (params: any) => {
|
||||
const slot = deferred<any>()
|
||||
pendings.push(slot)
|
||||
return slot.promise.then((value: any) => ({ ...value, remote_model: params.model }))
|
||||
},
|
||||
})
|
||||
try {
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
f.vm.formData.modelName = 'first-model'
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
f.vm.formData.modelName = 'second-model'
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
assert.equal(pendings.length, 2, 'both requests are in flight')
|
||||
pendings[1].resolve({ provider: 'lkeap', api: 'openai-completions', cataloged: true, capabilities: {} })
|
||||
await nextTick()
|
||||
pendings[0].resolve({ provider: 'lkeap', api: 'anthropic-messages', cataloged: false, capabilities: {} })
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
assert.equal(f.vm.resolved.remote_model, 'second-model', 'the stale answer must be dropped')
|
||||
assert.equal(f.vm.resolved.api, 'openai-completions')
|
||||
assert.equal(f.vm.resolving, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a resolve failure without a readable message shows no [object Object]', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders, resolve: async () => { throw { code: 500 } } })
|
||||
try {
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
await nextTick()
|
||||
await new Promise(resolve => setTimeout(resolve, 450))
|
||||
assert.equal(f.vm.resolveFailed, true)
|
||||
assert.equal(f.vm.resolveError, '', 'no detail beats a stringified object')
|
||||
assert.equal(f.vm.resolved, null)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a provider id missing from the catalog still shows in the selector', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'retired-vendor'
|
||||
await nextTick()
|
||||
assert.equal(f.vm.selectedProvider, undefined)
|
||||
assert.equal(f.vm.selectedProviderDisplayLabel, 'retired-vendor')
|
||||
assert.deepEqual(f.vm.plainExtraFields, [], 'an unknown vendor declares no extra fields')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('editing preserves extra_config keys the current vendor does not declare', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders })
|
||||
try {
|
||||
f.props.visible = false
|
||||
await nextTick()
|
||||
f.props.modelData = {
|
||||
id: 'legacy-extra', modelName: 'deepseek-v3.1', name: '', source: 'remote',
|
||||
baseUrl: 'https://api.lkeap.cloud.tencent.com/v1', provider: 'lkeap', isDefault: false,
|
||||
extraConfig: { api_version: 'v1', retired_knob: 'keep-me' },
|
||||
spec: { reasoning: true, context_window: 64000, compat: { max_tokens_field: 'max_tokens' } },
|
||||
}
|
||||
f.props.visible = true
|
||||
await nextTick()
|
||||
await nextTick()
|
||||
assert.deepEqual(plain(f.vm.formData.extraConfig), { api_version: 'v1', retired_knob: 'keep-me' })
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 1)
|
||||
assert.deepEqual(plain(f.saves[0].extraConfig), { api_version: 'v1', retired_knob: 'keep-me' })
|
||||
assert.deepEqual(
|
||||
plain(f.saves[0].spec),
|
||||
{ reasoning: true, context_window: 64000, compat: { max_tokens_field: 'max_tokens' } },
|
||||
'spec fields other than compat survive the round-trip',
|
||||
)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('advanced overrides: invalid compat JSON blocks save, valid JSON and protocol override are persisted', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'lkeap'
|
||||
f.vm.setExtraConfig('api', 'openai-responses')
|
||||
f.vm.setExtraConfig('remote_model_name', '')
|
||||
f.vm.formData.specCompat = '{ not json'
|
||||
await nextTick()
|
||||
assert.notEqual(f.vm.specCompatError, '')
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 0)
|
||||
assert.equal(f.vm.advancedOpen, true, 'the advanced section opens to show the error')
|
||||
f.vm.formData.specCompat = '["array"]'
|
||||
await nextTick()
|
||||
assert.equal(f.vm.specCompatError, 'model.editor.advanced.compat.mustBeObject')
|
||||
f.vm.formData.specCompat = '{"max_tokens_field": "max_tokens"}'
|
||||
await nextTick()
|
||||
assert.equal(f.vm.specCompatError, '')
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 1)
|
||||
assert.deepEqual(plain(f.saves[0].extraConfig), { api: 'openai-responses' })
|
||||
assert.equal(f.saves[0].specCompat, '{"max_tokens_field": "max_tokens"}')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('editing a legacy row keeps thinking_control until the user clears it', async () => {
|
||||
const f = await fixture({ type: 'chat', providers: catalogProviders })
|
||||
try {
|
||||
f.props.visible = false
|
||||
await nextTick()
|
||||
f.props.modelData = {
|
||||
id: 'legacy', modelName: 'qwen3-32b', name: '', source: 'remote', baseUrl: 'https://example.com/v1',
|
||||
provider: 'aliyun', isDefault: false, thinkingControl: 'enable_thinking',
|
||||
extraConfig: { thinking_control: 'enable_thinking', api_version: 'v1' },
|
||||
spec: { compat: { max_tokens_field: 'max_tokens' }, context_window: 1 },
|
||||
}
|
||||
f.props.visible = true
|
||||
await nextTick()
|
||||
await nextTick()
|
||||
assert.equal(f.vm.showLegacyThinkingControl, true)
|
||||
assert.equal(f.vm.formData.thinkingControl, 'enable_thinking')
|
||||
assert.deepEqual(plain(f.vm.formData.extraConfig), { api_version: 'v1' })
|
||||
assert.equal(f.vm.formData.specCompat, JSON.stringify({ max_tokens_field: 'max_tokens' }, null, 2))
|
||||
assert.deepEqual(plain(f.vm.buildExtraConfig()), { api_version: 'v1', thinking_control: 'enable_thinking' })
|
||||
f.vm.formData.thinkingControl = ''
|
||||
assert.equal(f.vm.showLegacyThinkingControl, true, 'select stays visible after clearing')
|
||||
assert.deepEqual(plain(f.vm.buildExtraConfig()), { api_version: 'v1' })
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('parent save serializes extra_config, spec.compat and max_output_tokens from the editor payload', async () => {
|
||||
const payloads: any[] = []
|
||||
const save = runInNewContext(saveScript + '\nhandleModelSave', {
|
||||
URL, console: { error() {} },
|
||||
currentModelType: { value: 'chat' }, editingModel: { value: null },
|
||||
getModelType: () => 'KnowledgeQA', t: (key: string) => key,
|
||||
createModel: async (data: any) => { payloads.push(data) }, updateModelAPI: async () => {},
|
||||
MessagePlugin: { success() {}, error() {}, warning() {} }, loadModels: async () => {},
|
||||
})
|
||||
await save({
|
||||
modelName: 'gpt-5', source: 'remote', baseUrl: 'https://api.openai.com/v1', provider: 'openai',
|
||||
extraConfig: { api: 'openai-responses', remote_model_name: ' gpt-5-2025 ', empty: ' ' },
|
||||
thinkingControl: '', specCompat: '{"max_tokens_field":"max_completion_tokens"}',
|
||||
spec: { compat: { old: true }, reasoning: true }, contextWindow: 400000, maxOutputTokens: 16384,
|
||||
})
|
||||
assert.equal(payloads.length, 1)
|
||||
const params = payloads[0].parameters
|
||||
assert.deepEqual(plain(params.extra_config), { api: 'openai-responses', remote_model_name: 'gpt-5-2025' })
|
||||
assert.deepEqual(plain(params.spec), { reasoning: true, compat: { max_tokens_field: 'max_completion_tokens' } })
|
||||
assert.equal(params.max_output_tokens, 16384)
|
||||
assert.equal(params.context_window, 400000)
|
||||
await assert.rejects(save({
|
||||
modelName: 'gpt-5', source: 'remote', baseUrl: 'https://api.openai.com/v1', specCompat: '[1]',
|
||||
}), /compat\.invalid/)
|
||||
})
|
||||
|
||||
// PUT /models/:id restores the stored extra_config when the field is absent
|
||||
// (internal/handler/model.go), so clearing the last key has to be sent as {}.
|
||||
test('parent save sends an empty extra_config so cleared vendor fields really clear', async () => {
|
||||
const updates: any[] = []
|
||||
const creates: any[] = []
|
||||
const save = runInNewContext(saveScript + '\nhandleModelSave', {
|
||||
URL, console: { error() {} },
|
||||
currentModelType: { value: 'chat' }, editingModel: { value: { id: 'saved-model' } },
|
||||
getModelType: () => 'KnowledgeQA', t: (key: string) => key,
|
||||
createModel: async (data: any) => { creates.push(data) },
|
||||
updateModelAPI: async (_id: string, data: any) => { updates.push(data) },
|
||||
MessagePlugin: { success() {}, error() {}, warning() {} }, loadModels: async () => {},
|
||||
})
|
||||
await save({
|
||||
modelName: 'gpt-5', source: 'remote', baseUrl: 'https://api.openai.com/v1', provider: 'openai',
|
||||
extraConfig: {}, thinkingControl: '',
|
||||
})
|
||||
assert.deepEqual(plain(updates[0].parameters.extra_config), {})
|
||||
// Local rows never edit extra_config here, so they keep the omit-and-preserve path.
|
||||
await save({ modelName: 'llama3', source: 'local', extraConfig: {}, thinkingControl: '' })
|
||||
assert.equal('extra_config' in updates[1].parameters, false)
|
||||
assert.equal(creates.length, 0)
|
||||
})
|
||||
|
||||
// Two vendors that share one model id (deepseek-v4-pro is sold by DeepSeek,
|
||||
// Aliyun, Volcengine and the gateways alike) and one that does not.
|
||||
const switchProviders = [
|
||||
{
|
||||
value: 'vendor-a', label: 'Vendor A', description: '', order: 1, modelTypes: ['chat'],
|
||||
defaultUrls: { chat: 'https://a.example.com/v1' },
|
||||
models: [
|
||||
{ id: 'shared-model', name: 'Shared', type: 'chat', context_window: 128000, max_output_tokens: 8192 },
|
||||
{ id: 'only-on-a', name: 'Only on A', type: 'chat', context_window: 1000000, input: ['text', 'image'] },
|
||||
],
|
||||
},
|
||||
{
|
||||
value: 'vendor-b', label: 'Vendor B', description: '', order: 2, modelTypes: ['chat'],
|
||||
defaultUrls: { chat: 'https://b.example.com/v1' },
|
||||
models: [
|
||||
{ id: 'shared-model', name: 'Shared', type: 'chat', context_window: 128000 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
test('switching vendor drops a model the new vendor does not serve, and what the catalog filled for it', async () => {
|
||||
const f = await fixture({ providers: switchProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'vendor-a'
|
||||
f.vm.handleProviderChange('vendor-a')
|
||||
await nextTick()
|
||||
// The select's v-model writes the name; the change handler fills the
|
||||
// capability fields from the catalog entry.
|
||||
f.vm.formData.modelName = 'only-on-a'
|
||||
f.vm.handleCatalogModelChange('only-on-a')
|
||||
await nextTick()
|
||||
assert.equal(f.vm.formData.modelName, 'only-on-a')
|
||||
// The catalog filled these, so they belong to that model.
|
||||
assert.equal(f.vm.formData.contextWindow, 1000000)
|
||||
assert.equal(f.vm.formData.supportsVision, true)
|
||||
|
||||
f.vm.formData.provider = 'vendor-b'
|
||||
f.vm.handleProviderChange('vendor-b')
|
||||
await nextTick()
|
||||
// Left in place the name would be saved verbatim and fail at first call.
|
||||
assert.equal(f.vm.formData.modelName, '')
|
||||
// A 1M window from another vendor's model is the exact mis-configuration
|
||||
// the field warns about, so it goes with the name.
|
||||
assert.equal(f.vm.formData.contextWindow, undefined)
|
||||
assert.equal(f.vm.formData.supportsVision, false)
|
||||
assert.equal(f.vm.formData.baseUrl, 'https://b.example.com/v1')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('switching vendor keeps a model both vendors serve, and never discards typed values', async () => {
|
||||
const f = await fixture({ providers: switchProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'vendor-a'
|
||||
f.vm.handleProviderChange('vendor-a')
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'shared-model'
|
||||
f.vm.handleCatalogModelChange('shared-model')
|
||||
await nextTick()
|
||||
// The operator overrides the catalog's number by hand.
|
||||
f.vm.formData.contextWindow = 64000
|
||||
f.vm.formData.maxOutputTokens = 4096
|
||||
|
||||
f.vm.formData.provider = 'vendor-b'
|
||||
f.vm.handleProviderChange('vendor-b')
|
||||
await nextTick()
|
||||
assert.equal(f.vm.formData.modelName, 'shared-model', 'both vendors serve it')
|
||||
assert.equal(f.vm.formData.contextWindow, 64000, 'a typed value is the operator‘s')
|
||||
assert.equal(f.vm.formData.maxOutputTokens, 4096)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('switching vendor clears a connection result that described the old one', async () => {
|
||||
const f = await fixture({ providers: switchProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'vendor-a'
|
||||
f.vm.handleProviderChange('vendor-a')
|
||||
await nextTick()
|
||||
f.vm.formData.modelName = 'shared-model'
|
||||
await f.vm.checkRemoteAPI()
|
||||
assert.equal(f.vm.remoteChecked, true)
|
||||
|
||||
f.vm.formData.provider = 'vendor-b'
|
||||
f.vm.handleProviderChange('vendor-b')
|
||||
await nextTick()
|
||||
assert.equal(f.vm.remoteChecked, false)
|
||||
assert.equal(f.vm.remoteMessage, '')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
// A VLM entry is a chat model that accepts images, so the backend — which
|
||||
// already scopes the provider list to the requested model type — returns it
|
||||
// typed "chat". Re-filtering on that type in the editor emptied the picker
|
||||
// for every vendor under 视觉.
|
||||
const vlmProviders = [{
|
||||
value: 'vendor-v', label: 'Vendor V', description: '', order: 1, modelTypes: ['chat', 'vllm'],
|
||||
defaultUrls: { chat: 'https://v.example.com/v1', vllm: 'https://v.example.com/v1' },
|
||||
models: [
|
||||
{ id: 'sees-images', name: 'Sees Images', type: 'chat', input: ['text', 'image'], context_window: 128000 },
|
||||
],
|
||||
}]
|
||||
|
||||
test('the vision picker lists the vendor models the backend scoped to it', async () => {
|
||||
const f = await fixture({ type: 'vllm', providers: vlmProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'vendor-v'
|
||||
f.vm.handleProviderChange('vendor-v')
|
||||
await nextTick()
|
||||
assert.deepEqual(f.vm.catalogModelOptions.map((o: any) => o.value), ['sees-images'])
|
||||
assert.equal(f.vm.catalogModelOptions[0].vision, true)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('rerank and asr pickers list their own entries', async () => {
|
||||
for (const [type, id] of [['rerank', 'the-reranker'], ['asr', 'the-transcriber']]) {
|
||||
const providers = [{
|
||||
value: 'vendor-t', label: 'Vendor T', description: '', order: 1, modelTypes: [type],
|
||||
defaultUrls: { [type]: 'https://t.example.com/v1' },
|
||||
models: [{ id, name: id, type }],
|
||||
}]
|
||||
const f = await fixture({ type, providers })
|
||||
try {
|
||||
f.vm.formData.provider = 'vendor-t'
|
||||
f.vm.handleProviderChange('vendor-t')
|
||||
await nextTick()
|
||||
assert.deepEqual(f.vm.catalogModelOptions.map((o: any) => o.value), [id], type)
|
||||
} finally { f.close() }
|
||||
}
|
||||
})
|
||||
|
||||
// TDesign hides a select's popup when it has no options, which takes the
|
||||
// creatable "create" row with it: the field accepts keystrokes but offers no
|
||||
// way to commit them, and a blur throws the text away. That is every vendor
|
||||
// with no catalog for the current type — 自定义 (OpenAI 兼容接口) above all.
|
||||
test('a vendor with no catalog falls back to a plain text field', async () => {
|
||||
const f = await fixture({ providers: switchProviders })
|
||||
try {
|
||||
f.vm.formData.provider = 'vendor-a'
|
||||
f.vm.handleProviderChange('vendor-a')
|
||||
await nextTick()
|
||||
assert.ok(f.vm.catalogModelOptions.length > 0, 'a catalogued vendor keeps the picker')
|
||||
|
||||
const f2 = await fixture({ providers: [{
|
||||
value: 'bare', label: 'Bare', description: '', order: 1, modelTypes: ['chat'],
|
||||
defaultUrls: { chat: 'https://bare.example.com/v1' }, models: [],
|
||||
}] })
|
||||
try {
|
||||
f2.vm.formData.provider = 'bare'
|
||||
f2.vm.handleProviderChange('bare')
|
||||
await nextTick()
|
||||
assert.equal(f2.vm.catalogModelOptions.length, 0)
|
||||
// Typing is the only way in, and it must survive as the model name.
|
||||
f2.vm.formData.modelName = 'my-own-model'
|
||||
await nextTick()
|
||||
assert.equal(f2.vm.formData.modelName, 'my-own-model')
|
||||
} finally { f2.close() }
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
|
|
|||
|
|
@ -330,20 +330,19 @@ const handleCancel = () => {
|
|||
gap: 10px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.setting-drawer__header-icon {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 9px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
|
||||
color: var(--td-brand-color);
|
||||
font-size: var(--app-text-xl);
|
||||
font-size: var(--app-text-lg);
|
||||
transition: background var(--app-motion-base) ease;
|
||||
}
|
||||
|
||||
|
|
@ -557,7 +556,10 @@ const handleCancel = () => {
|
|||
}
|
||||
|
||||
.t-drawer__header {
|
||||
padding: 14px 18px;
|
||||
// 72px 的抽屉头在一屏设置里太重:图标 32px、上下各 14px,再加标题与副标题
|
||||
// 两行。收到 60px(图标 28px、内边距 10px)够了,标题字号刻意不动——再小
|
||||
// 就和正文里的字段标签一样大,层级会塌。
|
||||
padding: 10px 18px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1114,6 +1114,8 @@ export default {
|
|||
enabled: 'Agent enabled'
|
||||
},
|
||||
editor: {
|
||||
reasoningEffortUnsupported: 'The selected model cannot think; every option except "Off" is ignored.',
|
||||
reasoningEffortAlwaysOn: 'The selected model always reasons and cannot be switched off; only the effort level can be changed.',
|
||||
createTitle: 'Create Agent',
|
||||
editTitle: 'Edit Agent',
|
||||
buttons: {
|
||||
|
|
@ -4593,6 +4595,28 @@ export default {
|
|||
}
|
||||
},
|
||||
model: {
|
||||
reasoning: {
|
||||
levels: {
|
||||
off: 'Off',
|
||||
auto: 'Auto',
|
||||
minimal: 'Minimal',
|
||||
low: 'Low',
|
||||
medium: 'Medium',
|
||||
high: 'High',
|
||||
xhigh: 'Extra high',
|
||||
max: 'Max',
|
||||
},
|
||||
levelDescriptions: {
|
||||
off: 'Thinking disabled; no thinking parameters are sent',
|
||||
auto: 'Vendor default intensity; the model decides how much to think',
|
||||
minimal: 'Least thinking, fastest responses',
|
||||
low: 'Light thinking',
|
||||
medium: 'Moderate thinking',
|
||||
high: 'Deep thinking, slower responses',
|
||||
xhigh: 'Very high thinking budget (select models only)',
|
||||
max: 'Maximum thinking budget (select models only)',
|
||||
},
|
||||
},
|
||||
modelName: 'Model Name',
|
||||
defaultTag: 'Default',
|
||||
addModelInSettings: 'Go to global settings to add models',
|
||||
|
|
@ -4600,6 +4624,53 @@ export default {
|
|||
selectModelPlaceholder: 'Select a model',
|
||||
searchPlaceholder: 'Search models...',
|
||||
editor: {
|
||||
maxOutputTokensLabel: 'Max output tokens',
|
||||
maxOutputTokensPlaceholder: 'Leave empty for the catalog default',
|
||||
maxOutputTokensDesc: 'Output cap per response. Leave empty to use the catalog default for this model.',
|
||||
catalog: {
|
||||
reasoning: 'Reasoning',
|
||||
vision: 'Vision',
|
||||
hint: 'Pick a model from the vendor catalog or type a custom model name.',
|
||||
},
|
||||
resolved: {
|
||||
title: 'How this model is called',
|
||||
empty: 'Fill in the vendor and model name to see how this model will be called',
|
||||
failed: 'Resolve failed',
|
||||
protocol: 'Request protocol',
|
||||
catalog: 'Capabilities from',
|
||||
catalogedYes: 'Built-in model profile',
|
||||
catalogedNo: 'Vendor defaults (model not in the catalog)',
|
||||
endpoint: 'Request endpoint',
|
||||
thinkingFormat: 'Thinking switch sent as',
|
||||
thinkingLevels: 'Selectable effort',
|
||||
noThinking: 'This model cannot think',
|
||||
},
|
||||
advanced: {
|
||||
toggle: 'Advanced',
|
||||
api: {
|
||||
label: 'Protocol override',
|
||||
auto: 'Auto (from vendor / URL)',
|
||||
desc: 'Force a request protocol; normally unnecessary.',
|
||||
},
|
||||
remoteModelName: {
|
||||
label: 'Remote model name',
|
||||
placeholder: 'Leave empty to use the model name',
|
||||
desc: 'Model id actually sent to the vendor when it differs from the name above.',
|
||||
},
|
||||
legacyThinking: {
|
||||
label: 'Thinking parameter format (legacy)',
|
||||
catalog: 'Follow catalog default (recommended)',
|
||||
none: 'Do not send thinking fields',
|
||||
desc: 'This model still carries a legacy thinking_control setting. Choose "Follow catalog default" to let the catalog decide.',
|
||||
},
|
||||
compat: {
|
||||
label: 'Protocol compat override (JSON)',
|
||||
placeholder: "{'{'} \"max_tokens_field\": \"max_tokens\" {'}'}",
|
||||
desc: 'Compat switches merged over the catalog defaults for the resolved protocol; see catalog/compat.go on the backend. Leave empty for no override.',
|
||||
invalid: 'Invalid JSON',
|
||||
mustBeObject: 'Must be a JSON object',
|
||||
},
|
||||
},
|
||||
addTitle: 'Add Model',
|
||||
editTitle: 'Edit Model',
|
||||
sectionType: 'Model Type',
|
||||
|
|
@ -4634,23 +4705,6 @@ export default {
|
|||
baseUrlPlaceholderAsr: 'e.g. https://api.openai.com/v1',
|
||||
apiKeyOptional: 'API Key (optional)',
|
||||
apiKeyPlaceholder: 'Enter API Key',
|
||||
lkeap: {
|
||||
secretIdLabel: 'SecretId',
|
||||
secretIdPlaceholder: 'Tencent Cloud API SecretId',
|
||||
secretKeyLabel: 'SecretKey',
|
||||
secretKeyPlaceholder: 'Tencent Cloud API SecretKey',
|
||||
regionLabel: 'Region',
|
||||
regionPlaceholder: 'ap-guangzhou',
|
||||
regionDesc: 'RunRerank supports ap-beijing, ap-guangzhou, etc. Default: ap-guangzhou',
|
||||
rerankCredentialHint: 'Rerank uses Tencent Cloud API signature (not the OpenAI-style LKEAP API key). Create SecretId/SecretKey in the CAM console.'
|
||||
},
|
||||
volcengine: {
|
||||
accessKeyLabel: 'Access Key ID',
|
||||
accessKeyPlaceholder: 'Volcengine Access Key ID',
|
||||
secretKeyLabel: 'Secret Access Key',
|
||||
secretKeyPlaceholder: 'Volcengine Secret Access Key',
|
||||
rerankCredentialHint: 'Rerank uses VikingDB AK/SK signing, not an Ark API key. Recommended model: doubao-seed-rerank.'
|
||||
},
|
||||
customHeadersLabel: 'Custom Request Headers (optional)',
|
||||
customHeadersDesc: 'Extra HTTP headers appended to requests to the remote model API (e.g. for enterprise gateway auth or tracing). Reserved headers like Authorization / Content-Type are ignored.',
|
||||
customHeadersAdd: 'Add Header',
|
||||
|
|
@ -4678,26 +4732,6 @@ export default {
|
|||
maxConcurrencyLabel: 'Background concurrency limit',
|
||||
maxConcurrencyPlaceholder: '0 = use global default',
|
||||
maxConcurrencyDesc: 'Caps concurrent background (ingestion/enrichment) calls to this model, shared per model across all replicas. 0 or empty falls back to the global default; interactive chat is never affected.',
|
||||
thinkingControlLabel: 'Thinking mode request format',
|
||||
thinkingControlDesc: 'Controls how the agent’s “Thinking mode” on/off switch is written to the API. We pre-select based on vendor/model when possible; change it to match your API docs. With “Do not send”, the agent Thinking mode switch has no effect.',
|
||||
thinkingControl: {
|
||||
none: {
|
||||
label: 'Do not send thinking fields',
|
||||
hint: 'Agent “Thinking mode” switch has no effect; thinking parameters are not sent in requests'
|
||||
},
|
||||
chatTemplateKwargs: {
|
||||
label: 'chat_template_kwargs',
|
||||
hint: 'Custom OpenAI-compatible gateways, NVIDIA NIM, vLLM / local Qwen'
|
||||
},
|
||||
enableThinking: {
|
||||
label: 'enable_thinking',
|
||||
hint: 'Alibaba DashScope: qwen3, qwen-plus, qwen-max, qwen-turbo'
|
||||
},
|
||||
thinkingType: {
|
||||
label: 'thinking.type',
|
||||
hint: 'Volcengine Ark; Tencent LKEAP (DeepSeek V3, etc.; default for LKEAP; use “Do not send” for R1)'
|
||||
}
|
||||
},
|
||||
dimensionHint: 'Model selected. Click "Detect Dimension" to fetch the vector dimension automatically.',
|
||||
loadModelListFailed: 'Failed to load model list',
|
||||
listRefreshed: 'List refreshed',
|
||||
|
|
@ -4719,6 +4753,7 @@ export default {
|
|||
ollamaNotSupportRerank: 'Ollama does not support ReRank models, please use a remote API instead',
|
||||
goToOllamaSettings: 'Open Settings',
|
||||
validation: {
|
||||
extraFieldRequired: 'Please fill in {name}',
|
||||
modelNameRequired: 'Please enter the model name',
|
||||
modelNameEmpty: 'Model name cannot be empty',
|
||||
modelNameMax: 'Model name cannot exceed 100 characters',
|
||||
|
|
@ -4728,112 +4763,7 @@ export default {
|
|||
},
|
||||
providerLabel: 'Provider',
|
||||
providerPlaceholder: 'Select model provider',
|
||||
providers: {
|
||||
openai: {
|
||||
label: 'OpenAI',
|
||||
description: 'gpt-5.2, gpt-5-mini, etc.'
|
||||
},
|
||||
anthropic: {
|
||||
label: 'Anthropic',
|
||||
description: 'Claude models via native Anthropic Messages API'
|
||||
},
|
||||
azure_openai: {
|
||||
label: 'Azure OpenAI',
|
||||
description: 'OpenAI service hosted on Microsoft Azure'
|
||||
},
|
||||
aliyun: {
|
||||
label: 'Aliyun DashScope',
|
||||
description: 'qwen-plus, tongyi-embedding-vision-plus, qwen3-rerank, etc.'
|
||||
},
|
||||
zhipu: {
|
||||
label: 'Zhipu BigModel',
|
||||
description: 'glm-4.7, embedding-3, rerank, etc.'
|
||||
},
|
||||
openrouter: {
|
||||
label: 'OpenRouter',
|
||||
description: 'openai/gpt-5.2-chat, google/gemini-3-flash-preview, etc.'
|
||||
},
|
||||
litellm: {
|
||||
label: 'LiteLLM',
|
||||
description: 'Self-hosted proxy to 100+ providers (OpenAI, Anthropic, Gemini, Bedrock, etc.). Replace the placeholder URL; loopback hosts need SSRF_WHITELIST.'
|
||||
},
|
||||
requesty: {
|
||||
label: 'Requesty',
|
||||
description: 'openai/gpt-4o-mini, anthropic/claude-sonnet-4-5, etc.'
|
||||
},
|
||||
generic: {
|
||||
label: 'Custom (OpenAI-compatible)',
|
||||
description: 'Generic API endpoint'
|
||||
},
|
||||
siliconflow: {
|
||||
label: 'SiliconFlow',
|
||||
description: 'deepseek-ai/DeepSeek-V3.1, etc.'
|
||||
},
|
||||
jina: {
|
||||
label: 'Jina',
|
||||
description: 'jina-clip-v1, jina-embeddings-v2-base-zh, etc.'
|
||||
},
|
||||
volcengine: {
|
||||
label: 'Volcengine',
|
||||
description: 'doubao-1-5-pro-32k-250115, doubao-embedding-vision-250615, etc.'
|
||||
},
|
||||
deepseek: {
|
||||
label: 'DeepSeek',
|
||||
description: 'deepseek-chat, deepseek-reasoner, etc.'
|
||||
},
|
||||
hunyuan: {
|
||||
label: 'Hunyuan',
|
||||
description: 'hunyuan-pro, hunyuan-standard, hunyuan-embedding, etc.'
|
||||
},
|
||||
minimax: {
|
||||
label: 'MiniMax',
|
||||
description: 'MiniMax-M3, MiniMax-M2.7, MiniMax-M2.7-highspeed, etc.'
|
||||
},
|
||||
mimo: {
|
||||
label: 'MiMo',
|
||||
description: 'mimo-v2-flash'
|
||||
},
|
||||
gemini: {
|
||||
label: 'Google Gemini',
|
||||
description: 'gemini-3-flash-preview, gemini-2.5-pro, etc.'
|
||||
},
|
||||
gpustack: {
|
||||
label: 'GPUStack',
|
||||
description: 'Choose your deployed model on GPUStack'
|
||||
},
|
||||
modelscope: {
|
||||
label: 'ModelScope',
|
||||
description: 'Qwen/Qwen3-8B, Qwen/Qwen3-Embedding-8B, etc.'
|
||||
},
|
||||
qiniu: {
|
||||
label: 'Qiniu Cloud',
|
||||
description: 'deepseek/deepseek-v3.2-251201, z-ai/glm-4.7, etc.'
|
||||
},
|
||||
moonshot: {
|
||||
label: 'Moonshot',
|
||||
description: 'kimi-k2-turbo-preview, moonshot-v1-8k-vision-preview, etc.'
|
||||
},
|
||||
qianfan: {
|
||||
label: 'Baidu Qianfan',
|
||||
description: 'ernie-5.0-thinking-preview, embedding-v1, bce-reranker-base, etc.'
|
||||
},
|
||||
longcat: {
|
||||
label: 'LongCat AI',
|
||||
description: 'LongCat-Flash-Chat, LongCat-Flash-Thinking, etc.'
|
||||
},
|
||||
lkeap: {
|
||||
label: 'Tencent Cloud LKEAP',
|
||||
description: 'DeepSeek-R1, DeepSeek-V3, lke-reranker-base, etc.'
|
||||
},
|
||||
nvidia: {
|
||||
label: 'NVIDIA',
|
||||
description: 'deepseek-ai-deepseek-v3_1, nv-embed-v1, rerank-qa-mistral-4b, etc.'
|
||||
},
|
||||
novita: {
|
||||
label: 'Novita AI',
|
||||
description: 'moonshotai/kimi-k2.5, zai-org/glm-5, minimax/minimax-m2.7, qwen/qwen3-embedding-0.6b, etc.'
|
||||
}
|
||||
}
|
||||
providerDocs: 'Read the {provider} model docs',
|
||||
},
|
||||
builtinTag: 'Built-in'
|
||||
},
|
||||
|
|
@ -5199,6 +5129,8 @@ export default {
|
|||
}
|
||||
},
|
||||
debug: {
|
||||
reasoningEffort: 'Reasoning effort',
|
||||
reasoningEffortDesc: 'Sends reasoning_effort using the levels reported by the model catalog',
|
||||
title: 'Model Test',
|
||||
description: 'Send a real request using saved model settings. Save pending edits before testing here.',
|
||||
groupModel: 'Select model',
|
||||
|
|
@ -5221,15 +5153,11 @@ export default {
|
|||
audioFile: 'Audio file',
|
||||
chooseFile: 'Choose file',
|
||||
parameters: 'Request parameters',
|
||||
thinking: 'Thinking mode',
|
||||
thinkingDesc: 'Only applies to models that support thinking',
|
||||
systemPrompt: 'System Prompt',
|
||||
systemPromptPlaceholder: 'Optional system prompt',
|
||||
run: 'Run test',
|
||||
copyResult: 'Copy result',
|
||||
history: 'History',
|
||||
thinkOn: 'Thinking on',
|
||||
thinkOff: 'Thinking off',
|
||||
runLabel: 'Run #{n}',
|
||||
success: 'Request succeeded',
|
||||
failed: 'Request failed',
|
||||
|
|
@ -5237,6 +5165,9 @@ export default {
|
|||
requestPreview: 'Request preview',
|
||||
requestFailed: 'Model test request failed',
|
||||
metrics: {
|
||||
api: 'Protocol',
|
||||
thinkingFormat: 'Thinking format',
|
||||
requestedReasoningEffort: 'Requested effort',
|
||||
dimension: 'Dimensions',
|
||||
resultCount: 'Result count',
|
||||
answerChars: 'Answer chars',
|
||||
|
|
|
|||
|
|
@ -1114,6 +1114,8 @@ export default {
|
|||
enabled: 'エージェントを有効化しました'
|
||||
},
|
||||
editor: {
|
||||
reasoningEffortUnsupported: '選択中のモデルは思考に対応していません。「オフ」以外は無視されます。',
|
||||
reasoningEffortAlwaysOn: '選択中のモデルは常に思考します。オフにはできず、強度のみ調整できます。',
|
||||
createTitle: 'エージェントを作成',
|
||||
editTitle: 'エージェントを編集',
|
||||
buttons: {
|
||||
|
|
@ -4593,6 +4595,28 @@ export default {
|
|||
}
|
||||
},
|
||||
model: {
|
||||
reasoning: {
|
||||
levels: {
|
||||
off: 'オフ',
|
||||
auto: '自動',
|
||||
minimal: '最小',
|
||||
low: '低',
|
||||
medium: '中',
|
||||
high: '高',
|
||||
xhigh: '超高',
|
||||
max: '最大',
|
||||
},
|
||||
levelDescriptions: {
|
||||
off: '思考を無効化し、思考パラメータを送信しません',
|
||||
auto: 'ベンダー既定の強度。思考量はモデルが決めます',
|
||||
minimal: '最小限の思考、最速の応答',
|
||||
low: '軽い思考',
|
||||
medium: '中程度の思考',
|
||||
high: '深い思考、応答は遅くなります',
|
||||
xhigh: '超高の思考予算(一部モデルのみ)',
|
||||
max: '最大の思考予算(一部モデルのみ)',
|
||||
},
|
||||
},
|
||||
modelName: 'モデル名',
|
||||
defaultTag: 'デフォルト',
|
||||
addModelInSettings: 'モデルを追加するにはシステム設定を開いてください',
|
||||
|
|
@ -4600,6 +4624,53 @@ export default {
|
|||
selectModelPlaceholder: 'モデルを選択',
|
||||
searchPlaceholder: 'モデルを検索...',
|
||||
editor: {
|
||||
maxOutputTokensLabel: '最大出力トークン',
|
||||
maxOutputTokensPlaceholder: '空欄でカタログ既定値',
|
||||
maxOutputTokensDesc: '1 回の応答の出力上限。空欄ならこのモデルのカタログ既定値を使用します。',
|
||||
catalog: {
|
||||
reasoning: '推論',
|
||||
vision: '画像',
|
||||
hint: 'ベンダーのカタログから選ぶか、カスタムのモデル名を入力できます。',
|
||||
},
|
||||
resolved: {
|
||||
title: '実際の呼び出し方',
|
||||
empty: 'ベンダーとモデル名を入力すると、このモデルの呼び出し方を表示します',
|
||||
failed: '解決に失敗',
|
||||
protocol: 'リクエストプロトコル',
|
||||
catalog: '能力の取得元',
|
||||
catalogedYes: '内蔵モデルプロファイル',
|
||||
catalogedNo: 'ベンダー既定(カタログ未収録)',
|
||||
endpoint: 'リクエスト先',
|
||||
thinkingFormat: '思考切替の送り方',
|
||||
thinkingLevels: '選択できる思考強度',
|
||||
noThinking: 'このモデルは思考できません',
|
||||
},
|
||||
advanced: {
|
||||
toggle: '詳細設定',
|
||||
api: {
|
||||
label: 'プロトコル上書き',
|
||||
auto: '自動(ベンダー / URL から推定)',
|
||||
desc: 'リクエストプロトコルを強制します。通常は変更不要です。',
|
||||
},
|
||||
remoteModelName: {
|
||||
label: 'リモートモデル名',
|
||||
placeholder: '空欄でモデル名と同じ',
|
||||
desc: '上のモデル名と異なる場合に、実際にベンダーへ送るモデル ID。',
|
||||
},
|
||||
legacyThinking: {
|
||||
label: '思考パラメータ形式(旧設定)',
|
||||
catalog: 'カタログ既定に従う(推奨)',
|
||||
none: '思考パラメータを送信しない',
|
||||
desc: 'このモデルには旧版の thinking_control 設定が残っています。「カタログ既定に従う」を選ぶとカタログが決定します。',
|
||||
},
|
||||
compat: {
|
||||
label: 'プロトコル互換上書き(JSON)',
|
||||
placeholder: "{'{'} \"max_tokens_field\": \"max_tokens\" {'}'}",
|
||||
desc: '解決されたプロトコルのカタログ既定値に上書きマージされる互換スイッチ。バックエンドの catalog/compat.go を参照。空欄で上書きなし。',
|
||||
invalid: 'JSON が不正です',
|
||||
mustBeObject: 'JSON オブジェクトが必要です',
|
||||
},
|
||||
},
|
||||
addTitle: 'モデルを追加',
|
||||
editTitle: 'モデルを編集',
|
||||
sectionType: 'モデルタイプ',
|
||||
|
|
@ -4634,23 +4705,6 @@ export default {
|
|||
baseUrlPlaceholderAsr: '例: https://api.openai.com/v1',
|
||||
apiKeyOptional: 'APIキー(任意)',
|
||||
apiKeyPlaceholder: 'APIキーを入力してください',
|
||||
lkeap: {
|
||||
secretIdLabel: 'SecretId',
|
||||
secretIdPlaceholder: 'Tencent Cloud APIのSecretId',
|
||||
secretKeyLabel: 'SecretKey',
|
||||
secretKeyPlaceholder: 'Tencent Cloud APIのSecretKey',
|
||||
regionLabel: 'リージョン',
|
||||
regionPlaceholder: 'ap-guangzhou',
|
||||
regionDesc: 'RunRerankはap-beijing、ap-guangzhouなどに対応しています。デフォルト値: ap-guangzhou',
|
||||
rerankCredentialHint: 'リランクはTencent CloudのAPI署名(OpenAI形式のLKEAP APIキーではありません)を使用します。SecretId/SecretKeyはCAMコンソールで作成してください。'
|
||||
},
|
||||
volcengine: {
|
||||
accessKeyLabel: 'Access Key ID',
|
||||
accessKeyPlaceholder: 'VolcengineのAccess Key ID',
|
||||
secretKeyLabel: 'Secret Access Key',
|
||||
secretKeyPlaceholder: 'VolcengineのSecret Access Key',
|
||||
rerankCredentialHint: 'リランクはArkのAPIキーではなく、VikingDBのAK/SK署名を使用します。推奨モデル: doubao-seed-rerank。'
|
||||
},
|
||||
customHeadersLabel: 'カスタムリクエストヘッダー(任意)',
|
||||
customHeadersDesc: 'リモートモデルAPIへのリクエストに追加するHTTPヘッダーです(企業ゲートウェイの認証やトレースなどに利用)。Authorization / Content-Typeなどの予約ヘッダーは無視されます。',
|
||||
customHeadersAdd: 'ヘッダーを追加',
|
||||
|
|
@ -4678,26 +4732,6 @@ export default {
|
|||
maxConcurrencyLabel: 'バックグラウンドの並列実行上限',
|
||||
maxConcurrencyPlaceholder: '0 = グローバルのデフォルト値を使用',
|
||||
maxConcurrencyDesc: 'このモデルへのバックグラウンド(取り込み・エンリッチメント)呼び出しの並列数を制限します。モデルごとにすべてのレプリカで共有されます。0または空欄の場合はグローバルのデフォルト値が使われます。対話型のチャットには影響しません。',
|
||||
thinkingControlLabel: '思考モードのリクエスト形式',
|
||||
thinkingControlDesc: 'エージェントの「思考モード」のオン/オフをAPIにどう送信するかを設定します。可能な場合はベンダやモデルに応じて自動選択されます。お使いのAPIドキュメントに合わせて変更してください。「送信しない」を選ぶと、エージェントの思考モードの切り替えは効果がありません。',
|
||||
thinkingControl: {
|
||||
none: {
|
||||
label: '思考関連のフィールドを送信しない',
|
||||
hint: 'エージェントの「思考モード」の切り替えは効果がなく、リクエストに思考パラメータは送信されません'
|
||||
},
|
||||
chatTemplateKwargs: {
|
||||
label: 'chat_template_kwargs',
|
||||
hint: 'OpenAI互換のカスタムゲートウェイ、NVIDIA NIM、vLLM / ローカルのQwen'
|
||||
},
|
||||
enableThinking: {
|
||||
label: 'enable_thinking',
|
||||
hint: 'Alibaba DashScope: qwen3、qwen-plus、qwen-max、qwen-turbo'
|
||||
},
|
||||
thinkingType: {
|
||||
label: 'thinking.type',
|
||||
hint: 'Volcengine Ark、Tencent LKEAP(DeepSeek V3など。LKEAPのデフォルト値。R1では「送信しない」を使用)'
|
||||
}
|
||||
},
|
||||
dimensionHint: 'モデルを選択しました。「次元数を検出」をクリックするとベクトル次元数を自動取得できます。',
|
||||
loadModelListFailed: 'モデル一覧の読み込みに失敗しました',
|
||||
listRefreshed: '一覧を更新しました',
|
||||
|
|
@ -4719,6 +4753,7 @@ export default {
|
|||
ollamaNotSupportRerank: 'Ollamaはリランクモデルに対応していません。リモートAPIを使用してください',
|
||||
goToOllamaSettings: '設定を開く',
|
||||
validation: {
|
||||
extraFieldRequired: '{name} を入力してください',
|
||||
modelNameRequired: 'モデル名を入力してください',
|
||||
modelNameEmpty: 'モデル名は空にできません',
|
||||
modelNameMax: 'モデル名は100文字以内で入力してください',
|
||||
|
|
@ -4728,112 +4763,7 @@ export default {
|
|||
},
|
||||
providerLabel: 'プロバイダ',
|
||||
providerPlaceholder: 'モデルプロバイダを選択',
|
||||
providers: {
|
||||
openai: {
|
||||
label: 'OpenAI',
|
||||
description: 'gpt-5.2、gpt-5-miniなど'
|
||||
},
|
||||
anthropic: {
|
||||
label: 'Anthropic',
|
||||
description: 'ネイティブのAnthropic Messages API経由のClaudeモデル'
|
||||
},
|
||||
azure_openai: {
|
||||
label: 'Azure OpenAI',
|
||||
description: 'Microsoft AzureでホストされるOpenAIサービス'
|
||||
},
|
||||
aliyun: {
|
||||
label: 'Aliyun DashScope',
|
||||
description: 'qwen-plus、tongyi-embedding-vision-plus、qwen3-rerankなど'
|
||||
},
|
||||
zhipu: {
|
||||
label: 'Zhipu BigModel',
|
||||
description: 'glm-4.7、embedding-3、rerankなど'
|
||||
},
|
||||
openrouter: {
|
||||
label: 'OpenRouter',
|
||||
description: 'openai/gpt-5.2-chat、google/gemini-3-flash-previewなど'
|
||||
},
|
||||
litellm: {
|
||||
label: 'LiteLLM',
|
||||
description: '100以上のプロバイダ(OpenAI、Anthropic、Gemini、Bedrockなど)へのセルフホスト型プロキシです。プレースホルダのURLを置き換えてください。ループバックのホストにはSSRF_WHITELISTの設定が必要です。'
|
||||
},
|
||||
requesty: {
|
||||
label: 'Requesty',
|
||||
description: 'openai/gpt-4o-mini、anthropic/claude-sonnet-4-5など'
|
||||
},
|
||||
generic: {
|
||||
label: 'カスタム(OpenAI互換)',
|
||||
description: '汎用のAPIエンドポイント'
|
||||
},
|
||||
siliconflow: {
|
||||
label: 'SiliconFlow',
|
||||
description: 'deepseek-ai/DeepSeek-V3.1など'
|
||||
},
|
||||
jina: {
|
||||
label: 'Jina',
|
||||
description: 'jina-clip-v1、jina-embeddings-v2-base-zhなど'
|
||||
},
|
||||
volcengine: {
|
||||
label: 'Volcengine',
|
||||
description: 'doubao-1-5-pro-32k-250115、doubao-embedding-vision-250615など'
|
||||
},
|
||||
deepseek: {
|
||||
label: 'DeepSeek',
|
||||
description: 'deepseek-chat、deepseek-reasonerなど'
|
||||
},
|
||||
hunyuan: {
|
||||
label: 'Hunyuan',
|
||||
description: 'hunyuan-pro、hunyuan-standard、hunyuan-embeddingなど'
|
||||
},
|
||||
minimax: {
|
||||
label: 'MiniMax',
|
||||
description: 'MiniMax-M3、MiniMax-M2.7、MiniMax-M2.7-highspeedなど'
|
||||
},
|
||||
mimo: {
|
||||
label: 'MiMo',
|
||||
description: 'mimo-v2-flash'
|
||||
},
|
||||
gemini: {
|
||||
label: 'Google Gemini',
|
||||
description: 'gemini-3-flash-preview、gemini-2.5-proなど'
|
||||
},
|
||||
gpustack: {
|
||||
label: 'GPUStack',
|
||||
description: 'GPUStackにデプロイ済みのモデルを選択してください'
|
||||
},
|
||||
modelscope: {
|
||||
label: 'ModelScope',
|
||||
description: 'Qwen/Qwen3-8B、Qwen/Qwen3-Embedding-8Bなど'
|
||||
},
|
||||
qiniu: {
|
||||
label: 'Qiniu Cloud',
|
||||
description: 'deepseek/deepseek-v3.2-251201、z-ai/glm-4.7など'
|
||||
},
|
||||
moonshot: {
|
||||
label: 'Moonshot',
|
||||
description: 'kimi-k2-turbo-preview、moonshot-v1-8k-vision-previewなど'
|
||||
},
|
||||
qianfan: {
|
||||
label: 'Baidu Qianfan',
|
||||
description: 'ernie-5.0-thinking-preview、embedding-v1、bce-reranker-baseなど'
|
||||
},
|
||||
longcat: {
|
||||
label: 'LongCat AI',
|
||||
description: 'LongCat-Flash-Chat、LongCat-Flash-Thinkingなど'
|
||||
},
|
||||
lkeap: {
|
||||
label: 'Tencent Cloud LKEAP',
|
||||
description: 'DeepSeek-R1、DeepSeek-V3、lke-reranker-baseなど'
|
||||
},
|
||||
nvidia: {
|
||||
label: 'NVIDIA',
|
||||
description: 'deepseek-ai-deepseek-v3_1、nv-embed-v1、rerank-qa-mistral-4bなど'
|
||||
},
|
||||
novita: {
|
||||
label: 'Novita AI',
|
||||
description: 'moonshotai/kimi-k2.5、zai-org/glm-5、minimax/minimax-m2.7、qwen/qwen3-embedding-0.6bなど'
|
||||
}
|
||||
}
|
||||
providerDocs: '{provider} のモデルドキュメントを見る',
|
||||
},
|
||||
builtinTag: '組み込み'
|
||||
},
|
||||
|
|
@ -5199,6 +5129,8 @@ export default {
|
|||
}
|
||||
},
|
||||
debug: {
|
||||
reasoningEffort: '思考強度',
|
||||
reasoningEffortDesc: 'モデルカタログが報告するレベルで reasoning_effort を送信します',
|
||||
title: 'モデルテスト',
|
||||
description: '保存済みのモデル設定でリクエストを送信します。編集中の変更は保存後に反映されます。',
|
||||
groupModel: 'モデルを選択',
|
||||
|
|
@ -5221,15 +5153,11 @@ export default {
|
|||
audioFile: '音声ファイル',
|
||||
chooseFile: 'ファイルを選択',
|
||||
parameters: 'リクエストパラメータ',
|
||||
thinking: '思考モード',
|
||||
thinkingDesc: '思考に対応したモデルにのみ適用されます',
|
||||
systemPrompt: 'システムプロンプト',
|
||||
systemPromptPlaceholder: 'システムプロンプト(任意)',
|
||||
run: 'テストを実行',
|
||||
copyResult: '結果をコピー',
|
||||
history: '履歴',
|
||||
thinkOn: '思考オン',
|
||||
thinkOff: '思考オフ',
|
||||
runLabel: '実行 #{n}',
|
||||
success: 'リクエストに成功しました',
|
||||
failed: 'リクエストに失敗しました',
|
||||
|
|
@ -5237,6 +5165,9 @@ export default {
|
|||
requestPreview: 'リクエストのプレビュー',
|
||||
requestFailed: 'モデルテストのリクエストに失敗しました',
|
||||
metrics: {
|
||||
api: 'プロトコル',
|
||||
thinkingFormat: '思考形式',
|
||||
requestedReasoningEffort: '要求した強度',
|
||||
dimension: '次元数',
|
||||
resultCount: '結果件数',
|
||||
answerChars: '回答文字数',
|
||||
|
|
|
|||
|
|
@ -2373,6 +2373,8 @@ export default {
|
|||
}
|
||||
},
|
||||
debug: {
|
||||
reasoningEffort: '사고 강도',
|
||||
reasoningEffortDesc: '모델 카탈로그가 보고한 수준으로 reasoning_effort를 보냅니다',
|
||||
title: '모델 테스트',
|
||||
description: '저장된 모델 설정으로 요청을 보냅니다. 편집 중인 변경 사항은 저장 후 반영됩니다.',
|
||||
groupModel: '모델 선택',
|
||||
|
|
@ -2395,15 +2397,11 @@ export default {
|
|||
audioFile: '오디오 파일',
|
||||
chooseFile: '파일 선택',
|
||||
parameters: '요청 매개변수',
|
||||
thinking: '사고 모드',
|
||||
thinkingDesc: '사고 모드를 지원하는 모델에만 적용됩니다',
|
||||
systemPrompt: 'System Prompt',
|
||||
systemPromptPlaceholder: '선택 사항, 시스템 프롬프트 입력',
|
||||
run: '테스트 실행',
|
||||
copyResult: '결과 복사',
|
||||
history: '기록',
|
||||
thinkOn: '사고 켜짐',
|
||||
thinkOff: '사고 꺼짐',
|
||||
runLabel: '{n}번째 실행',
|
||||
success: '호출 성공',
|
||||
failed: '호출 실패',
|
||||
|
|
@ -2411,6 +2409,9 @@ export default {
|
|||
requestPreview: '요청 미리보기',
|
||||
requestFailed: '모델 테스트 요청 실패',
|
||||
metrics: {
|
||||
api: '프로토콜',
|
||||
thinkingFormat: '사고 형식',
|
||||
requestedReasoningEffort: '요청한 강도',
|
||||
dimension: '벡터 차원',
|
||||
resultCount: '결과 수',
|
||||
answerChars: '답변 문자 수',
|
||||
|
|
@ -2753,6 +2754,28 @@ export default {
|
|||
languageSaved: '언어 설정이 저장되었습니다'
|
||||
},
|
||||
model: {
|
||||
reasoning: {
|
||||
levels: {
|
||||
off: '끄기',
|
||||
auto: '자동',
|
||||
minimal: '최소',
|
||||
low: '낮음',
|
||||
medium: '중간',
|
||||
high: '높음',
|
||||
xhigh: '매우 높음',
|
||||
max: '최대',
|
||||
},
|
||||
levelDescriptions: {
|
||||
off: '사고를 끄고 사고 파라미터를 보내지 않습니다',
|
||||
auto: '공급사 기본 강도, 사고량은 모델이 결정합니다',
|
||||
minimal: '최소 사고, 가장 빠른 응답',
|
||||
low: '가벼운 사고',
|
||||
medium: '중간 강도 사고',
|
||||
high: '깊은 사고, 응답이 느려집니다',
|
||||
xhigh: '매우 높은 사고 예산(일부 모델만)',
|
||||
max: '최대 사고 예산(일부 모델만)',
|
||||
},
|
||||
},
|
||||
modelName: '모델 이름',
|
||||
defaultTag: '기본값',
|
||||
addModelInSettings: '전역 설정에서 모델 추가하기',
|
||||
|
|
@ -2761,6 +2784,53 @@ export default {
|
|||
searchPlaceholder: '모델 검색...',
|
||||
builtinTag: '내장',
|
||||
editor: {
|
||||
maxOutputTokensLabel: '최대 출력 토큰',
|
||||
maxOutputTokensPlaceholder: '비워 두면 카탈로그 기본값',
|
||||
maxOutputTokensDesc: '응답 1회의 출력 상한입니다. 비워 두면 이 모델의 카탈로그 기본값을 사용합니다.',
|
||||
catalog: {
|
||||
reasoning: '추론',
|
||||
vision: '비전',
|
||||
hint: '공급사 카탈로그에서 선택하거나 사용자 지정 모델 이름을 입력할 수 있습니다.',
|
||||
},
|
||||
resolved: {
|
||||
title: '실제 호출 방식',
|
||||
empty: '공급사와 모델 이름을 입력하면 이 모델이 어떻게 호출되는지 표시합니다',
|
||||
failed: '해석 실패',
|
||||
protocol: '요청 프로토콜',
|
||||
catalog: '기능 출처',
|
||||
catalogedYes: '내장 모델 프로필',
|
||||
catalogedNo: '공급사 기본값(카탈로그 미수록)',
|
||||
endpoint: '요청 엔드포인트',
|
||||
thinkingFormat: '사고 전환 전달 방식',
|
||||
thinkingLevels: '선택 가능한 사고 강도',
|
||||
noThinking: '이 모델은 사고를 지원하지 않습니다',
|
||||
},
|
||||
advanced: {
|
||||
toggle: '고급',
|
||||
api: {
|
||||
label: '프로토콜 재정의',
|
||||
auto: '자동(공급사 / URL 기준)',
|
||||
desc: '요청 프로토콜을 강제합니다. 일반적으로 변경할 필요가 없습니다.',
|
||||
},
|
||||
remoteModelName: {
|
||||
label: '원격 모델 이름',
|
||||
placeholder: '비워 두면 모델 이름과 동일',
|
||||
desc: '위 모델 이름과 다를 때 실제로 공급사에 보내는 모델 ID입니다.',
|
||||
},
|
||||
legacyThinking: {
|
||||
label: '사고 파라미터 형식(레거시)',
|
||||
catalog: '카탈로그 기본값 따르기(권장)',
|
||||
none: '사고 파라미터를 보내지 않음',
|
||||
desc: '이 모델에는 이전 버전의 thinking_control 설정이 남아 있습니다. "카탈로그 기본값 따르기"를 선택하면 카탈로그가 결정합니다.',
|
||||
},
|
||||
compat: {
|
||||
label: '프로토콜 호환 재정의(JSON)',
|
||||
placeholder: "{'{'} \"max_tokens_field\": \"max_tokens\" {'}'}",
|
||||
desc: '해석된 프로토콜의 카탈로그 기본값 위에 병합되는 호환 스위치입니다. 백엔드 catalog/compat.go 참조. 비워 두면 재정의하지 않습니다.',
|
||||
invalid: '잘못된 JSON',
|
||||
mustBeObject: 'JSON 객체여야 합니다',
|
||||
},
|
||||
},
|
||||
addTitle: '모델 추가',
|
||||
editTitle: '모델 편집',
|
||||
sectionType: '모델 유형',
|
||||
|
|
@ -2807,8 +2877,6 @@ export default {
|
|||
maxConcurrencyLabel: '백그라운드 동시 실행 상한',
|
||||
maxConcurrencyPlaceholder: '0이면 전역 기본값 사용',
|
||||
maxConcurrencyDesc: '문서 인덱싱/보강 등 백그라운드 작업이 이 모델을 호출하는 동시 실행 수를 제한합니다(모델별로 모든 복제본이 공유). 0 또는 비워 두면 전역 기본값을 사용하며, 대화형 채팅에는 영향을 주지 않습니다.',
|
||||
thinkingControlLabel: '사고 모드 매개변수 형식',
|
||||
thinkingControlDesc: '에이전트 「사고 모드」 켜기/끄기 시 API에 어떻게 기록할지 결정합니다. 벤더/모델에 따라 미리 선택되며, 실제 API와 다르면 문서에 맞게 수정하세요. 「전송 안 함」을 선택하면 에이전트 「사고 모드」 스위치가 효과가 없습니다.',
|
||||
dimensionHint: '모델이 선택되었습니다. "차원 감지" 버튼을 클릭하여 벡터 차원을 자동으로 가져옵니다',
|
||||
loadModelListFailed: '모델 목록 로드 실패',
|
||||
listRefreshed: '목록이 새로고침되었습니다',
|
||||
|
|
@ -2831,113 +2899,9 @@ export default {
|
|||
goToOllamaSettings: '설정 보기',
|
||||
providerLabel: '프로바이더',
|
||||
providerPlaceholder: '모델 프로바이더 선택',
|
||||
providers: {
|
||||
novita: {
|
||||
label: 'Novita AI',
|
||||
description: 'moonshotai/kimi-k2.5, zai-org/glm-5, minimax/minimax-m2.7, qwen/qwen3-embedding-0.6b 등'
|
||||
},
|
||||
nvidia: {
|
||||
label: 'NVIDIA',
|
||||
description: 'deepseek-ai-deepseek-v3_1, nv-embed-v1, rerank-qa-mistral-4b, etc.'
|
||||
},
|
||||
lkeap: {
|
||||
label: '텐센트 클라우드 LKEAP',
|
||||
description: 'DeepSeek-R1, DeepSeek-V3, lke-reranker-base 등'
|
||||
},
|
||||
longcat: {
|
||||
label: 'LongCat AI',
|
||||
description: 'LongCat-Flash-Chat, LongCat-Flash-Thinking, etc.'
|
||||
},
|
||||
qianfan: {
|
||||
label: 'Baidu Qianfan',
|
||||
description: 'ernie-5.0-thinking-preview, embedding-v1, bce-reranker-base, etc.'
|
||||
},
|
||||
moonshot: {
|
||||
label: 'Moonshot',
|
||||
description: 'kimi-k2-turbo-preview, moonshot-v1-8k-vision-preview, etc.'
|
||||
},
|
||||
qiniu: {
|
||||
label: 'Qiniu Cloud',
|
||||
description: 'deepseek/deepseek-v3.2-251201, z-ai/glm-4.7, etc.'
|
||||
},
|
||||
modelscope: {
|
||||
label: 'ModelScope',
|
||||
description: 'Qwen/Qwen3-8B, Qwen/Qwen3-Embedding-8B, etc.'
|
||||
},
|
||||
gpustack: {
|
||||
label: 'GPUStack',
|
||||
description: 'Choose your deployed model on GPUStack'
|
||||
},
|
||||
gemini: {
|
||||
label: 'Google Gemini',
|
||||
description: 'gemini-3-flash-preview, gemini-2.5-pro 등'
|
||||
},
|
||||
mimo: {
|
||||
label: 'MiMo',
|
||||
description: 'mimo-v2-flash'
|
||||
},
|
||||
minimax: {
|
||||
label: 'MiniMax',
|
||||
description: 'MiniMax-M3, MiniMax-M2.7, MiniMax-M2.7-highspeed 등'
|
||||
},
|
||||
hunyuan: {
|
||||
label: 'Hunyuan',
|
||||
description: 'hunyuan-pro, hunyuan-standard, hunyuan-embedding 등'
|
||||
},
|
||||
deepseek: {
|
||||
label: 'DeepSeek',
|
||||
description: 'deepseek-chat, deepseek-reasoner 등'
|
||||
},
|
||||
volcengine: {
|
||||
label: 'Volcengine',
|
||||
description: 'doubao-1-5-pro-32k-250115, doubao-embedding-vision-250615 등'
|
||||
},
|
||||
jina: {
|
||||
label: 'Jina',
|
||||
description: 'jina-clip-v1, jina-embeddings-v2-base-zh, etc.'
|
||||
},
|
||||
siliconflow: {
|
||||
label: 'SiliconFlow',
|
||||
description: 'deepseek-ai/DeepSeek-V3.1 등'
|
||||
},
|
||||
generic: {
|
||||
label: '사용자 정의 (OpenAI 호환)',
|
||||
description: 'Generic API endpoint'
|
||||
},
|
||||
requesty: {
|
||||
label: 'Requesty',
|
||||
description: 'openai/gpt-4o-mini, anthropic/claude-sonnet-4-5 등'
|
||||
},
|
||||
openrouter: {
|
||||
label: 'OpenRouter',
|
||||
description: 'openai/gpt-5.2-chat, google/gemini-3-flash-preview 등'
|
||||
},
|
||||
litellm: {
|
||||
label: 'LiteLLM',
|
||||
description: '자체 호스팅 프록시로 OpenAI, Anthropic, Gemini, Bedrock 등 100+ 공급자를 연결합니다. 플레이스홀더 URL을 실제 주소로 바꾸세요. localhost는 SSRF_WHITELIST에 추가해야 합니다.'
|
||||
},
|
||||
zhipu: {
|
||||
label: 'Zhipu BigModel',
|
||||
description: 'glm-4.7, embedding-3, rerank, etc.'
|
||||
},
|
||||
aliyun: {
|
||||
label: 'Aliyun DashScope',
|
||||
description: 'qwen-plus, tongyi-embedding-vision-plus, qwen3-rerank 등'
|
||||
},
|
||||
azure_openai: {
|
||||
label: 'Azure OpenAI',
|
||||
description: 'Microsoft Azure에서 호스팅되는 OpenAI 서비스'
|
||||
},
|
||||
anthropic: {
|
||||
label: 'Anthropic',
|
||||
description: 'Claude models via native Anthropic Messages API'
|
||||
},
|
||||
openai: {
|
||||
label: 'OpenAI',
|
||||
description: 'gpt-5.2, gpt-5-mini 등'
|
||||
}
|
||||
},
|
||||
providerDocs: '{provider} 모델 문서 보기',
|
||||
validation: {
|
||||
extraFieldRequired: '{name}을(를) 입력하세요',
|
||||
modelNameRequired: '모델 이름을 입력해주세요',
|
||||
modelNameEmpty: '모델 이름은 비워둘 수 없습니다',
|
||||
modelNameMax: '모델 이름은 100자를 초과할 수 없습니다',
|
||||
|
|
@ -2945,41 +2909,6 @@ export default {
|
|||
baseUrlEmpty: 'Base URL은 비워둘 수 없습니다',
|
||||
baseUrlInvalid: 'Base URL 형식이 올바르지 않습니다. 유효한 URL을 입력해주세요'
|
||||
},
|
||||
thinkingControl: {
|
||||
thinkingType: {
|
||||
label: 'thinking.type',
|
||||
hint: 'Volcengine Ark; Tencent LKEAP (DeepSeek V3 등, LKEAP 기본값; R1은 「전송 안 함」)'
|
||||
},
|
||||
enableThinking: {
|
||||
label: 'enable_thinking',
|
||||
hint: 'Alibaba DashScope: qwen3, qwen-plus, qwen-max, qwen-turbo'
|
||||
},
|
||||
chatTemplateKwargs: {
|
||||
label: 'chat_template_kwargs',
|
||||
hint: '사용자 정의 OpenAI 호환, NVIDIA NIM, vLLM / 로컬 Qwen 배포'
|
||||
},
|
||||
none: {
|
||||
label: '사고 매개변수 전송 안 함',
|
||||
hint: '에이전트 「사고 모드」 스위치가 효과 없음, 요청에 사고 관련 매개변수를 보내지 않음'
|
||||
}
|
||||
},
|
||||
volcengine: {
|
||||
accessKeyLabel: 'Access Key ID',
|
||||
accessKeyPlaceholder: 'Volcengine Access Key ID',
|
||||
secretKeyLabel: 'Secret Access Key',
|
||||
secretKeyPlaceholder: 'Volcengine Secret Access Key',
|
||||
rerankCredentialHint: 'Rerank은 Ark API 키가 아닌 VikingDB AK/SK 서명을 사용합니다. 권장 모델: doubao-seed-rerank.'
|
||||
},
|
||||
lkeap: {
|
||||
secretIdLabel: 'SecretId',
|
||||
secretIdPlaceholder: 'Tencent Cloud API SecretId',
|
||||
secretKeyLabel: 'SecretKey',
|
||||
secretKeyPlaceholder: 'Tencent Cloud API SecretKey',
|
||||
regionLabel: 'Region',
|
||||
regionPlaceholder: 'ap-guangzhou',
|
||||
regionDesc: 'RunRerank supports ap-beijing, ap-guangzhou, etc. Default: ap-guangzhou',
|
||||
rerankCredentialHint: 'Rerank uses Tencent Cloud API signature (not the OpenAI-style LKEAP API key). Create SecretId/SecretKey in the CAM console.'
|
||||
},
|
||||
modelNamePlaceholder: {
|
||||
local: '예: llama2:latest',
|
||||
remote: '예: gpt-4, claude-3-opus',
|
||||
|
|
@ -6392,6 +6321,8 @@ export default {
|
|||
capabilityUnconfigured: '미구성'
|
||||
},
|
||||
editor: {
|
||||
reasoningEffortUnsupported: '선택한 모델은 사고를 지원하지 않습니다. "끄기" 외의 옵션은 무시됩니다.',
|
||||
reasoningEffortAlwaysOn: '선택한 모델은 항상 사고하며 끌 수 없습니다. 강도만 조정할 수 있습니다.',
|
||||
createTitle: '에이전트 만들기',
|
||||
editTitle: '에이전트 편집',
|
||||
buttons: {
|
||||
|
|
|
|||
|
|
@ -2373,6 +2373,8 @@ export default {
|
|||
}
|
||||
},
|
||||
debug: {
|
||||
reasoningEffort: 'Интенсивность размышлений',
|
||||
reasoningEffortDesc: 'Отправляет reasoning_effort с уровнями, которые сообщает каталог модели',
|
||||
title: 'Тест модели',
|
||||
description: 'Запрос с сохранёнными настройками модели. Перед проверкой сохраните изменения.',
|
||||
groupModel: 'Выбор модели',
|
||||
|
|
@ -2395,15 +2397,11 @@ export default {
|
|||
audioFile: 'Аудиофайл',
|
||||
chooseFile: 'Выбрать файл',
|
||||
parameters: 'Параметры запроса',
|
||||
thinking: 'Режим размышления',
|
||||
thinkingDesc: 'Применяется только к моделям с поддержкой размышления',
|
||||
systemPrompt: 'System Prompt',
|
||||
systemPromptPlaceholder: 'Необязательно: системный промпт',
|
||||
run: 'Запустить тест',
|
||||
copyResult: 'Копировать результат',
|
||||
history: 'История',
|
||||
thinkOn: 'Размышление вкл.',
|
||||
thinkOff: 'Размышление выкл.',
|
||||
runLabel: 'Запуск №{n}',
|
||||
success: 'Запрос выполнен',
|
||||
failed: 'Запрос не выполнен',
|
||||
|
|
@ -2411,6 +2409,9 @@ export default {
|
|||
requestPreview: 'Просмотр запроса',
|
||||
requestFailed: 'Не удалось выполнить тест модели',
|
||||
metrics: {
|
||||
api: 'Протокол',
|
||||
thinkingFormat: 'Формат размышлений',
|
||||
requestedReasoningEffort: 'Запрошенная интенсивность',
|
||||
dimension: 'Размерность вектора',
|
||||
resultCount: 'Количество результатов',
|
||||
answerChars: 'Символов в ответе',
|
||||
|
|
@ -2753,6 +2754,28 @@ export default {
|
|||
languageSaved: 'Настройки языка сохранены'
|
||||
},
|
||||
model: {
|
||||
reasoning: {
|
||||
levels: {
|
||||
off: 'Выкл',
|
||||
auto: 'Авто',
|
||||
minimal: 'Минимальный',
|
||||
low: 'Низкий',
|
||||
medium: 'Средний',
|
||||
high: 'Высокий',
|
||||
xhigh: 'Очень высокий',
|
||||
max: 'Максимальный',
|
||||
},
|
||||
levelDescriptions: {
|
||||
off: 'Размышления отключены, параметры размышления не отправляются',
|
||||
auto: 'Интенсивность по умолчанию поставщика; модель сама решает, сколько думать',
|
||||
minimal: 'Минимум размышлений, самые быстрые ответы',
|
||||
low: 'Лёгкие размышления',
|
||||
medium: 'Умеренные размышления',
|
||||
high: 'Глубокие размышления, ответы медленнее',
|
||||
xhigh: 'Очень большой бюджет размышлений (только некоторые модели)',
|
||||
max: 'Максимальный бюджет размышлений (только некоторые модели)',
|
||||
},
|
||||
},
|
||||
modelName: 'Название модели',
|
||||
defaultTag: 'По умолчанию',
|
||||
addModelInSettings: 'Перейти в общие настройки для добавления моделей',
|
||||
|
|
@ -2761,6 +2784,53 @@ export default {
|
|||
searchPlaceholder: 'Поиск моделей...',
|
||||
builtinTag: 'Built-in',
|
||||
editor: {
|
||||
maxOutputTokensLabel: 'Макс. выходных токенов',
|
||||
maxOutputTokensPlaceholder: 'Пусто — значение из каталога',
|
||||
maxOutputTokensDesc: 'Лимит вывода на один ответ. Оставьте пустым, чтобы использовать значение каталога для этой модели.',
|
||||
catalog: {
|
||||
reasoning: 'Рассуждение',
|
||||
vision: 'Зрение',
|
||||
hint: 'Выберите модель из каталога поставщика или введите своё имя модели.',
|
||||
},
|
||||
resolved: {
|
||||
title: 'Как вызывается модель',
|
||||
empty: 'Укажите поставщика и имя модели, чтобы увидеть, как она будет вызвана',
|
||||
failed: 'Не удалось определить',
|
||||
protocol: 'Протокол запроса',
|
||||
catalog: 'Источник возможностей',
|
||||
catalogedYes: 'Встроенный профиль модели',
|
||||
catalogedNo: 'Настройки поставщика (модели нет в каталоге)',
|
||||
endpoint: 'Адрес запроса',
|
||||
thinkingFormat: 'Переключатель размышлений',
|
||||
thinkingLevels: 'Доступная интенсивность',
|
||||
noThinking: 'Модель не умеет размышлять',
|
||||
},
|
||||
advanced: {
|
||||
toggle: 'Дополнительно',
|
||||
api: {
|
||||
label: 'Переопределение протокола',
|
||||
auto: 'Авто (по поставщику / URL)',
|
||||
desc: 'Принудительно задать протокол запросов; обычно не требуется.',
|
||||
},
|
||||
remoteModelName: {
|
||||
label: 'Имя модели у поставщика',
|
||||
placeholder: 'Пусто — совпадает с именем модели',
|
||||
desc: 'ID модели, который реально отправляется поставщику, если отличается от имени выше.',
|
||||
},
|
||||
legacyThinking: {
|
||||
label: 'Формат параметров размышления (устаревший)',
|
||||
catalog: 'Следовать каталогу (рекомендуется)',
|
||||
none: 'Не отправлять параметры размышления',
|
||||
desc: 'У этой модели сохранилась устаревшая настройка thinking_control. Выберите «Следовать каталогу», чтобы решение принимал каталог.',
|
||||
},
|
||||
compat: {
|
||||
label: 'Переопределение совместимости протокола (JSON)',
|
||||
placeholder: "{'{'} \"max_tokens_field\": \"max_tokens\" {'}'}",
|
||||
desc: 'Переключатели совместимости, накладываемые на значения каталога для определённого протокола; см. catalog/compat.go на бэкенде. Пусто — без переопределения.',
|
||||
invalid: 'Некорректный JSON',
|
||||
mustBeObject: 'Должен быть JSON-объект',
|
||||
},
|
||||
},
|
||||
addTitle: 'Добавить модель',
|
||||
editTitle: 'Редактировать модель',
|
||||
sectionType: 'Тип модели',
|
||||
|
|
@ -2807,8 +2877,6 @@ export default {
|
|||
maxConcurrencyLabel: 'Лимит фоновой параллельности',
|
||||
maxConcurrencyPlaceholder: '0 — использовать глобальное значение',
|
||||
maxConcurrencyDesc: 'Ограничивает число одновременных фоновых вызовов (индексация/обогащение) к этой модели, общее для модели по всем репликам. 0 или пусто — используется глобальное значение по умолчанию; интерактивный чат не затрагивается.',
|
||||
thinkingControlLabel: 'Формат параметров режима размышления',
|
||||
thinkingControlDesc: 'Определяет, как переключатель «Режим размышления» агента записывается в API. При возможности выбирается по поставщику/модели; при несоответствии измените по документации API. При выборе «Не отправлять» переключатель «Режим размышления» агента не действует.',
|
||||
dimensionHint: 'Модель выбрана. Нажмите «Определить размерность», чтобы автоматически получить значение.',
|
||||
loadModelListFailed: 'Не удалось загрузить список моделей',
|
||||
listRefreshed: 'Список обновлён',
|
||||
|
|
@ -2831,113 +2899,9 @@ export default {
|
|||
goToOllamaSettings: 'Открыть настройки',
|
||||
providerLabel: 'Провайдер',
|
||||
providerPlaceholder: 'Выберите провайдера модели',
|
||||
providers: {
|
||||
novita: {
|
||||
label: 'Novita AI',
|
||||
description: 'moonshotai/kimi-k2.5, zai-org/glm-5, minimax/minimax-m2.7, qwen/qwen3-embedding-0.6b, etc.'
|
||||
},
|
||||
nvidia: {
|
||||
label: 'NVIDIA',
|
||||
description: 'deepseek-ai-deepseek-v3_1, nv-embed-v1, rerank-qa-mistral-4b, etc.'
|
||||
},
|
||||
lkeap: {
|
||||
label: 'Tencent Cloud LKEAP',
|
||||
description: 'DeepSeek-R1, DeepSeek-V3, lke-reranker-base и др.'
|
||||
},
|
||||
longcat: {
|
||||
label: 'LongCat AI',
|
||||
description: 'LongCat-Flash-Chat, LongCat-Flash-Thinking, etc.'
|
||||
},
|
||||
qianfan: {
|
||||
label: 'Baidu Qianfan',
|
||||
description: 'ernie-5.0-thinking-preview, embedding-v1, bce-reranker-base, etc.'
|
||||
},
|
||||
moonshot: {
|
||||
label: 'Moonshot',
|
||||
description: 'kimi-k2-turbo-preview, moonshot-v1-8k-vision-preview, etc.'
|
||||
},
|
||||
qiniu: {
|
||||
label: 'Qiniu Cloud',
|
||||
description: 'deepseek/deepseek-v3.2-251201, z-ai/glm-4.7, etc.'
|
||||
},
|
||||
modelscope: {
|
||||
label: 'ModelScope',
|
||||
description: 'Qwen/Qwen3-8B, Qwen/Qwen3-Embedding-8B, etc.'
|
||||
},
|
||||
gpustack: {
|
||||
label: 'GPUStack',
|
||||
description: 'Choose your deployed model on GPUStack'
|
||||
},
|
||||
gemini: {
|
||||
label: 'Google Gemini',
|
||||
description: 'gemini-3-flash-preview, gemini-2.5-pro, etc.'
|
||||
},
|
||||
mimo: {
|
||||
label: 'MiMo',
|
||||
description: 'mimo-v2-flash'
|
||||
},
|
||||
minimax: {
|
||||
label: 'MiniMax',
|
||||
description: 'MiniMax-M3, MiniMax-M2.7, MiniMax-M2.7-highspeed, etc.'
|
||||
},
|
||||
hunyuan: {
|
||||
label: 'Hunyuan',
|
||||
description: 'hunyuan-pro, hunyuan-standard, hunyuan-embedding, etc.'
|
||||
},
|
||||
deepseek: {
|
||||
label: 'DeepSeek',
|
||||
description: 'deepseek-chat, deepseek-reasoner, etc.'
|
||||
},
|
||||
volcengine: {
|
||||
label: 'Volcengine',
|
||||
description: 'doubao-1-5-pro-32k-250115, doubao-embedding-vision-250615, etc.'
|
||||
},
|
||||
jina: {
|
||||
label: 'Jina',
|
||||
description: 'jina-clip-v1, jina-embeddings-v2-base-zh, etc.'
|
||||
},
|
||||
siliconflow: {
|
||||
label: 'SiliconFlow',
|
||||
description: 'deepseek-ai/DeepSeek-V3.1, etc.'
|
||||
},
|
||||
generic: {
|
||||
label: 'Пользовательский (OpenAI-совместимый)',
|
||||
description: 'Generic API endpoint'
|
||||
},
|
||||
requesty: {
|
||||
label: 'Requesty',
|
||||
description: 'openai/gpt-4o-mini, anthropic/claude-sonnet-4-5, etc.'
|
||||
},
|
||||
openrouter: {
|
||||
label: 'OpenRouter',
|
||||
description: 'openai/gpt-5.2-chat, google/gemini-3-flash-preview, etc.'
|
||||
},
|
||||
litellm: {
|
||||
label: 'LiteLLM',
|
||||
description: 'Self-hosted прокси к 100+ провайдерам (OpenAI, Anthropic, Gemini, Bedrock и др.). Замените URL-заглушку; localhost нужно добавить в SSRF_WHITELIST.'
|
||||
},
|
||||
zhipu: {
|
||||
label: 'Zhipu BigModel',
|
||||
description: 'glm-4.7, embedding-3, rerank, etc.'
|
||||
},
|
||||
aliyun: {
|
||||
label: 'Aliyun DashScope',
|
||||
description: 'qwen-plus, tongyi-embedding-vision-plus, qwen3-rerank, etc.'
|
||||
},
|
||||
azure_openai: {
|
||||
label: 'Azure OpenAI',
|
||||
description: 'Сервис OpenAI на платформе Microsoft Azure'
|
||||
},
|
||||
anthropic: {
|
||||
label: 'Anthropic',
|
||||
description: 'Claude models via native Anthropic Messages API'
|
||||
},
|
||||
openai: {
|
||||
label: 'OpenAI',
|
||||
description: 'gpt-5.2, gpt-5-mini, etc.'
|
||||
}
|
||||
},
|
||||
providerDocs: 'Документация моделей {provider}',
|
||||
validation: {
|
||||
extraFieldRequired: 'Заполните {name}',
|
||||
modelNameRequired: 'Введите название модели',
|
||||
modelNameEmpty: 'Название модели не может быть пустым',
|
||||
modelNameMax: 'Название модели не может превышать 100 символов',
|
||||
|
|
@ -2945,41 +2909,6 @@ export default {
|
|||
baseUrlEmpty: 'Base URL не может быть пустым',
|
||||
baseUrlInvalid: 'Недопустимый Base URL, введите корректный адрес'
|
||||
},
|
||||
thinkingControl: {
|
||||
thinkingType: {
|
||||
label: 'thinking.type',
|
||||
hint: 'Volcengine Ark; Tencent LKEAP (DeepSeek V3 и др.; по умолчанию для LKEAP; для R1 — «Не отправлять»)'
|
||||
},
|
||||
enableThinking: {
|
||||
label: 'enable_thinking',
|
||||
hint: 'Alibaba DashScope: qwen3, qwen-plus, qwen-max, qwen-turbo'
|
||||
},
|
||||
chatTemplateKwargs: {
|
||||
label: 'chat_template_kwargs',
|
||||
hint: 'Пользовательские OpenAI-совместимые шлюзы, NVIDIA NIM, vLLM / локальный Qwen'
|
||||
},
|
||||
none: {
|
||||
label: 'Не отправлять параметры размышления',
|
||||
hint: 'Переключатель «Режим размышления» агента не действует; параметры размышления не отправляются в запросе'
|
||||
}
|
||||
},
|
||||
volcengine: {
|
||||
accessKeyLabel: 'Access Key ID',
|
||||
accessKeyPlaceholder: 'Volcengine Access Key ID',
|
||||
secretKeyLabel: 'Secret Access Key',
|
||||
secretKeyPlaceholder: 'Volcengine Secret Access Key',
|
||||
rerankCredentialHint: 'Rerank использует подпись VikingDB AK/SK, а не Ark API key. Рекомендуемая модель: doubao-seed-rerank.'
|
||||
},
|
||||
lkeap: {
|
||||
secretIdLabel: 'SecretId',
|
||||
secretIdPlaceholder: 'Tencent Cloud API SecretId',
|
||||
secretKeyLabel: 'SecretKey',
|
||||
secretKeyPlaceholder: 'Tencent Cloud API SecretKey',
|
||||
regionLabel: 'Region',
|
||||
regionPlaceholder: 'ap-guangzhou',
|
||||
regionDesc: 'RunRerank supports ap-beijing, ap-guangzhou, etc. Default: ap-guangzhou',
|
||||
rerankCredentialHint: 'Rerank uses Tencent Cloud API signature (not the OpenAI-style LKEAP API key). Create SecretId/SecretKey in the CAM console.'
|
||||
},
|
||||
modelNamePlaceholder: {
|
||||
local: 'например: llama2:latest',
|
||||
remote: 'например: gpt-4, claude-3-opus',
|
||||
|
|
@ -6392,6 +6321,8 @@ export default {
|
|||
capabilityUnconfigured: 'Not set'
|
||||
},
|
||||
editor: {
|
||||
reasoningEffortUnsupported: 'Выбранная модель не поддерживает размышления; все варианты, кроме «Выкл», игнорируются.',
|
||||
reasoningEffortAlwaysOn: 'Выбранная модель всегда размышляет, её нельзя отключить — можно менять только уровень усилий.',
|
||||
createTitle: 'Create Agent',
|
||||
editTitle: 'Edit Agent',
|
||||
buttons: {
|
||||
|
|
|
|||
|
|
@ -2375,6 +2375,8 @@ export default {
|
|||
}
|
||||
},
|
||||
debug: {
|
||||
reasoningEffort: '思考强度',
|
||||
reasoningEffortDesc: '按模型目录上报的等级发送 reasoning_effort',
|
||||
title: '模型测试',
|
||||
description: '使用已保存的模型配置发送真实请求;编辑中的修改需保存后才会生效',
|
||||
groupModel: '选择模型',
|
||||
|
|
@ -2397,15 +2399,11 @@ export default {
|
|||
audioFile: '音频文件',
|
||||
chooseFile: '选择文件',
|
||||
parameters: '请求参数',
|
||||
thinking: '思考模式',
|
||||
thinkingDesc: '仅对支持思考模式的模型生效',
|
||||
systemPrompt: 'System Prompt',
|
||||
systemPromptPlaceholder: '可选,输入系统提示词',
|
||||
run: '运行测试',
|
||||
copyResult: '复制结果',
|
||||
history: '历史记录',
|
||||
thinkOn: '思考开启',
|
||||
thinkOff: '思考关闭',
|
||||
runLabel: '第 {n} 次运行',
|
||||
success: '调用成功',
|
||||
failed: '调用失败',
|
||||
|
|
@ -2413,6 +2411,9 @@ export default {
|
|||
requestPreview: '请求预览',
|
||||
requestFailed: '模型测试请求失败',
|
||||
metrics: {
|
||||
api: '协议',
|
||||
thinkingFormat: '思考格式',
|
||||
requestedReasoningEffort: '请求思考强度',
|
||||
dimension: '向量维度',
|
||||
resultCount: '结果数量',
|
||||
answerChars: '回答字符数',
|
||||
|
|
@ -2755,6 +2756,28 @@ export default {
|
|||
languageSaved: '语言设置已保存'
|
||||
},
|
||||
model: {
|
||||
reasoning: {
|
||||
levels: {
|
||||
off: '关闭',
|
||||
auto: '自动',
|
||||
minimal: '极低',
|
||||
low: '低',
|
||||
medium: '中',
|
||||
high: '高',
|
||||
xhigh: '极高',
|
||||
max: '最大',
|
||||
},
|
||||
levelDescriptions: {
|
||||
off: '关闭思考,不写入任何思考参数',
|
||||
auto: '厂商默认强度,由模型自行决定思考深度',
|
||||
minimal: '最少思考,响应最快',
|
||||
low: '轻度思考',
|
||||
medium: '中等思考强度',
|
||||
high: '深度思考,响应更慢',
|
||||
xhigh: '超高强度思考(仅部分模型支持)',
|
||||
max: '最大思考预算(仅部分模型支持)',
|
||||
},
|
||||
},
|
||||
modelName: '模型名称',
|
||||
defaultTag: '默认',
|
||||
addModelInSettings: '前往全局设置添加模型',
|
||||
|
|
@ -2763,6 +2786,53 @@ export default {
|
|||
searchPlaceholder: '搜索模型...',
|
||||
builtinTag: '内置',
|
||||
editor: {
|
||||
maxOutputTokensLabel: '最大输出 tokens',
|
||||
maxOutputTokensPlaceholder: '留空使用目录默认',
|
||||
maxOutputTokensDesc: '单次回复的输出上限。留空则沿用目录中该模型的默认值。',
|
||||
catalog: {
|
||||
reasoning: '推理',
|
||||
vision: '视觉',
|
||||
hint: '可从厂商内置目录选择,也可直接输入自定义模型名。',
|
||||
},
|
||||
resolved: {
|
||||
title: '实际调用方式',
|
||||
empty: '填写厂商与模型名后,这里会显示这个模型将被怎样调用',
|
||||
failed: '解析失败',
|
||||
protocol: '请求协议',
|
||||
catalog: '能力来源',
|
||||
catalogedYes: '内置模型档案',
|
||||
catalogedNo: '厂商通用默认(未收录此模型)',
|
||||
endpoint: '请求地址',
|
||||
thinkingFormat: '思考开关传参',
|
||||
thinkingLevels: '可选思考强度',
|
||||
noThinking: '该模型不支持思考',
|
||||
},
|
||||
advanced: {
|
||||
toggle: '高级',
|
||||
api: {
|
||||
label: '协议覆盖',
|
||||
auto: '自动(按厂商 / URL 推断)',
|
||||
desc: '强制使用指定的请求协议;一般无需修改。',
|
||||
},
|
||||
remoteModelName: {
|
||||
label: '远端模型名',
|
||||
placeholder: '留空与模型名相同',
|
||||
desc: '实际发送给厂商的模型 ID,与上面的模型名不同时填写。',
|
||||
},
|
||||
legacyThinking: {
|
||||
label: '思考参数格式(旧配置)',
|
||||
catalog: '遵循目录默认(推荐)',
|
||||
none: '不写入思考参数',
|
||||
desc: '此模型仍带有旧版 thinking_control 设置。选择「遵循目录默认」后由目录决定思考参数的写法。',
|
||||
},
|
||||
compat: {
|
||||
label: '协议兼容覆盖(JSON)',
|
||||
placeholder: "{'{'} \"max_tokens_field\": \"max_tokens\" {'}'}",
|
||||
desc: '按协议合并到目录默认值的兼容开关,字段见后端 catalog/compat.go。留空表示不覆盖。',
|
||||
invalid: 'JSON 格式不正确',
|
||||
mustBeObject: '必须是 JSON 对象',
|
||||
},
|
||||
},
|
||||
addTitle: '添加模型',
|
||||
editTitle: '编辑模型',
|
||||
sectionType: '模型类型',
|
||||
|
|
@ -2809,8 +2879,6 @@ export default {
|
|||
maxConcurrencyLabel: '后台并发上限',
|
||||
maxConcurrencyPlaceholder: '0 表示使用全局默认',
|
||||
maxConcurrencyDesc: '限制文档入库/富化等后台任务对该模型的并发调用数(按模型全副本共享)。0 或留空表示沿用全局默认;不影响交互式对话。',
|
||||
thinkingControlLabel: '思考模式参数格式',
|
||||
thinkingControlDesc: '决定智能体「思考模式」开/关时如何写入 API。已尝试按厂商/模型预选,若与实际情况不符请按 API 文档手动修改;选「不写入」时,智能体「思考模式」开关不生效。',
|
||||
dimensionHint: '模型已选择,点击"检测维度"按钮自动获取向量维度',
|
||||
loadModelListFailed: '加载模型列表失败',
|
||||
listRefreshed: '列表已刷新',
|
||||
|
|
@ -2833,113 +2901,9 @@ export default {
|
|||
goToOllamaSettings: '查看设置',
|
||||
providerLabel: '服务商',
|
||||
providerPlaceholder: '选择模型服务商',
|
||||
providers: {
|
||||
novita: {
|
||||
label: 'Novita AI',
|
||||
description: 'moonshotai/kimi-k2.5, zai-org/glm-5, minimax/minimax-m2.7, qwen/qwen3-embedding-0.6b 等'
|
||||
},
|
||||
nvidia: {
|
||||
label: 'NVIDIA',
|
||||
description: 'deepseek-ai-deepseek-v3_1, nv-embed-v1, rerank-qa-mistral-4b, etc.'
|
||||
},
|
||||
lkeap: {
|
||||
label: '腾讯云 LKEAP',
|
||||
description: 'DeepSeek-R1、DeepSeek-V3、lke-reranker-base 等'
|
||||
},
|
||||
longcat: {
|
||||
label: 'LongCat AI',
|
||||
description: 'LongCat-Flash-Chat, LongCat-Flash-Thinking, etc.'
|
||||
},
|
||||
qianfan: {
|
||||
label: '百度千帆 Baidu Cloud',
|
||||
description: 'ernie-5.0-thinking-preview, embedding-v1, bce-reranker-base, etc.'
|
||||
},
|
||||
moonshot: {
|
||||
label: '月之暗面 Moonshot',
|
||||
description: 'kimi-k2-turbo-preview, moonshot-v1-8k-vision-preview, etc.'
|
||||
},
|
||||
qiniu: {
|
||||
label: '七牛云 Qiniu',
|
||||
description: 'deepseek/deepseek-v3.2-251201, z-ai/glm-4.7, etc.'
|
||||
},
|
||||
modelscope: {
|
||||
label: '魔搭 ModelScope',
|
||||
description: 'Qwen/Qwen3-8B, Qwen/Qwen3-Embedding-8B, etc.'
|
||||
},
|
||||
gpustack: {
|
||||
label: 'GPUStack',
|
||||
description: 'Choose your deployed model on GPUStack'
|
||||
},
|
||||
gemini: {
|
||||
label: 'Google Gemini',
|
||||
description: 'gemini-3-flash-preview, gemini-2.5-pro 等'
|
||||
},
|
||||
mimo: {
|
||||
label: '小米 MiMo',
|
||||
description: 'mimo-v2-flash'
|
||||
},
|
||||
minimax: {
|
||||
label: 'MiniMax',
|
||||
description: 'MiniMax-M3, MiniMax-M2.7, MiniMax-M2.7-highspeed 等'
|
||||
},
|
||||
hunyuan: {
|
||||
label: '腾讯混元 Hunyuan',
|
||||
description: 'hunyuan-pro, hunyuan-standard, hunyuan-embedding, etc.'
|
||||
},
|
||||
deepseek: {
|
||||
label: 'DeepSeek',
|
||||
description: 'deepseek-chat, deepseek-reasoner 等'
|
||||
},
|
||||
volcengine: {
|
||||
label: '火山引擎 Volcengine',
|
||||
description: 'doubao-1-5-pro-32k-250115, doubao-embedding-vision-250615, etc.'
|
||||
},
|
||||
jina: {
|
||||
label: 'Jina',
|
||||
description: 'jina-clip-v1, jina-embeddings-v2-base-zh, etc.'
|
||||
},
|
||||
siliconflow: {
|
||||
label: '硅基流动 SiliconFlow',
|
||||
description: 'deepseek-ai/DeepSeek-V3.1, etc.'
|
||||
},
|
||||
generic: {
|
||||
label: '自定义 (OpenAI兼容接口)',
|
||||
description: 'Generic API endpoint (OpenAI-compatible)'
|
||||
},
|
||||
requesty: {
|
||||
label: 'Requesty',
|
||||
description: 'openai/gpt-4o-mini, anthropic/claude-sonnet-4-5, etc.'
|
||||
},
|
||||
openrouter: {
|
||||
label: 'OpenRouter',
|
||||
description: 'openai/gpt-5.2-chat, google/gemini-3-flash-preview, etc.'
|
||||
},
|
||||
litellm: {
|
||||
label: 'LiteLLM',
|
||||
description: '自托管代理,统一接入 OpenAI、Anthropic、Gemini、Bedrock 等 100+ 厂商。请将占位 URL 换成可访问地址;localhost 需加入 SSRF_WHITELIST。'
|
||||
},
|
||||
zhipu: {
|
||||
label: '智谱 BigModel',
|
||||
description: 'glm-4.7, embedding-3, rerank, etc.'
|
||||
},
|
||||
aliyun: {
|
||||
label: '阿里云 DashScope',
|
||||
description: 'qwen-plus, tongyi-embedding-vision-plus, qwen3-rerank, etc.'
|
||||
},
|
||||
azure_openai: {
|
||||
label: 'Azure OpenAI',
|
||||
description: 'Microsoft Azure 上的 OpenAI 服务'
|
||||
},
|
||||
anthropic: {
|
||||
label: 'Anthropic',
|
||||
description: 'Claude models via native Anthropic Messages API'
|
||||
},
|
||||
openai: {
|
||||
label: 'OpenAI',
|
||||
description: 'gpt-5.2, gpt-5-mini, etc.'
|
||||
}
|
||||
},
|
||||
providerDocs: '查看 {provider} 的模型文档',
|
||||
validation: {
|
||||
extraFieldRequired: '请填写 {name}',
|
||||
modelNameRequired: '请输入模型名称',
|
||||
modelNameEmpty: '模型名称不能为空',
|
||||
modelNameMax: '模型名称不能超过100个字符',
|
||||
|
|
@ -2947,41 +2911,6 @@ export default {
|
|||
baseUrlEmpty: 'Base URL 不能为空',
|
||||
baseUrlInvalid: 'Base URL 格式不正确,请输入有效的 URL'
|
||||
},
|
||||
thinkingControl: {
|
||||
thinkingType: {
|
||||
label: 'thinking.type',
|
||||
hint: '火山引擎 Ark;腾讯云 LKEAP(DeepSeek V3 等,选 LKEAP 时默认此项;R1 请改「不写入」)'
|
||||
},
|
||||
enableThinking: {
|
||||
label: 'enable_thinking',
|
||||
hint: '阿里云 DashScope:qwen3、qwen-plus、qwen-max、qwen-turbo'
|
||||
},
|
||||
chatTemplateKwargs: {
|
||||
label: 'chat_template_kwargs',
|
||||
hint: '自定义 OpenAI 兼容、NVIDIA NIM、vLLM / 本地 Qwen 部署'
|
||||
},
|
||||
none: {
|
||||
label: '不写入思考参数',
|
||||
hint: '智能体「思考模式」开关不生效,不会在请求中写入思考相关参数'
|
||||
}
|
||||
},
|
||||
volcengine: {
|
||||
accessKeyLabel: 'Access Key ID',
|
||||
accessKeyPlaceholder: '火山引擎访问密钥 Access Key ID',
|
||||
secretKeyLabel: 'Secret Access Key',
|
||||
secretKeyPlaceholder: '火山引擎访问密钥 Secret Access Key',
|
||||
rerankCredentialHint: 'Rerank 使用 VikingDB AK/SK 签名(非方舟 API Key),模型建议填写 doubao-seed-rerank。'
|
||||
},
|
||||
lkeap: {
|
||||
secretIdLabel: 'SecretId',
|
||||
secretIdPlaceholder: '腾讯云 API 密钥 SecretId',
|
||||
secretKeyLabel: 'SecretKey',
|
||||
secretKeyPlaceholder: '腾讯云 API 密钥 SecretKey',
|
||||
regionLabel: '地域',
|
||||
regionPlaceholder: 'ap-guangzhou',
|
||||
regionDesc: 'RunRerank 支持 ap-beijing、ap-guangzhou 等,默认 ap-guangzhou',
|
||||
rerankCredentialHint: 'Rerank 使用腾讯云 API 签名(非 OpenAI API Key)。请在云 API 密钥控制台创建 SecretId/SecretKey。'
|
||||
},
|
||||
modelNamePlaceholder: {
|
||||
local: '例如:llama2:latest',
|
||||
remote: '例如:gpt-4, claude-3-opus',
|
||||
|
|
@ -6394,6 +6323,8 @@ export default {
|
|||
capabilityUnconfigured: '未配置'
|
||||
},
|
||||
editor: {
|
||||
reasoningEffortUnsupported: '当前所选模型不支持思考,除「关闭」外的选项将被忽略。',
|
||||
reasoningEffortAlwaysOn: '当前所选模型始终开启思考,无法关闭,只能调整思考强度。',
|
||||
createTitle: '创建智能体',
|
||||
editTitle: '编辑智能体',
|
||||
buttons: {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,105 @@
|
|||
import { computed, ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import i18n from '@/i18n'
|
||||
import { listModelProviders, type ModelProviderOption } from '@/api/initialization'
|
||||
import {
|
||||
loadProvidersForType,
|
||||
mergeProviderIndex,
|
||||
providerDescription,
|
||||
providerIcon,
|
||||
providerLabel,
|
||||
} from '@/stores/modelProvidersState'
|
||||
|
||||
/**
|
||||
* Vendor catalog cache. Every component that renders a vendor (model
|
||||
* editor, model cards, debug drawer) reads through this store so the
|
||||
* frontend keeps no vendor table or naming heuristics of its own — the
|
||||
* backend catalog (GET /api/v1/models/providers) is the single source.
|
||||
*
|
||||
* Providers are fetched once per model type (the backend filters the
|
||||
* built-in model list by type) and merged into an id index so lookups by
|
||||
* provider id work regardless of which type loaded them first.
|
||||
*/
|
||||
export const useModelProvidersStore = defineStore('modelProviders', () => {
|
||||
const byType = ref<Record<string, ModelProviderOption[]>>({})
|
||||
const byId = ref<Record<string, ModelProviderOption>>({})
|
||||
const loadingByType = ref<Record<string, boolean>>({})
|
||||
const pending = new Map<string, Promise<ModelProviderOption[]>>()
|
||||
|
||||
const currentLocale = computed(() => String(i18n.global.locale.value || ''))
|
||||
|
||||
const normalizeType = (modelType?: string) => (modelType || '').trim().toLowerCase()
|
||||
|
||||
/**
|
||||
* Load providers for one model type (once); concurrent callers share the
|
||||
* request. Never rejects: a failed fetch resolves to [] and is NOT cached,
|
||||
* so the next component to mount retries instead of rendering an empty
|
||||
* vendor dropdown for the rest of the session.
|
||||
*/
|
||||
const ensureLoaded = async (modelType?: string, force = false): Promise<ModelProviderOption[]> => {
|
||||
const key = normalizeType(modelType)
|
||||
if (!force && byType.value[key]) return byType.value[key]
|
||||
const inflight = pending.get(key)
|
||||
if (inflight && !force) return inflight
|
||||
|
||||
const request = (async () => {
|
||||
loadingByType.value = { ...loadingByType.value, [key]: true }
|
||||
try {
|
||||
const { providers, cacheable } = await loadProvidersForType(listModelProviders, key)
|
||||
if (!cacheable) return providers
|
||||
byType.value = { ...byType.value, [key]: providers }
|
||||
byId.value = mergeProviderIndex(byId.value, providers)
|
||||
return providers
|
||||
} finally {
|
||||
loadingByType.value = { ...loadingByType.value, [key]: false }
|
||||
}
|
||||
})()
|
||||
pending.set(key, request)
|
||||
// Only drop our own entry: a concurrent force-reload may have replaced it.
|
||||
void request.finally(() => {
|
||||
if (pending.get(key) === request) pending.delete(key)
|
||||
})
|
||||
return request
|
||||
}
|
||||
|
||||
const providersFor = (modelType?: string): ModelProviderOption[] => byType.value[normalizeType(modelType)] || []
|
||||
|
||||
const isLoading = (modelType?: string): boolean => !!loadingByType.value[normalizeType(modelType)]
|
||||
|
||||
const providerById = (id?: string | null): ModelProviderOption | undefined => {
|
||||
if (!id) return undefined
|
||||
return byId.value[id]
|
||||
}
|
||||
|
||||
const iconFor = (id?: string | null): string => providerIcon(providerById(id))
|
||||
|
||||
const labelFor = (id?: string | null, locale?: string): string => {
|
||||
const provider = providerById(id)
|
||||
if (!provider) return id || ''
|
||||
return providerLabel(provider, locale ?? currentLocale.value)
|
||||
}
|
||||
|
||||
const descriptionFor = (id?: string | null, locale?: string): string =>
|
||||
providerDescription(providerById(id), locale ?? currentLocale.value)
|
||||
|
||||
const reset = () => {
|
||||
byType.value = {}
|
||||
byId.value = {}
|
||||
loadingByType.value = {}
|
||||
pending.clear()
|
||||
}
|
||||
|
||||
return {
|
||||
byType,
|
||||
byId,
|
||||
currentLocale,
|
||||
ensureLoaded,
|
||||
providersFor,
|
||||
isLoading,
|
||||
providerById,
|
||||
iconFor,
|
||||
labelFor,
|
||||
descriptionFor,
|
||||
reset,
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,224 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import type { ModelProviderOption } from '@/api/initialization'
|
||||
|
||||
import {
|
||||
credentialLabelForModelType,
|
||||
extraFieldLabel,
|
||||
extraFieldsForModelType,
|
||||
loadProvidersForType,
|
||||
mergeProviderIndex,
|
||||
normalizeModelType,
|
||||
pickLocalized,
|
||||
providerDescription,
|
||||
providerIcon,
|
||||
providerLabel,
|
||||
sortProviders,
|
||||
} from './modelProvidersState.ts'
|
||||
|
||||
/** loadProvidersForType logs failures; keep the test output readable. */
|
||||
async function withoutConsoleError<T>(run: () => Promise<T>): Promise<T> {
|
||||
const original = console.error
|
||||
console.error = () => {}
|
||||
try {
|
||||
return await run()
|
||||
} finally {
|
||||
console.error = original
|
||||
}
|
||||
}
|
||||
|
||||
const svgIcon = 'data:image/svg+xml;base64,PHN2Zy8+'
|
||||
|
||||
function provider(overrides: Partial<ModelProviderOption> & Pick<ModelProviderOption, 'value'>): ModelProviderOption {
|
||||
return {
|
||||
label: overrides.value,
|
||||
description: '',
|
||||
defaultUrls: {},
|
||||
modelTypes: ['chat'],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test('providerLabel uses labels[locale], then the same language, then label', () => {
|
||||
const lkeap = provider({
|
||||
value: 'lkeap',
|
||||
label: 'Tencent Cloud LKEAP',
|
||||
labels: { 'zh-CN': '腾讯云 LKEAP' },
|
||||
})
|
||||
assert.equal(providerLabel(lkeap, 'zh-CN'), '腾讯云 LKEAP')
|
||||
assert.equal(providerLabel(lkeap, 'zh-TW'), '腾讯云 LKEAP', 'language match without exact region')
|
||||
assert.equal(providerLabel(lkeap, 'en-US'), 'Tencent Cloud LKEAP')
|
||||
assert.equal(providerLabel(lkeap, 'ja-JP'), 'Tencent Cloud LKEAP')
|
||||
assert.equal(providerLabel(lkeap), 'Tencent Cloud LKEAP')
|
||||
assert.equal(providerLabel(null, 'zh-CN'), '')
|
||||
})
|
||||
|
||||
test('providerLabel falls back to the id when the vendor ships no label', () => {
|
||||
assert.equal(providerLabel(provider({ value: 'custom', label: '' }), 'en-US'), 'custom')
|
||||
})
|
||||
|
||||
test('pickLocalized ignores empty localized strings', () => {
|
||||
assert.equal(pickLocalized({ 'zh-CN': ' ' }, 'zh-CN', 'fallback'), 'fallback')
|
||||
assert.equal(pickLocalized(undefined, 'zh-CN', 'fallback'), 'fallback')
|
||||
assert.equal(pickLocalized({ 'zh-CN': 'x' }, undefined, 'fallback'), 'fallback')
|
||||
})
|
||||
|
||||
test('providerDescription mirrors the label lookup', () => {
|
||||
const p = provider({ value: 'x', description: 'gpt-4o, o3', descriptions: { 'zh-CN': 'gpt-4o、o3 等' } })
|
||||
assert.equal(providerDescription(p, 'zh-CN'), 'gpt-4o、o3 等')
|
||||
assert.equal(providerDescription(p, 'ru-RU'), 'gpt-4o, o3')
|
||||
})
|
||||
|
||||
test('providerIcon only accepts data image URIs', () => {
|
||||
assert.equal(providerIcon(provider({ value: 'a', icon: svgIcon })), svgIcon)
|
||||
assert.equal(providerIcon(provider({ value: 'b' })), '')
|
||||
assert.equal(providerIcon(provider({ value: 'c', icon: 'https://evil.example/x.svg' })), '')
|
||||
assert.equal(providerIcon(undefined), '')
|
||||
})
|
||||
|
||||
test('extraFieldsForModelType honours model_types in either naming scheme', () => {
|
||||
const fields = [
|
||||
{ key: 'api_version', label: 'API Version', type: 'string' },
|
||||
{ key: 'secret_key', label: 'Secret Key', type: 'password', model_types: ['Rerank'], secret: true },
|
||||
{ key: 'region', label: 'Region', type: 'string', model_types: ['rerank'] },
|
||||
{ key: '', label: 'broken', type: 'string' },
|
||||
]
|
||||
assert.deepEqual(extraFieldsForModelType(fields, 'rerank').map((f) => f.key), ['api_version', 'secret_key', 'region'])
|
||||
assert.deepEqual(extraFieldsForModelType(fields, 'chat').map((f) => f.key), ['api_version'])
|
||||
assert.deepEqual(extraFieldsForModelType(fields, 'KnowledgeQA').map((f) => f.key), ['api_version'])
|
||||
assert.deepEqual(extraFieldsForModelType(undefined, 'chat'), [])
|
||||
})
|
||||
|
||||
test('normalizeModelType maps backend names onto editor names', () => {
|
||||
assert.equal(normalizeModelType('KnowledgeQA'), 'chat')
|
||||
assert.equal(normalizeModelType('VLLM'), 'vllm')
|
||||
assert.equal(normalizeModelType('embedding'), 'embedding')
|
||||
assert.equal(normalizeModelType(''), '')
|
||||
})
|
||||
|
||||
test('extraFieldLabel localizes with the same fallback chain', () => {
|
||||
const field = { key: 'region', label: 'Region', labels: { 'zh-CN': '地域' }, type: 'string' }
|
||||
assert.equal(extraFieldLabel(field, 'zh-CN'), '地域')
|
||||
assert.equal(extraFieldLabel(field, 'en-US'), 'Region')
|
||||
assert.equal(extraFieldLabel({ key: 'k', label: '', type: 'string' }), 'k')
|
||||
})
|
||||
|
||||
test('sortProviders orders by backend order then label', () => {
|
||||
const sorted = sortProviders([
|
||||
provider({ value: 'generic', label: 'Custom', order: 99 }),
|
||||
provider({ value: 'openai', label: 'OpenAI', order: 30 }),
|
||||
provider({ value: 'zeta', label: 'Zeta' }),
|
||||
provider({ value: 'aliyun', label: 'Aliyun', order: 30 }),
|
||||
])
|
||||
assert.deepEqual(sorted.map((p) => p.value), ['aliyun', 'openai', 'generic', 'zeta'])
|
||||
})
|
||||
|
||||
test('sortProviders survives rows with neither label nor value', () => {
|
||||
const sorted = sortProviders([
|
||||
{ description: '', defaultUrls: {}, modelTypes: [] } as unknown as ModelProviderOption,
|
||||
provider({ value: 'openai', label: 'OpenAI' }),
|
||||
])
|
||||
assert.equal(sorted.length, 2)
|
||||
})
|
||||
|
||||
test('loadProvidersForType caches a successful list, sorted and id-filtered', async () => {
|
||||
const seen: Array<string | undefined> = []
|
||||
const result = await loadProvidersForType(async (type) => {
|
||||
seen.push(type)
|
||||
return [
|
||||
provider({ value: 'zeta', label: 'Zeta' }),
|
||||
{ value: '', label: 'broken' },
|
||||
null,
|
||||
provider({ value: 'openai', label: 'OpenAI', order: 1 }),
|
||||
]
|
||||
}, 'chat')
|
||||
assert.deepEqual(seen, ['chat'])
|
||||
assert.equal(result.cacheable, true)
|
||||
assert.deepEqual(result.providers.map((p) => p.value), ['openai', 'zeta'])
|
||||
})
|
||||
|
||||
test('loadProvidersForType passes undefined for the all-types key', async () => {
|
||||
const seen: Array<string | undefined> = []
|
||||
await loadProvidersForType(async (type) => { seen.push(type); return [] }, '')
|
||||
assert.deepEqual(seen, [undefined])
|
||||
})
|
||||
|
||||
test('loadProvidersForType caches a genuinely empty catalog', async () => {
|
||||
const result = await loadProvidersForType(async () => [], 'rerank')
|
||||
assert.deepEqual(result, { providers: [], cacheable: true })
|
||||
})
|
||||
|
||||
test('loadProvidersForType never caches a failed or malformed response', async () => {
|
||||
await withoutConsoleError(async () => {
|
||||
const failed = await loadProvidersForType(async () => { throw new Error('502') }, 'chat')
|
||||
assert.deepEqual(failed, { providers: [], cacheable: false }, 'a transient failure must be retried')
|
||||
})
|
||||
for (const malformed of [null, undefined, { data: [] }, 'nope']) {
|
||||
const result = await loadProvidersForType(async () => malformed, 'chat')
|
||||
assert.deepEqual(result, { providers: [], cacheable: false })
|
||||
}
|
||||
})
|
||||
|
||||
test('mergeProviderIndex keeps catalog models collected across model types', () => {
|
||||
const chat = provider({ value: 'openai', models: [{ id: 'gpt-4o', name: 'GPT-4o', type: 'chat' }] })
|
||||
const embedding = provider({
|
||||
value: 'openai',
|
||||
models: [
|
||||
{ id: 'text-embedding-3-large', name: 'Embedding 3 Large', type: 'embedding' },
|
||||
{ id: 'gpt-4o', name: 'GPT-4o', type: 'chat' },
|
||||
],
|
||||
})
|
||||
const index = mergeProviderIndex(mergeProviderIndex({}, [chat]), [embedding])
|
||||
assert.deepEqual(index.openai.models?.map((m) => m.id), ['gpt-4o', 'text-embedding-3-large'])
|
||||
assert.equal(Object.keys(index).length, 1)
|
||||
})
|
||||
|
||||
test('mergeProviderIndex tolerates missing values and model lists', () => {
|
||||
const base = mergeProviderIndex({}, [
|
||||
provider({ value: 'openai' }),
|
||||
{ label: 'no id' } as unknown as ModelProviderOption,
|
||||
])
|
||||
assert.deepEqual(Object.keys(base), ['openai'])
|
||||
// A later fetch without `models` must not wipe what an earlier one collected.
|
||||
const withModels = mergeProviderIndex(
|
||||
mergeProviderIndex({}, [provider({ value: 'openai', models: [{ id: 'gpt-4o', name: 'GPT-4o', type: 'chat' }] })]),
|
||||
[provider({ value: 'openai', label: 'OpenAI' })],
|
||||
)
|
||||
assert.deepEqual(withModels.openai.models?.map((m) => m.id), ['gpt-4o'])
|
||||
assert.equal(withModels.openai.label, 'OpenAI', 'fresh metadata still wins')
|
||||
})
|
||||
|
||||
test('credentialLabelForModelType follows the vendor declaration, not a hardcoded table', () => {
|
||||
const labels = [
|
||||
{
|
||||
label: 'SecretId',
|
||||
labels: { 'zh-CN': 'SecretId(TC3 签名)' },
|
||||
placeholder: 'AKID...',
|
||||
hint: 'not an sk- key',
|
||||
model_types: ['Rerank'],
|
||||
required: true,
|
||||
},
|
||||
]
|
||||
// The signed rerank API renames the field; chat on the same vendor does not.
|
||||
const rerank = credentialLabelForModelType(labels, 'rerank')
|
||||
assert.equal(rerank?.label, 'SecretId')
|
||||
assert.equal(rerank?.required, true)
|
||||
assert.equal(credentialLabelForModelType(labels, 'chat'), null)
|
||||
assert.equal(credentialLabelForModelType(labels, 'embedding'), null)
|
||||
|
||||
// Backend spelling of the model type resolves the same way.
|
||||
assert.equal(credentialLabelForModelType(labels, 'Rerank')?.label, 'SecretId')
|
||||
|
||||
// Vendors that take a plain API key declare nothing.
|
||||
assert.equal(credentialLabelForModelType(undefined, 'rerank'), null)
|
||||
assert.equal(credentialLabelForModelType([], 'rerank'), null)
|
||||
|
||||
// An entry without a model_types filter applies to every type.
|
||||
const everywhere = [{ label: 'Access Key' }]
|
||||
assert.equal(credentialLabelForModelType(everywhere, 'chat')?.label, 'Access Key')
|
||||
|
||||
// Localization goes through the same picker as every other vendor string.
|
||||
assert.equal(pickLocalized(rerank?.labels, 'zh-CN', rerank!.label), 'SecretId(TC3 签名)')
|
||||
assert.equal(pickLocalized(rerank?.labels, 'en-US', rerank!.label), 'SecretId')
|
||||
})
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
/**
|
||||
* Pure helpers behind the modelProviders store. Kept free of Pinia / API
|
||||
* imports so they can be unit-tested under node:test.
|
||||
*
|
||||
* Every vendor fact the UI renders (name, description, icon, extra fields,
|
||||
* catalog models) comes from the backend catalog (internal/handler/
|
||||
* model_catalog.go); these helpers only pick the right locale / model type.
|
||||
*/
|
||||
import type {
|
||||
ModelProviderCredentialLabel,
|
||||
ModelProviderExtraField,
|
||||
ModelProviderOption,
|
||||
} from '@/api/initialization'
|
||||
|
||||
/** Editor model types → backend ModelType names used by ExtraField.model_types. */
|
||||
const FRONTEND_TO_BACKEND_MODEL_TYPE: Record<string, string> = {
|
||||
chat: 'KnowledgeQA',
|
||||
embedding: 'Embedding',
|
||||
rerank: 'Rerank',
|
||||
vllm: 'VLLM',
|
||||
asr: 'ASR',
|
||||
}
|
||||
|
||||
const BACKEND_TO_FRONTEND_MODEL_TYPE: Record<string, string> = Object.fromEntries(
|
||||
Object.entries(FRONTEND_TO_BACKEND_MODEL_TYPE).map(([front, back]) => [back, front]),
|
||||
)
|
||||
|
||||
/** Normalize either naming ("chat" / "KnowledgeQA") to the editor's lowercase form. */
|
||||
export function normalizeModelType(type: string | null | undefined): string {
|
||||
if (!type) return ''
|
||||
const trimmed = String(type).trim()
|
||||
if (FRONTEND_TO_BACKEND_MODEL_TYPE[trimmed]) return trimmed
|
||||
return BACKEND_TO_FRONTEND_MODEL_TYPE[trimmed] || trimmed.toLowerCase()
|
||||
}
|
||||
|
||||
/** Whether a field's model_types filter admits the given editor model type. */
|
||||
export function extraFieldAppliesTo(field: Pick<ModelProviderExtraField, 'model_types'>, modelType: string): boolean {
|
||||
const restricted = field.model_types
|
||||
if (!restricted || restricted.length === 0) return true
|
||||
const wanted = normalizeModelType(modelType)
|
||||
return restricted.some((entry) => normalizeModelType(entry) === wanted)
|
||||
}
|
||||
|
||||
/** Extra fields to render for a provider at one model type. */
|
||||
export function extraFieldsForModelType(
|
||||
fields: ReadonlyArray<ModelProviderExtraField> | null | undefined,
|
||||
modelType: string,
|
||||
): ModelProviderExtraField[] {
|
||||
if (!fields || fields.length === 0) return []
|
||||
return fields.filter((field) => !!field?.key && extraFieldAppliesTo(field, modelType))
|
||||
}
|
||||
|
||||
/**
|
||||
* The credential naming to use at one model type, or null when the vendor
|
||||
* takes a plain API key. First match wins, and an entry without a
|
||||
* `model_types` filter applies everywhere — same rule as extra fields.
|
||||
*/
|
||||
export function credentialLabelForModelType(
|
||||
labels: ReadonlyArray<ModelProviderCredentialLabel> | null | undefined,
|
||||
modelType: string,
|
||||
): ModelProviderCredentialLabel | null {
|
||||
if (!labels || labels.length === 0) return null
|
||||
return labels.find((label) => !!label?.label && extraFieldAppliesTo(label, modelType)) || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick a localized string from a `labels`-style map.
|
||||
*
|
||||
* Order: exact locale (`zh-CN`) → same language with any region (`zh-*`) →
|
||||
* the plain fallback. Empty strings never win.
|
||||
*/
|
||||
export function pickLocalized(
|
||||
localized: Record<string, string> | null | undefined,
|
||||
locale: string | null | undefined,
|
||||
fallback: string,
|
||||
): string {
|
||||
if (localized && locale) {
|
||||
const exact = localized[locale]
|
||||
if (typeof exact === 'string' && exact.trim()) return exact
|
||||
const language = locale.split(/[-_]/)[0]?.toLowerCase()
|
||||
if (language) {
|
||||
for (const [key, value] of Object.entries(localized)) {
|
||||
if (key.split(/[-_]/)[0]?.toLowerCase() === language && typeof value === 'string' && value.trim()) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
export function providerLabel(provider: ModelProviderOption | null | undefined, locale?: string): string {
|
||||
if (!provider) return ''
|
||||
return pickLocalized(provider.labels, locale, provider.label || provider.value || '')
|
||||
}
|
||||
|
||||
export function providerDescription(provider: ModelProviderOption | null | undefined, locale?: string): string {
|
||||
if (!provider) return ''
|
||||
return pickLocalized(provider.descriptions, locale, provider.description || '')
|
||||
}
|
||||
|
||||
/** `<img src>`-ready icon, or '' when the vendor ships none. */
|
||||
export function providerIcon(provider: ModelProviderOption | null | undefined): string {
|
||||
const icon = provider?.icon
|
||||
return typeof icon === 'string' && icon.startsWith('data:image/') ? icon : ''
|
||||
}
|
||||
|
||||
export function extraFieldLabel(field: ModelProviderExtraField, locale?: string): string {
|
||||
return pickLocalized(field.labels, locale, field.label || field.key)
|
||||
}
|
||||
|
||||
/** Stable display order: backend `order`, then label. */
|
||||
export function sortProviders(providers: ReadonlyArray<ModelProviderOption>): ModelProviderOption[] {
|
||||
return [...providers].sort((a, b) => {
|
||||
const orderA = typeof a.order === 'number' ? a.order : Number.MAX_SAFE_INTEGER
|
||||
const orderB = typeof b.order === 'number' ? b.order : Number.MAX_SAFE_INTEGER
|
||||
if (orderA !== orderB) return orderA - orderB
|
||||
return String(a.label || a.value || '').localeCompare(String(b.label || b.value || ''))
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch + normalize the vendor list for one model type.
|
||||
*
|
||||
* `cacheable` is false for a failed or malformed response so the caller keeps
|
||||
* no cache entry and the next component to mount retries; caching a transient
|
||||
* failure would blank the vendor dropdown for the rest of the session.
|
||||
* An empty-but-valid list IS cacheable — that is a real answer.
|
||||
*/
|
||||
export async function loadProvidersForType(
|
||||
fetcher: (modelType?: string) => Promise<unknown>,
|
||||
modelType: string,
|
||||
): Promise<{ providers: ModelProviderOption[]; cacheable: boolean }> {
|
||||
try {
|
||||
const raw = await fetcher(modelType || undefined)
|
||||
if (!Array.isArray(raw)) return { providers: [], cacheable: false }
|
||||
const providers = (raw as ModelProviderOption[]).filter((p) => !!p && typeof p.value === 'string' && !!p.value)
|
||||
return { providers: sortProviders(providers), cacheable: true }
|
||||
} catch (error) {
|
||||
console.error('Failed to load model providers', error)
|
||||
return { providers: [], cacheable: false }
|
||||
}
|
||||
}
|
||||
|
||||
/** Merge a freshly fetched list into the id index without dropping models seen for other types. */
|
||||
export function mergeProviderIndex(
|
||||
index: Record<string, ModelProviderOption>,
|
||||
providers: ReadonlyArray<ModelProviderOption>,
|
||||
): Record<string, ModelProviderOption> {
|
||||
const next = { ...index }
|
||||
for (const provider of providers) {
|
||||
if (!provider?.value) continue
|
||||
const existing = next[provider.value]
|
||||
if (!existing) {
|
||||
next[provider.value] = provider
|
||||
continue
|
||||
}
|
||||
const seen = new Set((existing.models || []).filter((model) => !!model?.id).map((model) => model.id))
|
||||
const mergedModels = [
|
||||
...(existing.models || []),
|
||||
...(provider.models || []).filter((model) => !!model?.id && !seen.has(model.id)),
|
||||
]
|
||||
next[provider.value] = { ...existing, ...provider, models: mergedModels }
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
FALLBACK_REASONING_LEVELS,
|
||||
canonicalLevels,
|
||||
clampLevel,
|
||||
levelDescriptionKey,
|
||||
levelEnablesThinking,
|
||||
levelFromLegacy,
|
||||
levelLabelKey,
|
||||
modelCanThink,
|
||||
modelCannotDisableThinking,
|
||||
optionsFor,
|
||||
supportedLevels,
|
||||
} from './reasoningEffort.ts'
|
||||
|
||||
test('levelFromLegacy maps the boolean when no effort is stored', () => {
|
||||
assert.equal(levelFromLegacy(true), 'auto')
|
||||
assert.equal(levelFromLegacy(false), 'off')
|
||||
assert.equal(levelFromLegacy(undefined), 'off')
|
||||
assert.equal(levelFromLegacy(null, ''), 'off')
|
||||
assert.equal(levelFromLegacy(true, ' '), 'auto')
|
||||
})
|
||||
|
||||
test('levelFromLegacy prefers a valid effort over the boolean', () => {
|
||||
assert.equal(levelFromLegacy(false, 'high'), 'high')
|
||||
assert.equal(levelFromLegacy(true, 'off'), 'off')
|
||||
assert.equal(levelFromLegacy(true, ' Medium '), 'medium')
|
||||
assert.equal(levelFromLegacy(true, 'bogus'), 'auto', 'unknown effort falls back to the boolean')
|
||||
assert.equal(levelFromLegacy(false, 'bogus'), 'off')
|
||||
})
|
||||
|
||||
test('levelLabelKey and levelDescriptionKey point at the model.reasoning namespace', () => {
|
||||
assert.equal(levelLabelKey('xhigh'), 'model.reasoning.levels.xhigh')
|
||||
assert.equal(levelDescriptionKey('auto'), 'model.reasoning.levelDescriptions.auto')
|
||||
})
|
||||
|
||||
test('levelEnablesThinking treats everything but off as enabled', () => {
|
||||
assert.equal(levelEnablesThinking('off'), false)
|
||||
assert.equal(levelEnablesThinking(''), false)
|
||||
assert.equal(levelEnablesThinking(undefined), false)
|
||||
assert.equal(levelEnablesThinking('auto'), true)
|
||||
assert.equal(levelEnablesThinking('max'), true)
|
||||
})
|
||||
|
||||
test('optionsFor offers the generic ladder without capabilities', () => {
|
||||
assert.deepEqual(optionsFor(undefined), FALLBACK_REASONING_LEVELS)
|
||||
assert.deepEqual(optionsFor(null), FALLBACK_REASONING_LEVELS)
|
||||
assert.deepEqual(optionsFor({}), FALLBACK_REASONING_LEVELS)
|
||||
assert.notEqual(optionsFor(undefined), FALLBACK_REASONING_LEVELS, 'callers get a fresh array')
|
||||
})
|
||||
|
||||
test('optionsFor follows thinking_levels exactly, in ladder order', () => {
|
||||
assert.deepEqual(optionsFor({ thinking_levels: ['high', 'low', 'medium'] }), ['low', 'medium', 'high'])
|
||||
assert.deepEqual(optionsFor({ thinking_levels: ['auto', 'off'] }), ['off', 'auto'])
|
||||
assert.deepEqual(optionsFor({ thinking_levels: ['max', 'weird', 'xhigh'] }), ['xhigh', 'max'])
|
||||
})
|
||||
|
||||
test('optionsFor never offers off for an always-on reasoning model', () => {
|
||||
// deepseek-reasoner / qwq-plus / gemini-3: the catalog maps `off` to null,
|
||||
// so the backend cannot switch thinking off for them.
|
||||
const alwaysOn = { thinking_levels: ['auto', 'minimal', 'low', 'medium', 'high'] }
|
||||
assert.equal(optionsFor(alwaysOn).includes('off'), false)
|
||||
assert.deepEqual(optionsFor(alwaysOn), ['auto', 'minimal', 'low', 'medium', 'high'])
|
||||
})
|
||||
|
||||
test('optionsFor shows a lone off for a model that cannot think', () => {
|
||||
assert.deepEqual(optionsFor({ thinking_levels: [] }), ['off'])
|
||||
assert.deepEqual(optionsFor({ thinking_levels: ['nonsense'] }), ['off'])
|
||||
})
|
||||
|
||||
test('modelCannotDisableThinking only fires for models with levels but no off', () => {
|
||||
assert.equal(modelCannotDisableThinking({ thinking_levels: ['auto', 'high'] }), true)
|
||||
assert.equal(modelCannotDisableThinking({ thinking_levels: ['off', 'auto'] }), false)
|
||||
assert.equal(modelCannotDisableThinking({ thinking_levels: [] }), false)
|
||||
assert.equal(modelCannotDisableThinking({}), false, 'no capabilities → nothing to claim')
|
||||
assert.equal(modelCannotDisableThinking(undefined), false)
|
||||
assert.equal(modelCannotDisableThinking(null), false)
|
||||
})
|
||||
|
||||
test('clampLevel rescues a stored off when the model cannot be switched off', () => {
|
||||
const alwaysOn = optionsFor({ thinking_levels: ['auto', 'low', 'high'] })
|
||||
assert.equal(clampLevel('off', alwaysOn), 'auto')
|
||||
assert.equal(clampLevel('medium', alwaysOn), 'auto')
|
||||
assert.equal(clampLevel('high', alwaysOn), 'high')
|
||||
// …and a stored graded level collapses to off for a model that cannot think.
|
||||
assert.equal(clampLevel('high', optionsFor({ thinking_levels: [] })), 'off')
|
||||
})
|
||||
|
||||
test('supportedLevels and modelCanThink reflect thinking_levels exactly', () => {
|
||||
assert.deepEqual(supportedLevels({ thinking_levels: ['medium', 'off', 'low'] }), ['off', 'low', 'medium'])
|
||||
assert.deepEqual(supportedLevels({ thinking_levels: [] }), [])
|
||||
assert.deepEqual(supportedLevels(undefined), [])
|
||||
assert.equal(modelCanThink({ thinking_levels: ['auto'] }), true)
|
||||
assert.equal(modelCanThink({ thinking_levels: [] }), false)
|
||||
assert.equal(modelCanThink(undefined), false)
|
||||
})
|
||||
|
||||
test('canonicalLevels normalizes case, drops duplicates and unknown values', () => {
|
||||
assert.deepEqual(canonicalLevels(['HIGH', 'high', 'nope', ' low ']), ['low', 'high'])
|
||||
assert.deepEqual(canonicalLevels(null), [])
|
||||
})
|
||||
|
||||
test('clampLevel keeps supported values and degrades gracefully', () => {
|
||||
const options = ['off', 'auto', 'low', 'high'] as const
|
||||
assert.equal(clampLevel('high', options), 'high')
|
||||
assert.equal(clampLevel('medium', options), 'auto', 'unsupported graded level falls back to auto')
|
||||
assert.equal(clampLevel('', options), 'off')
|
||||
assert.equal(clampLevel(undefined, options), 'off')
|
||||
assert.equal(clampLevel('medium', ['low', 'high']), 'low', 'no off/auto → first supported')
|
||||
assert.equal(clampLevel('medium', []), 'off')
|
||||
})
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
/**
|
||||
* Reasoning-effort helpers shared by the agent editor, the model debug
|
||||
* drawer and the model editor.
|
||||
*
|
||||
* Mirrors internal/models/api.ReasoningEffort: a protocol-neutral thinking
|
||||
* level that vendors map onto their own knobs. `off` disables thinking,
|
||||
* `auto` lets the vendor pick its default intensity, and the graded ladder
|
||||
* (minimal ... max) is clamped by the backend to what the model supports.
|
||||
*
|
||||
* Legacy boolean semantics: `thinking: true` == `auto`, `thinking: false` == `off`.
|
||||
*/
|
||||
|
||||
export const REASONING_LEVELS = [
|
||||
'off',
|
||||
'auto',
|
||||
'minimal',
|
||||
'low',
|
||||
'medium',
|
||||
'high',
|
||||
'xhigh',
|
||||
'max',
|
||||
] as const
|
||||
|
||||
export type ReasoningLevel = (typeof REASONING_LEVELS)[number]
|
||||
|
||||
/** Offered when the selected model has no catalog capabilities yet. */
|
||||
export const FALLBACK_REASONING_LEVELS: ReasoningLevel[] = ['off', 'auto', 'low', 'medium', 'high']
|
||||
|
||||
/** Minimal shape of the backend `capabilities` object we rely on here. */
|
||||
export interface ThinkingCapabilities {
|
||||
thinking_levels?: ReadonlyArray<string> | null
|
||||
}
|
||||
|
||||
export function isReasoningLevel(value: unknown): value is ReasoningLevel {
|
||||
return typeof value === 'string' && (REASONING_LEVELS as ReadonlyArray<string>).includes(value)
|
||||
}
|
||||
|
||||
/** Sort levels into the canonical ladder order, dropping unknown values and duplicates. */
|
||||
export function canonicalLevels(levels: ReadonlyArray<string> | null | undefined): ReasoningLevel[] {
|
||||
if (!levels || levels.length === 0) return []
|
||||
const wanted = new Set(levels.map((level) => String(level).trim().toLowerCase()))
|
||||
return REASONING_LEVELS.filter((level) => wanted.has(level))
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the graded level from a config that may carry only the legacy
|
||||
* boolean. A valid `effort` always wins; otherwise `true` → `auto`,
|
||||
* anything else → `off`.
|
||||
*/
|
||||
export function levelFromLegacy(thinking?: boolean | null, effort?: string | null): ReasoningLevel {
|
||||
const normalized = typeof effort === 'string' ? effort.trim().toLowerCase() : ''
|
||||
if (isReasoningLevel(normalized)) return normalized
|
||||
return thinking === true ? 'auto' : 'off'
|
||||
}
|
||||
|
||||
/** Whether a level asks the model to think at all. */
|
||||
export function levelEnablesThinking(level: string | null | undefined): boolean {
|
||||
return !!level && level !== 'off'
|
||||
}
|
||||
|
||||
/** i18n key of a level's short name. */
|
||||
export function levelLabelKey(level: string): string {
|
||||
return `model.reasoning.levels.${level}`
|
||||
}
|
||||
|
||||
/** i18n key of a level's one-line description. */
|
||||
export function levelDescriptionKey(level: string): string {
|
||||
return `model.reasoning.levelDescriptions.${level}`
|
||||
}
|
||||
|
||||
/** Whether the model can be asked to think (non-empty thinking_levels). */
|
||||
export function modelCanThink(capabilities?: ThinkingCapabilities | null): boolean {
|
||||
return (capabilities?.thinking_levels?.length ?? 0) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Levels the model itself reports, in ladder order. Empty when the model
|
||||
* cannot think (or no capabilities are known).
|
||||
*/
|
||||
export function supportedLevels(capabilities?: ThinkingCapabilities | null): ReasoningLevel[] {
|
||||
return canonicalLevels(capabilities?.thinking_levels)
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for a reasoning-level selector.
|
||||
*
|
||||
* When the model reports capabilities, `thinking_levels` is authoritative and
|
||||
* is followed EXACTLY — including the absence of `off`. Always-on reasoning
|
||||
* models (deepseek-reasoner, qwq-plus, the gemini-3 family, ...) map `off` to
|
||||
* null in the catalog, so offering "关闭" there would promise something the
|
||||
* backend cannot deliver: no switch is sent and the model thinks anyway.
|
||||
*
|
||||
* With no capabilities at all (model list not loaded, local/Ollama model, ...)
|
||||
* the generic off/auto/low/medium/high ladder is offered so the user can still
|
||||
* express a preference; the backend clamps it later.
|
||||
*/
|
||||
export function optionsFor(capabilities?: ThinkingCapabilities | null): ReasoningLevel[] {
|
||||
if (!capabilities || !Array.isArray(capabilities.thinking_levels)) {
|
||||
return [...FALLBACK_REASONING_LEVELS]
|
||||
}
|
||||
const levels = canonicalLevels(capabilities.thinking_levels)
|
||||
// A model that cannot think at all still needs one truthful value to show.
|
||||
return levels.length > 0 ? levels : ['off']
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the model reports capabilities but cannot be switched off — the UI
|
||||
* must say so, otherwise the absence of a "关闭" option looks like a bug.
|
||||
*/
|
||||
export function modelCannotDisableThinking(capabilities?: ThinkingCapabilities | null): boolean {
|
||||
if (!capabilities || !Array.isArray(capabilities.thinking_levels)) return false
|
||||
const levels = canonicalLevels(capabilities.thinking_levels)
|
||||
return levels.length > 0 && !levels.includes('off')
|
||||
}
|
||||
|
||||
/** Pick a level to show for a selector whose current value may be unsupported. */
|
||||
export function clampLevel(level: string | null | undefined, options: ReadonlyArray<ReasoningLevel>): ReasoningLevel {
|
||||
if (options.length === 0) return 'off'
|
||||
const normalized = typeof level === 'string' ? level.trim().toLowerCase() : ''
|
||||
if (isReasoningLevel(normalized) && options.includes(normalized)) return normalized
|
||||
// A stored level the model does not accept — an unsupported rung, or `off`
|
||||
// on an always-on reasoning model — becomes the vendor default.
|
||||
if (normalized && options.includes('auto')) return 'auto'
|
||||
return options.includes('off') ? 'off' : options[0]
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { defaultThinkingControl } from './thinkingControl.ts'
|
||||
|
||||
// Cases mirror internal/models/chat/provider_test.go TestResolveProvider thinking defaults.
|
||||
test('defaultThinkingControl matches backend provider adapters', () => {
|
||||
const cases: Array<[string, string, ReturnType<typeof defaultThinkingControl>]> = [
|
||||
['generic', 'anything', 'chat_template_kwargs'],
|
||||
['nvidia', 'anything', 'chat_template_kwargs'],
|
||||
['litellm', 'anything', 'chat_template_kwargs'],
|
||||
['volcengine', 'doubao', 'thinking_type'],
|
||||
['aliyun', 'qwen3-32b', 'enable_thinking'],
|
||||
['aliyun', 'qwen-plus', 'enable_thinking'],
|
||||
['aliyun', 'gpt-4', 'none'],
|
||||
['lkeap', '', 'thinking_type'],
|
||||
['lkeap', 'deepseek-v3.1', 'thinking_type'],
|
||||
['lkeap', 'deepseek-r1', 'none'],
|
||||
['openai', 'gpt-4o', 'none'],
|
||||
['openai', 'gpt-5', 'none'],
|
||||
['azure_openai', 'gpt-4', 'none'],
|
||||
['deepseek', 'deepseek-chat', 'none'],
|
||||
['zhipu', 'glm-4', 'none'],
|
||||
['gemini', 'gemini-2.0', 'none'],
|
||||
['siliconflow', 'qwen3-8b', 'none'],
|
||||
['hunyuan', 'hunyuan-turbo', 'none'],
|
||||
['moonshot', 'moonshot-v1-8k', 'none'],
|
||||
['weknoracloud', 'anything', 'none'],
|
||||
]
|
||||
for (const [provider, model, want] of cases) {
|
||||
assert.equal(
|
||||
defaultThinkingControl(provider, model),
|
||||
want,
|
||||
`${provider}/${model}`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
|
@ -1,90 +0,0 @@
|
|||
/** Mirrors backend internal/models/provider.IsQwenThinkingModel */
|
||||
export function isQwenThinkingModel(modelName: string): boolean {
|
||||
const lower = modelName.trim().toLowerCase()
|
||||
return (
|
||||
lower.startsWith('qwen3')
|
||||
|| lower.startsWith('qwen-plus')
|
||||
|| lower.startsWith('qwen-max')
|
||||
|| lower.startsWith('qwen-turbo')
|
||||
)
|
||||
}
|
||||
|
||||
/** Mirrors backend internal/models/provider.IsLKEAPDeepSeekR1Model */
|
||||
export function isLkeapDeepSeekR1Model(modelName: string): boolean {
|
||||
return modelName.toLowerCase().includes('deepseek-r1')
|
||||
}
|
||||
|
||||
export type ThinkingControlValue =
|
||||
| 'none'
|
||||
| 'chat_template_kwargs'
|
||||
| 'enable_thinking'
|
||||
| 'thinking_type'
|
||||
|
||||
const THINKING_CONTROL_VALUES: ThinkingControlValue[] = [
|
||||
'none',
|
||||
'chat_template_kwargs',
|
||||
'enable_thinking',
|
||||
'thinking_type',
|
||||
]
|
||||
|
||||
/**
|
||||
* Default thinking_control for provider+model.
|
||||
* Must stay aligned with chat.resolveProvider(...).Thinking() in provider.go.
|
||||
*/
|
||||
export function defaultThinkingControl(
|
||||
provider: string,
|
||||
modelName = '',
|
||||
): ThinkingControlValue {
|
||||
const p = provider.trim().toLowerCase()
|
||||
const model = modelName.trim()
|
||||
|
||||
switch (p) {
|
||||
case 'aliyun':
|
||||
return isQwenThinkingModel(model) ? 'enable_thinking' : 'none'
|
||||
case 'lkeap':
|
||||
// R1 系列后端不发 thinking 参数;其余(含未填模型名)按 LKEAP 的 thinking.type 格式预选
|
||||
if (model && isLkeapDeepSeekR1Model(model)) return 'none'
|
||||
return 'thinking_type'
|
||||
case 'generic':
|
||||
case 'nvidia':
|
||||
case 'litellm':
|
||||
return 'chat_template_kwargs'
|
||||
case 'volcengine':
|
||||
return 'thinking_type'
|
||||
default:
|
||||
// openai, azure_openai, anthropic, zhipu, deepseek, gemini, siliconflow,
|
||||
// hunyuan, moonshot, openrouter, weknoracloud, … → baseProvider / noThinking
|
||||
return 'none'
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve stored extra_config or fall back to the provider default. */
|
||||
export function resolveThinkingControl(
|
||||
saved: string | undefined,
|
||||
provider: string,
|
||||
modelName = '',
|
||||
): ThinkingControlValue {
|
||||
const v = saved?.trim().toLowerCase()
|
||||
if (THINKING_CONTROL_VALUES.includes(v as ThinkingControlValue)) {
|
||||
return v as ThinkingControlValue
|
||||
}
|
||||
return defaultThinkingControl(provider, modelName)
|
||||
}
|
||||
|
||||
/** Whether the debug drawer should expose Think on/off for this saved model. */
|
||||
export function modelSupportsThinking(model: {
|
||||
type: string
|
||||
source: string
|
||||
name: string
|
||||
parameters: {
|
||||
provider?: string
|
||||
extra_config?: { thinking_control?: string }
|
||||
}
|
||||
}): boolean {
|
||||
if (model.type !== 'KnowledgeQA' || model.source !== 'remote') return false
|
||||
return resolveThinkingControl(
|
||||
model.parameters.extra_config?.thinking_control,
|
||||
model.parameters.provider || '',
|
||||
model.name || '',
|
||||
) !== 'none'
|
||||
}
|
||||
|
|
@ -602,14 +602,29 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 思考模式 -->
|
||||
<!-- 思考强度:off / auto + 所选对话模型目录上报的等级 -->
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ $t('agent.editor.thinking') }}</label>
|
||||
<p class="desc">{{ $t('agentEditor.desc.thinking') }}</p>
|
||||
<p v-if="selectedChatModel && !selectedChatModelCanThink" class="desc">
|
||||
{{ $t('agent.editor.reasoningEffortUnsupported') }}
|
||||
</p>
|
||||
<p v-else-if="selectedChatModelAlwaysThinks" class="desc">
|
||||
{{ $t('agent.editor.reasoningEffortAlwaysOn') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="thinkingEnabled" />
|
||||
<t-select v-model="reasoningEffortLevel" class="reasoning-effort-select"
|
||||
:popup-props="{ overlayClassName: 'reasoning-level-select-popup' }">
|
||||
<t-option v-for="level in reasoningEffortOptions" :key="level" :value="level"
|
||||
:label="$t(levelLabelKey(level))" :show-overflow-tooltip="false">
|
||||
<div class="reasoning-level-option">
|
||||
<span class="reasoning-level-option__title">{{ $t(levelLabelKey(level)) }}</span>
|
||||
<span class="reasoning-level-option__hint">{{ $t(levelDescriptionKey(level)) }}</span>
|
||||
</div>
|
||||
</t-option>
|
||||
</t-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -1870,6 +1885,17 @@ import {
|
|||
type RequirementMissKind,
|
||||
type ScopeCapabilities,
|
||||
} from '@/utils/tool-capabilities';
|
||||
import {
|
||||
clampLevel,
|
||||
levelDescriptionKey,
|
||||
levelEnablesThinking,
|
||||
levelFromLegacy,
|
||||
levelLabelKey,
|
||||
modelCanThink,
|
||||
modelCannotDisableThinking,
|
||||
optionsFor,
|
||||
type ReasoningLevel,
|
||||
} from '@/utils/reasoningEffort';
|
||||
|
||||
// File extensions offered in the agent-level chat attachment parsing policy.
|
||||
const CHAT_PARSER_EXTENSIONS = [
|
||||
|
|
@ -2755,6 +2781,7 @@ const defaultFormData = {
|
|||
temperature: 0.7,
|
||||
max_completion_tokens: 0,
|
||||
thinking: false, // 默认禁用思考模式
|
||||
reasoning_effort: 'off', // 思考强度;与 thinking 布尔保持同步
|
||||
citation_enabled: true, // 默认输出知识库/网页来源引用
|
||||
// Agent模式设置
|
||||
max_iterations: 10,
|
||||
|
|
@ -3375,11 +3402,47 @@ const onAgentTypeChange = (val: AgentType) => {
|
|||
}
|
||||
};
|
||||
|
||||
// 思考模式计算属性(直接绑定 boolean)
|
||||
const thinkingEnabled = computed({
|
||||
get: () => formData.value.config.thinking === true,
|
||||
set: (val: boolean) => { formData.value.config.thinking = val; }
|
||||
// 思考强度:reasoning_effort 为准,旧数据只有 thinking 布尔时按 true→auto / false→off 推导。
|
||||
// 写入时同步维护 thinking 布尔,保证旧后端 / 旧读取路径继续工作。
|
||||
const selectedChatModel = computed(() =>
|
||||
allModels.value.find(model => model.id === formData.value.config.model_id),
|
||||
);
|
||||
const selectedChatModelCanThink = computed(() => modelCanThink(selectedChatModel.value?.capabilities));
|
||||
// 所选模型无法关闭思考(deepseek-reasoner / qwq-plus / gemini-3 等)时给出提示,
|
||||
// 否则下拉里没有「关闭」看起来像 bug。
|
||||
const selectedChatModelAlwaysThinks = computed(
|
||||
() => modelCannotDisableThinking(selectedChatModel.value?.capabilities),
|
||||
);
|
||||
// 目录上报 capabilities 时严格按 thinking_levels 出选项(含「没有 off」这一事实);
|
||||
// 没有 capabilities 的模型(本地 / Ollama / 模型列表未加载)才退回通用梯度。
|
||||
const reasoningEffortOptions = computed<ReasoningLevel[]>(() => optionsFor(selectedChatModel.value?.capabilities));
|
||||
const reasoningEffortLevel = computed<ReasoningLevel>({
|
||||
get: () => levelFromLegacy(formData.value.config.thinking, formData.value.config.reasoning_effort),
|
||||
set: (level: ReasoningLevel) => {
|
||||
formData.value.config.reasoning_effort = level;
|
||||
formData.value.config.thinking = levelEnablesThinking(level);
|
||||
},
|
||||
});
|
||||
// 已存等级可能不在所选模型的可用集合里(换模型,或加载了一个旧智能体):
|
||||
// 夹到可用集合上,并同步 thinking 布尔(由 setter 负责),避免界面显示「关闭」
|
||||
// 而后端其实没下发任何开关、模型照样思考。
|
||||
//
|
||||
// 只在模型真正解析出来之后才夹:模型列表异步加载期间 capabilities 还是 undefined,
|
||||
// 此时的通用梯度会把已保存的 max/xhigh 误降级成 auto。
|
||||
const clampReasoningEffortToModel = () => {
|
||||
if (editorInitializing.value || !selectedChatModel.value) return;
|
||||
const clamped = clampLevel(reasoningEffortLevel.value, reasoningEffortOptions.value);
|
||||
if (clamped !== reasoningEffortLevel.value) reasoningEffortLevel.value = clamped;
|
||||
};
|
||||
watch(
|
||||
() => [
|
||||
editorInitializing.value,
|
||||
formData.value.config.model_id,
|
||||
reasoningEffortOptions.value.join(','),
|
||||
].join('|'),
|
||||
() => clampReasoningEffortToModel(),
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// 是否为内置智能体
|
||||
const isBuiltinAgent = computed(() => {
|
||||
|
|
@ -3439,6 +3502,10 @@ watch(() => props.visible, async (val) => {
|
|||
if (agentData.config.thinking == null) {
|
||||
agentData.config.thinking = false;
|
||||
}
|
||||
// Legacy rows carry only the boolean: derive the graded level once so
|
||||
// the selector and the persisted config agree (true → auto, false → off).
|
||||
agentData.config.reasoning_effort = levelFromLegacy(agentData.config.thinking, agentData.config.reasoning_effort);
|
||||
agentData.config.thinking = levelEnablesThinking(agentData.config.reasoning_effort);
|
||||
|
||||
agentData.config.question_suggestions = {
|
||||
starters: {
|
||||
|
|
@ -5204,6 +5271,11 @@ const handleSave = async () => {
|
|||
align-items: flex-start;
|
||||
overflow: hidden;
|
||||
|
||||
.reasoning-effort-select {
|
||||
width: 100%;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
&.setting-control-full {
|
||||
width: 100%;
|
||||
min-width: 100%;
|
||||
|
|
@ -6503,6 +6575,37 @@ const handleSave = async () => {
|
|||
<!-- Non-scoped styles: TDesign teleports the popup outside this component, so
|
||||
scoped selectors can't reach .agent-type-popup .t-select-option. -->
|
||||
<style lang="less">
|
||||
.reasoning-level-select-popup {
|
||||
padding: 4px;
|
||||
|
||||
.t-select-option {
|
||||
height: auto !important;
|
||||
padding: 6px 10px;
|
||||
border-radius: 6px;
|
||||
margin: 2px 0;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
|
||||
.reasoning-level-option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
line-height: 1.35;
|
||||
min-width: 0;
|
||||
|
||||
&__title {
|
||||
font-size: var(--app-text-md);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&__hint {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--td-text-color-placeholder);
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.agent-type-popup {
|
||||
.t-select-option {
|
||||
// 默认 option 是 32px 单行;我们要双行显示,取消固定高度并放宽 padding
|
||||
|
|
|
|||
|
|
@ -102,7 +102,10 @@
|
|||
</div>
|
||||
</div>
|
||||
<p class="model-card__subtitle">
|
||||
<span>{{ vendorLabel(model) }}</span>
|
||||
<span class="model-card__vendor">
|
||||
<img v-if="vendorIcon(model)" :src="vendorIcon(model)" class="model-card__vendor-icon" alt="" />
|
||||
<span>{{ vendorLabel(model) }}</span>
|
||||
</span>
|
||||
<template v-if="model._modelType === 'embedding' && model.dimension">
|
||||
<span class="model-card__sep">·</span>
|
||||
<span>{{ $t('model.editor.dimensionLabel') }} {{ model.dimension }}</span>
|
||||
|
|
@ -293,16 +296,18 @@ import { useAuthStore } from '@/stores/auth'
|
|||
import { useUIStore } from '@/stores/ui'
|
||||
import { focusKbEditorSection } from '@/config/contextualGuides'
|
||||
import { useChatResourcesStore } from '@/stores/chatResources'
|
||||
import { useModelProvidersStore } from '@/stores/modelProviders'
|
||||
import {
|
||||
formatContextWindow,
|
||||
isDefaultContextWindow,
|
||||
effectiveContextWindow,
|
||||
} from '@/utils/contextWindow'
|
||||
|
||||
const { t, te } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
const uiStore = useUIStore()
|
||||
const chatResources = useChatResourcesStore()
|
||||
const providersStore = useModelProvidersStore()
|
||||
const router = useRouter()
|
||||
type ModelType = 'chat' | 'embedding' | 'rerank' | 'vllm' | 'asr'
|
||||
type FilterType = 'all' | ModelType
|
||||
|
|
@ -369,12 +374,17 @@ function convertToLegacyFormat(model: ModelConfig) {
|
|||
supportsVision: model.parameters.supports_vision || false,
|
||||
contextWindow: model.parameters.context_window || undefined,
|
||||
maxConcurrency: model.parameters.max_concurrency,
|
||||
maxOutputTokens: model.parameters.max_output_tokens || undefined,
|
||||
customHeaders: model.parameters.custom_headers
|
||||
? Object.entries(model.parameters.custom_headers).map(([key, value]) => ({ key, value: String(value) }))
|
||||
: [],
|
||||
lkeapRegion: model.parameters.extra_config?.region || 'ap-guangzhou',
|
||||
// 原始存库值,编辑弹窗内再 resolve(避免打开时被推断值覆盖)
|
||||
thinkingControl: model.parameters.extra_config?.thinking_control,
|
||||
// 厂商额外字段 / 高级覆盖原样带入编辑器(thinking_control 单独拆出,仅旧数据才有)
|
||||
extraConfig: Object.fromEntries(
|
||||
Object.entries(model.parameters.extra_config || {}).filter(([key]) => key !== 'thinking_control'),
|
||||
) as Record<string, string>,
|
||||
thinkingControl: model.parameters.extra_config?.thinking_control || '',
|
||||
spec: model.parameters.spec || null,
|
||||
capabilities: model.capabilities,
|
||||
_modelType: backendTypeToModelType[model.type] || 'chat' as ModelType,
|
||||
// Preserve the credential metadata map so the editor dialog can render
|
||||
// the "Configured" state without an extra round-trip.
|
||||
|
|
@ -423,15 +433,19 @@ const sourceLabel = (type: ModelType) => {
|
|||
}
|
||||
|
||||
// Maps a backend `provider` id (e.g. "openai", "aliyun", "weknoracloud")
|
||||
// to its localized short label. Reuses the same i18n keys the editor's
|
||||
// provider dropdown uses, so the model card and the editor stay in sync
|
||||
// when a provider is renamed. Falls back to '' when the backend didn't
|
||||
// store a provider — caller falls back to sourceLabel().
|
||||
// to the vendor's localized name from the backend catalog (modelProviders
|
||||
// store), so the model card and the editor dropdown always agree. Falls
|
||||
// back to the raw id when the catalog has not loaded yet, and to '' when
|
||||
// the backend didn't store a provider — caller falls back to sourceLabel().
|
||||
const providerLabel = (model: any): string => {
|
||||
const id = model.provider
|
||||
if (!id) return ''
|
||||
const key = `model.editor.providers.${id}.label`
|
||||
return te(key) ? t(key) : id
|
||||
return providersStore.labelFor(id, String(locale.value || '')) || id
|
||||
}
|
||||
|
||||
const vendorIcon = (model: any): string => {
|
||||
if (model.source === 'local' || !model.provider) return ''
|
||||
return providersStore.iconFor(model.provider)
|
||||
}
|
||||
|
||||
// What the vendor chip on a card shows. Keeps the chip text uniformly
|
||||
|
|
@ -479,6 +493,8 @@ const emptyHint = computed(() => {
|
|||
// 加载模型列表
|
||||
const loadModels = async () => {
|
||||
loading.value = true
|
||||
// 厂商图标 / 本地化名称来自目录 store;与模型列表并行加载,失败不影响卡片渲染。
|
||||
void providersStore.ensureLoaded('').catch(() => {})
|
||||
try {
|
||||
const models = await listModels()
|
||||
allModels.value = models
|
||||
|
|
@ -596,21 +612,46 @@ const handleModelSave = async (modelData: any) => {
|
|||
const trimmedAppSecret = (modelData.appSecret ?? '').trim()
|
||||
const appSecretFields: { app_secret?: string } =
|
||||
!editingModel.value && trimmedAppSecret ? { app_secret: trimmedAppSecret } : {}
|
||||
// extra_config: vendor extra fields + advanced overrides (already trimmed
|
||||
// by the editor) plus the legacy thinking_control for rows that still
|
||||
// carry it. Empty values are dropped so cleared keys disappear.
|
||||
const extraConfig: Record<string, string> = {}
|
||||
if (modelData.provider === 'lkeap' && saveType === 'rerank') {
|
||||
extraConfig.region = (modelData.lkeapRegion || 'ap-guangzhou').trim()
|
||||
if (modelData.source === 'remote') {
|
||||
for (const [key, value] of Object.entries(modelData.extraConfig || {})) {
|
||||
const trimmed = String(value ?? '').trim()
|
||||
if (key && trimmed) extraConfig[key] = trimmed
|
||||
}
|
||||
const legacyThinking = String(modelData.thinkingControl || '').trim()
|
||||
if (saveType === 'chat' && legacyThinking) {
|
||||
extraConfig.thinking_control = legacyThinking
|
||||
} else {
|
||||
delete extraConfig.thinking_control
|
||||
}
|
||||
}
|
||||
if (
|
||||
saveType === 'chat'
|
||||
&& modelData.source === 'remote'
|
||||
&& modelData.thinkingControl
|
||||
) {
|
||||
extraConfig.thinking_control = modelData.thinkingControl
|
||||
}
|
||||
const extraConfigFields = Object.keys(extraConfig).length > 0
|
||||
// Always send extra_config for remote models, even when it ends up empty:
|
||||
// PUT /models/:id restores the stored map when the field is absent
|
||||
// (internal/handler/model.go), so omitting it would make "clear the last
|
||||
// vendor field / protocol override" silently no-op. Local rows keep the
|
||||
// omit-when-empty behaviour — this form never edits their extra_config.
|
||||
const extraConfigFields = modelData.source === 'remote'
|
||||
? { extra_config: extraConfig }
|
||||
: {}
|
||||
|
||||
// parameters.spec: keep whatever the row already had, replace compat with
|
||||
// the (validated) JSON from the advanced textarea; drop spec when empty.
|
||||
const specText = String(modelData.specCompat ?? '').trim()
|
||||
const baseSpec = (modelData.spec && typeof modelData.spec === 'object') ? { ...modelData.spec } : {}
|
||||
if (specText) {
|
||||
const compat = JSON.parse(specText)
|
||||
if (!compat || typeof compat !== 'object' || Array.isArray(compat)) {
|
||||
throw new Error(t('model.editor.advanced.compat.invalid'))
|
||||
}
|
||||
baseSpec.compat = compat
|
||||
} else {
|
||||
delete baseSpec.compat
|
||||
}
|
||||
const specFields = Object.keys(baseSpec).length > 0 ? { spec: baseSpec } : {}
|
||||
|
||||
const apiModelData: ModelConfig = {
|
||||
name: modelData.modelName.trim(),
|
||||
display_name: modelData.displayName?.trim() || '',
|
||||
|
|
@ -640,6 +681,11 @@ const handleModelSave = async (modelData: any) => {
|
|||
&& Number(modelData.contextWindow) >= 1024
|
||||
? { context_window: Math.round(Number(modelData.contextWindow)) }
|
||||
: {}),
|
||||
...((saveType === 'chat' || saveType === 'vllm')
|
||||
&& Number(modelData.maxOutputTokens) > 0
|
||||
? { max_output_tokens: Math.round(Number(modelData.maxOutputTokens)) }
|
||||
: {}),
|
||||
...specFields,
|
||||
// 后台并发上限:仅 chat/embedding/vllm 受治理,>0 才写入(0/空沿用全局默认)。
|
||||
...(['chat', 'embedding', 'vllm'].includes(saveType)
|
||||
&& Number(modelData.maxConcurrency) > 0
|
||||
|
|
@ -1055,15 +1101,50 @@ onMounted(() => {
|
|||
}
|
||||
|
||||
.model-card__subtitle {
|
||||
// A flex row, not inline text: .model-card__vendor is an inline-flex box
|
||||
// whose baseline comes from its first item — the 14px icon, whose baseline
|
||||
// is its bottom edge — so as inline content it sat a couple of pixels off
|
||||
// the "· 200K" beside it. Aligning the row by centre instead of by
|
||||
// baseline puts every part of the line on one optical line.
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
margin: 2px 0 0;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.model-card__vendor {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
|
||||
// The vendor name is the only part long enough to need truncating; the
|
||||
// context window and the badges after it must stay readable.
|
||||
> span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.model-card__sep,
|
||||
.model-card__ctx,
|
||||
.model-card__vision {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.model-card__vendor-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex-shrink: 0;
|
||||
border-radius: 3px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.model-card__sep {
|
||||
margin: 0 4px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
|
|
|
|||
|
|
@ -56,7 +56,10 @@ func (e *AgentEngine) breakdownContext(messages []chat.Message, tools []chat.Too
|
|||
}
|
||||
}
|
||||
|
||||
if reasoning := est.EstimateString(msg.ReasoningContent); reasoning > 0 {
|
||||
// Reasoning is the text plus the opaque artifacts replayed with it, so
|
||||
// the line stays comparable to the message total the estimator reports.
|
||||
if reasoning := est.EstimateString(msg.ReasoningContent) +
|
||||
est.EstimateReasoningArtifacts(msg); reasoning > 0 {
|
||||
b.Reasoning += reasoning
|
||||
}
|
||||
for _, tc := range msg.ToolCalls {
|
||||
|
|
|
|||
|
|
@ -894,6 +894,8 @@ func (e *AgentEngine) runReActIteration(
|
|||
Iteration: state.CurrentRound,
|
||||
Thought: response.Content,
|
||||
ReasoningContent: response.ReasoningContent,
|
||||
ReasoningSignature: response.ReasoningSignature,
|
||||
ReasoningMetadata: response.ReasoningMetadata,
|
||||
ToolCalls: make([]types.ToolCall, 0),
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
|
@ -978,9 +980,11 @@ func (e *AgentEngine) runReActIteration(
|
|||
canContinue := e.withinIterationBudget(nextRound) || e.steerOverruns < maxSteerOverruns
|
||||
if canContinue {
|
||||
*messagesPtr = append(*messagesPtr, chat.Message{
|
||||
Role: "assistant",
|
||||
Content: verdict.finalAnswer,
|
||||
ReasoningContent: response.ReasoningContent,
|
||||
Role: "assistant",
|
||||
Content: verdict.finalAnswer,
|
||||
ReasoningContent: response.ReasoningContent,
|
||||
ReasoningSignature: response.ReasoningSignature,
|
||||
ReasoningMetadata: response.ReasoningMetadata,
|
||||
})
|
||||
injected := e.drainSteerMessages(ctx, state, messagesPtr, sessionID, assistantMessageID)
|
||||
if injected > 0 {
|
||||
|
|
|
|||
|
|
@ -914,12 +914,18 @@ func (e *AgentEngine) appendToolResults(
|
|||
messages []chat.Message,
|
||||
step types.AgentStep,
|
||||
) []chat.Message {
|
||||
// Add assistant message with tool calls (if any)
|
||||
if step.Thought != "" || len(step.ToolCalls) > 0 || step.ReasoningContent != "" {
|
||||
// Add assistant message with tool calls (if any). The reasoning artifacts
|
||||
// count as content of their own: an Anthropic round can consist purely of
|
||||
// a redacted_thinking block, and dropping the turn loses state the next
|
||||
// request has to replay.
|
||||
if step.Thought != "" || len(step.ToolCalls) > 0 || step.ReasoningContent != "" ||
|
||||
step.ReasoningSignature != "" || len(step.ReasoningMetadata) > 0 {
|
||||
assistantMsg := chat.Message{
|
||||
Role: "assistant",
|
||||
Content: step.Thought,
|
||||
ReasoningContent: step.ReasoningContent,
|
||||
Role: "assistant",
|
||||
Content: step.Thought,
|
||||
ReasoningContent: step.ReasoningContent,
|
||||
ReasoningSignature: step.ReasoningSignature,
|
||||
ReasoningMetadata: step.ReasoningMetadata,
|
||||
}
|
||||
|
||||
// Add tool calls to assistant message (following OpenAI format)
|
||||
|
|
|
|||
|
|
@ -22,10 +22,14 @@ import (
|
|||
type streamLLMResult struct {
|
||||
Content string
|
||||
ReasoningContent string // accumulated reasoning content, kept separate from answer
|
||||
ToolCalls []types.LLMToolCall
|
||||
Usage *types.TokenUsage
|
||||
FinishReason string // actual finish_reason from LLM (captured from last stream chunk)
|
||||
StreamError string // error message from stream (e.g., timeout), kept separate from Content
|
||||
// ReasoningSignature / ReasoningMetadata arrive on the closing chunk's
|
||||
// Data and must be persisted with the step for replay.
|
||||
ReasoningSignature string
|
||||
ReasoningMetadata types.ProviderMetadata
|
||||
ToolCalls []types.LLMToolCall
|
||||
Usage *types.TokenUsage
|
||||
FinishReason string // actual finish_reason from LLM (captured from last stream chunk)
|
||||
StreamError string // error message from stream (e.g., timeout), kept separate from Content
|
||||
}
|
||||
|
||||
// streamLLMToEventBus streams LLM response through EventBus (generic method)
|
||||
|
|
@ -133,6 +137,12 @@ func (e *AgentEngine) streamLLMToEventBus(
|
|||
if chunk.FinishReason != "" {
|
||||
result.FinishReason = chunk.FinishReason
|
||||
}
|
||||
if sig, ok := chunk.Data["reasoning_signature"].(string); ok && sig != "" {
|
||||
result.ReasoningSignature = sig
|
||||
}
|
||||
if md, ok := chunk.Data["reasoning_metadata"].(types.ProviderMetadata); ok && len(md) > 0 {
|
||||
result.ReasoningMetadata = md
|
||||
}
|
||||
|
||||
if emitFunc != nil {
|
||||
emitFunc(&chunk, result.Content)
|
||||
|
|
@ -257,6 +267,7 @@ func (e *AgentEngine) streamThinkingToEventBus(
|
|||
MaxCompletionTokens: budget,
|
||||
Tools: tools,
|
||||
Thinking: e.config.Thinking,
|
||||
ReasoningEffort: chat.SanitizeReasoningEffort(ctx, e.config.ReasoningEffort, "agent config"),
|
||||
ParallelToolCalls: ¶llelToolCalls,
|
||||
PromptCacheKey: sessionID,
|
||||
}
|
||||
|
|
@ -456,11 +467,13 @@ func (e *AgentEngine) streamThinkingToEventBus(
|
|||
}
|
||||
|
||||
resp := &types.ChatResponse{
|
||||
Content: fullContent,
|
||||
ReasoningContent: llmResult.ReasoningContent,
|
||||
ToolCalls: llmResult.ToolCalls,
|
||||
FinishReason: finishReason,
|
||||
AnswerStreamed: answerStreamed,
|
||||
Content: fullContent,
|
||||
ReasoningContent: llmResult.ReasoningContent,
|
||||
ReasoningSignature: llmResult.ReasoningSignature,
|
||||
ReasoningMetadata: llmResult.ReasoningMetadata,
|
||||
ToolCalls: llmResult.ToolCalls,
|
||||
FinishReason: finishReason,
|
||||
AnswerStreamed: answerStreamed,
|
||||
}
|
||||
if answerStreamed {
|
||||
resp.AnswerEventID = answerID
|
||||
|
|
|
|||
|
|
@ -20,8 +20,10 @@
|
|||
package token
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
|
|
@ -137,6 +139,13 @@ func (e *Estimator) EstimateString(s string) int {
|
|||
// 26k — compaction then cut in the wrong place, freed almost nothing, and ran
|
||||
// again the next round. Reasoning content is counted alongside text and tool
|
||||
// calls for that reason.
|
||||
//
|
||||
// The reasoning artifacts that travel with it are counted too. They are opaque
|
||||
// to us but not to the provider's billing: an Anthropic thinking signature is a
|
||||
// few hundred base64 characters, and an OpenAI Responses encrypted reasoning
|
||||
// item (or an OpenRouter reasoning_details blob) is several kilobytes replayed
|
||||
// on every assistant turn. Leaving them out reproduces exactly the
|
||||
// under-measurement described above, one replayed turn at a time.
|
||||
func (e *Estimator) EstimateMessage(msg *chat.Message) int {
|
||||
tokens := perMessageOverhead
|
||||
tokens += e.EstimateString(msg.Role)
|
||||
|
|
@ -144,17 +153,52 @@ func (e *Estimator) EstimateMessage(msg *chat.Message) int {
|
|||
tokens += e.EstimateString(msg.Name)
|
||||
tokens += e.EstimateString(msg.ToolCallID)
|
||||
tokens += e.EstimateString(msg.ReasoningContent)
|
||||
tokens += e.EstimateReasoningArtifacts(msg)
|
||||
tokens += e.estimateImageParts(msg)
|
||||
|
||||
for _, tc := range msg.ToolCalls {
|
||||
tokens += e.EstimateString(tc.Function.Name)
|
||||
tokens += e.EstimateString(tc.Function.Arguments)
|
||||
tokens += e.estimateProviderMetadata(tc.ProviderMetadata)
|
||||
tokens += perToolCallOverhead
|
||||
}
|
||||
|
||||
return tokens
|
||||
}
|
||||
|
||||
// EstimateReasoningArtifacts counts the opaque provider state replayed with an
|
||||
// assistant turn. The signature carries a protocol tag that is stripped before
|
||||
// it goes out, so only the payload after the tag is billed; the metadata is
|
||||
// sent as-is, one JSON value per namespace key.
|
||||
func (e *Estimator) EstimateReasoningArtifacts(msg *chat.Message) int {
|
||||
tokens := 0
|
||||
if sig := msg.ReasoningSignature; sig != "" {
|
||||
if _, payload, found := strings.Cut(sig, ":"); found {
|
||||
sig = payload
|
||||
}
|
||||
tokens += e.EstimateString(sig)
|
||||
}
|
||||
tokens += e.estimateProviderMetadata(msg.ReasoningMetadata)
|
||||
return tokens
|
||||
}
|
||||
|
||||
// estimateProviderMetadata counts one opaque provider-state map, one JSON
|
||||
// value per namespace key, the way it goes out on the wire.
|
||||
//
|
||||
// The same accounting applies per tool call as it does per turn: a Gemini
|
||||
// thought signature and an OpenAI Responses item id ride on the tool call, not
|
||||
// on the message, and are replayed on every subsequent turn. A signature runs
|
||||
// to kilobytes, so a round of parallel calls left uncounted under-measures the
|
||||
// context exactly the way the missing reasoning content did.
|
||||
func (e *Estimator) estimateProviderMetadata(md map[string]json.RawMessage) int {
|
||||
tokens := 0
|
||||
for key, raw := range md {
|
||||
tokens += e.EstimateString(key)
|
||||
tokens += e.EstimateString(string(raw))
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
|
||||
// estimateImageParts counts multimodal content. MultiContent is the assembled
|
||||
// representation actually sent to the provider, so when it is present the raw
|
||||
// Images list is the same pictures counted a second time.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,127 @@
|
|||
package token
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// TestEstimateMessageCountsReasoningArtifacts pins the fix for the compaction
|
||||
// trigger under-measuring replayed assistant turns. An OpenAI Responses
|
||||
// encrypted reasoning item or an Anthropic signature rides on every replayed
|
||||
// assistant message; leaving it out of the estimate is the same class of bug
|
||||
// the package comment describes for reasoning_content.
|
||||
func TestEstimateMessageCountsReasoningArtifacts(t *testing.T) {
|
||||
est, err := NewEstimator()
|
||||
if err != nil {
|
||||
t.Fatalf("NewEstimator: %v", err)
|
||||
}
|
||||
|
||||
plain := chat.Message{Role: "assistant", Content: "ok"}
|
||||
blob, err := json.Marshal([]string{strings.Repeat("QUJDRA", 800)})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
withArtifacts := plain
|
||||
withArtifacts.ReasoningSignature = "anthropic-messages:" + strings.Repeat("c2ln", 200)
|
||||
withArtifacts.ReasoningMetadata = types.ProviderMetadata{"openai_responses_reasoning": blob}
|
||||
|
||||
base := est.EstimateMessage(&plain)
|
||||
full := est.EstimateMessage(&withArtifacts)
|
||||
if full <= base {
|
||||
t.Fatalf("reasoning artifacts not counted: base=%d full=%d", base, full)
|
||||
}
|
||||
// The blobs are kilobytes, so the delta must be substantial rather than
|
||||
// the handful of tokens a key name alone would add.
|
||||
if delta := full - base; delta < 500 {
|
||||
t.Errorf("artifact cost looks under-counted: delta=%d", delta)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEstimateReasoningArtifactsSkipsProtocolTag checks the stored signature's
|
||||
// "<protocol>:" prefix is not billed: api.SignatureFor strips it before the
|
||||
// signature goes out on the wire.
|
||||
func TestEstimateReasoningArtifactsSkipsProtocolTag(t *testing.T) {
|
||||
est, err := NewEstimator()
|
||||
if err != nil {
|
||||
t.Fatalf("NewEstimator: %v", err)
|
||||
}
|
||||
payload := strings.Repeat("c2ln", 50)
|
||||
tagged := &chat.Message{Role: "assistant", ReasoningSignature: "anthropic-messages:" + payload}
|
||||
untagged := &chat.Message{Role: "assistant", ReasoningSignature: payload}
|
||||
if got, want := est.EstimateReasoningArtifacts(tagged), est.EstimateReasoningArtifacts(untagged); got != want {
|
||||
t.Errorf("protocol tag billed: tagged=%d untagged=%d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEstimateReasoningArtifactsEmpty keeps the common case free of cost.
|
||||
func TestEstimateReasoningArtifactsEmpty(t *testing.T) {
|
||||
est, err := NewEstimator()
|
||||
if err != nil {
|
||||
t.Fatalf("NewEstimator: %v", err)
|
||||
}
|
||||
if got := est.EstimateReasoningArtifacts(&chat.Message{Role: "user", Content: "hi"}); got != 0 {
|
||||
t.Errorf("expected 0 for a message without artifacts, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Gemini thought signatures and OpenAI Responses item ids ride on the tool
|
||||
// call, not on the message, and are replayed on every later turn. Counting
|
||||
// only name+arguments under-measured a parallel tool round by kilobytes —
|
||||
// the same failure mode as the message-level artifacts above.
|
||||
func TestEstimateMessageCountsToolCallProviderMetadata(t *testing.T) {
|
||||
est, err := NewEstimator()
|
||||
if err != nil {
|
||||
t.Fatalf("NewEstimator: %v", err)
|
||||
}
|
||||
|
||||
signature, err := json.Marshal(strings.Repeat("CtoBCr8B", 400))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
call := chat.ToolCall{
|
||||
ID: "call_1", Type: "function",
|
||||
Function: chat.FunctionCall{Name: "search", Arguments: `{"q":"x"}`},
|
||||
}
|
||||
plain := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{call}}
|
||||
|
||||
withMetadata := call
|
||||
withMetadata.ProviderMetadata = types.ToolCallMetadata{"thought_signature": signature}
|
||||
annotated := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{withMetadata}}
|
||||
|
||||
base := est.EstimateMessage(&plain)
|
||||
full := est.EstimateMessage(&annotated)
|
||||
if full <= base {
|
||||
t.Fatalf("tool-call provider metadata not counted: base=%d full=%d", base, full)
|
||||
}
|
||||
// It must be accounted like the message-level artifacts: the payload, not
|
||||
// just the namespace key.
|
||||
if delta := full - base; delta < 500 {
|
||||
t.Errorf("tool-call metadata looks under-counted: delta=%d", delta)
|
||||
}
|
||||
}
|
||||
|
||||
// Every call in a parallel round carries its own signature, so the cost has
|
||||
// to scale with the number of calls.
|
||||
func TestEstimateMessageCountsMetadataPerToolCall(t *testing.T) {
|
||||
est, err := NewEstimator()
|
||||
if err != nil {
|
||||
t.Fatalf("NewEstimator: %v", err)
|
||||
}
|
||||
md := types.ToolCallMetadata{"thought_signature": json.RawMessage(`"` + strings.Repeat("CtoB", 200) + `"`)}
|
||||
call := chat.ToolCall{
|
||||
ID: "c", Type: "function",
|
||||
Function: chat.FunctionCall{Name: "f", Arguments: "{}"}, ProviderMetadata: md,
|
||||
}
|
||||
one := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{call}}
|
||||
two := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{call, call}}
|
||||
|
||||
single := est.EstimateMessage(&one) - est.EstimateMessage(&chat.Message{Role: "assistant"})
|
||||
double := est.EstimateMessage(&two) - est.EstimateMessage(&chat.Message{Role: "assistant"})
|
||||
if double < single*2-perToolCallOverhead {
|
||||
t.Errorf("metadata counted once for a parallel round: single=%d double=%d", single, double)
|
||||
}
|
||||
}
|
||||
|
|
@ -2,10 +2,12 @@ package agent
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/api/openaicompletions"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
|
@ -28,9 +30,17 @@ func TestToolImagesReachNextModelTurnAfterAllReplies(t *testing.T) {
|
|||
require.Equal(t, "user", messages[3].Role)
|
||||
require.Equal(t, step.ToolCalls[0].Result.Images, messages[3].Images)
|
||||
require.Contains(t, messages[3].Content, "untrusted tool evidence")
|
||||
wire := (&chat.RemoteAPIChat{}).ConvertMessages(messages)
|
||||
require.Len(t, wire[3].MultiContent, 2)
|
||||
require.Equal(t, step.ToolCalls[0].Result.Images[0], wire[3].MultiContent[0].ImageURL.URL)
|
||||
client := openaicompletions.New(openaicompletions.Config{Settings: catalog.DefaultOpenAICompletions()})
|
||||
body, err := client.BuildRequestBody(messages, nil, false)
|
||||
require.NoError(t, err)
|
||||
raw, err := json.Marshal(body["messages"])
|
||||
require.NoError(t, err)
|
||||
var wire []map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &wire))
|
||||
parts := wire[3]["content"].([]any)
|
||||
require.Len(t, parts, 2)
|
||||
imagePart := parts[0].(map[string]any)["image_url"].(map[string]any)
|
||||
require.Equal(t, step.ToolCalls[0].Result.Images[0], imagePart["url"])
|
||||
} else {
|
||||
require.Len(t, messages, 3)
|
||||
require.Contains(t, messages[1].Content, "cannot view")
|
||||
|
|
|
|||
|
|
@ -507,15 +507,20 @@ func buildAgentStepMessages(step types.AgentStep) []chat.Message {
|
|||
nonTerminalCalls := filterNonTerminalToolCalls(step.ToolCalls)
|
||||
if len(nonTerminalCalls) == 0 {
|
||||
if step.IntermediateAnswer && strings.TrimSpace(step.Thought) != "" {
|
||||
return []chat.Message{{Role: "assistant", Content: step.Thought, ReasoningContent: step.ReasoningContent}}
|
||||
return []chat.Message{{
|
||||
Role: "assistant", Content: step.Thought, ReasoningContent: step.ReasoningContent,
|
||||
ReasoningSignature: step.ReasoningSignature, ReasoningMetadata: step.ReasoningMetadata,
|
||||
}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
assistantMsg := chat.Message{
|
||||
Role: "assistant",
|
||||
Content: step.Thought,
|
||||
ReasoningContent: step.ReasoningContent,
|
||||
ToolCalls: make([]chat.ToolCall, 0, len(nonTerminalCalls)),
|
||||
Role: "assistant",
|
||||
Content: step.Thought,
|
||||
ReasoningContent: step.ReasoningContent,
|
||||
ReasoningSignature: step.ReasoningSignature,
|
||||
ReasoningMetadata: step.ReasoningMetadata,
|
||||
ToolCalls: make([]chat.ToolCall, 0, len(nonTerminalCalls)),
|
||||
}
|
||||
for _, tc := range nonTerminalCalls {
|
||||
argsJSON, _ := json.Marshal(tc.Args)
|
||||
|
|
@ -546,7 +551,8 @@ func buildAgentStepMessages(step types.AgentStep) []chat.Message {
|
|||
// finalAnswerHistoryMessage is the canonical answer of a turn, or nil when the
|
||||
// turn produced no text (stopped, or answered purely through tools). The
|
||||
// generated-file markers belong to that turn, so they are relabeled before
|
||||
// being replayed into a later turn's history.
|
||||
// being replayed into a later turn's history. It also carries the closing
|
||||
// round's reasoning artifacts — see finalAnswerReasoningStep.
|
||||
func finalAnswerHistoryMessage(m *types.Message) *chat.Message {
|
||||
finalContent := agentHistoryThinkTagRegex.ReplaceAllString(m.Content, "")
|
||||
// Version clarification was written for that message's turn, not this one.
|
||||
|
|
@ -558,7 +564,46 @@ func finalAnswerHistoryMessage(m *types.Message) *chat.Message {
|
|||
if finalContent == "" {
|
||||
return nil
|
||||
}
|
||||
return &chat.Message{Role: "assistant", Content: finalContent}
|
||||
final := &chat.Message{Role: "assistant", Content: finalContent}
|
||||
// The artifacts ride in their own fields, so stripping <think> blocks out
|
||||
// of the visible answer above and replaying the round's reasoning here are
|
||||
// not in conflict: nothing thinking-shaped is added back to Content.
|
||||
if step := finalAnswerReasoningStep(m.AgentSteps); step != nil {
|
||||
final.ReasoningContent = step.ReasoningContent
|
||||
final.ReasoningSignature = step.ReasoningSignature
|
||||
final.ReasoningMetadata = step.ReasoningMetadata
|
||||
}
|
||||
return final
|
||||
}
|
||||
|
||||
// finalAnswerReasoningStep returns the step whose reasoning artifacts belong on
|
||||
// the turn's final assistant message, or nil when none do.
|
||||
//
|
||||
// A turn normally ends with a plain answer and no tool calls. The engine
|
||||
// records that closing round like any other, artifacts included, but
|
||||
// buildAgentStepMessages emits nothing for a step without tool calls — so
|
||||
// everything the next turn has to hand back (the OpenAI Responses encrypted
|
||||
// reasoning items, a DeepSeek/MiMo reasoning_content, an Anthropic thinking
|
||||
// signature) stopped at the turn boundary, exactly as the tool rounds' did
|
||||
// before they were replayed.
|
||||
//
|
||||
// Only the last step is eligible: an earlier round's artifacts belong to the
|
||||
// assistant message that round already produced, with its tool results in
|
||||
// between. Whether that message exists is asked of buildAgentStepMessages
|
||||
// itself rather than restated here, so a shape it learns to replay later is one
|
||||
// this function stops duplicating without being touched.
|
||||
func finalAnswerReasoningStep(steps types.AgentSteps) *types.AgentStep {
|
||||
if len(steps) == 0 {
|
||||
return nil
|
||||
}
|
||||
last := &steps[len(steps)-1]
|
||||
if last.ReasoningContent == "" && last.ReasoningSignature == "" && len(last.ReasoningMetadata) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(buildAgentStepMessages(*last)) > 0 {
|
||||
return nil
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
// legacyFinalAnswerToolName is the name of the now-removed final_answer tool.
|
||||
|
|
|
|||
|
|
@ -450,6 +450,78 @@ func TestBuildAssistantHistoryMessages_ReplaysReasoningContent(t *testing.T) {
|
|||
assert.Empty(t, got[2].ReasoningContent)
|
||||
}
|
||||
|
||||
// TestBuildAssistantHistoryMessages_ReplaysFinalAnswerReasoning covers the
|
||||
// common shape the tool-round replay missed: a turn that ends with a plain
|
||||
// answer and no tool calls.
|
||||
//
|
||||
// The engine records that closing round as an ordinary step, artifacts and
|
||||
// all, but buildAgentStepMessages emits nothing for a step without tool calls,
|
||||
// so everything the provider needs back — the OpenAI Responses encrypted
|
||||
// reasoning items, a DeepSeek/MiMo reasoning_content, an Anthropic thinking
|
||||
// signature — used to end at the turn boundary.
|
||||
func TestBuildAssistantHistoryMessages_ReplaysFinalAnswerReasoning(t *testing.T) {
|
||||
items := json.RawMessage(`[{"type":"reasoning","id":"rs_1","encrypted_content":"opaque"}]`)
|
||||
msg := &types.Message{
|
||||
Role: "assistant",
|
||||
Content: "<think>leaked</think>The answer is 42.",
|
||||
AgentSteps: types.AgentSteps{
|
||||
{
|
||||
Iteration: 0,
|
||||
Thought: "The answer is 42.",
|
||||
ReasoningContent: "checking the arithmetic",
|
||||
ReasoningSignature: "sig-1",
|
||||
ReasoningMetadata: types.ProviderMetadata{"openai_responses_reasoning": items},
|
||||
},
|
||||
},
|
||||
}
|
||||
got := buildAssistantHistoryMessages(msg)
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "assistant", got[0].Role)
|
||||
// The think tags stay out of the visible answer; the artifacts ride in
|
||||
// their own fields, which is where the providers read them.
|
||||
assert.Equal(t, "The answer is 42.", got[0].Content)
|
||||
assert.Equal(t, "checking the arithmetic", got[0].ReasoningContent)
|
||||
assert.Equal(t, "sig-1", got[0].ReasoningSignature)
|
||||
assert.JSONEq(t, string(items), string(got[0].ReasoningMetadata["openai_responses_reasoning"]))
|
||||
}
|
||||
|
||||
// TestBuildAssistantHistoryMessages_FinalAnswerDoesNotDuplicateReasoning pins
|
||||
// the other half: artifacts buildAgentStepMessages already replayed must not be
|
||||
// repeated on the final message. A round that issued tool calls, and a round
|
||||
// whose text was already emitted as an intermediate answer, both carry their
|
||||
// own assistant message.
|
||||
func TestBuildAssistantHistoryMessages_FinalAnswerDoesNotDuplicateReasoning(t *testing.T) {
|
||||
toolRound := types.AgentStep{
|
||||
Thought: "Let me search.",
|
||||
ReasoningContent: "tool round thinking",
|
||||
ToolCalls: []types.ToolCall{{
|
||||
ID: "call_1",
|
||||
Name: agenttools.ToolSearchKnowledge,
|
||||
Args: map[string]interface{}{"query": "foo"},
|
||||
Result: &types.ToolResult{Success: true, Output: "doc A"},
|
||||
}},
|
||||
}
|
||||
withTools := buildAssistantHistoryMessages(&types.Message{
|
||||
Role: "assistant", Content: "Found it.", AgentSteps: types.AgentSteps{toolRound},
|
||||
})
|
||||
require.Len(t, withTools, 3)
|
||||
assert.Equal(t, "tool round thinking", withTools[0].ReasoningContent)
|
||||
assert.Empty(t, withTools[2].ReasoningContent, "the tool round already replayed its own artifacts")
|
||||
|
||||
steered := buildAssistantHistoryMessages(&types.Message{
|
||||
Role: "assistant", Content: "Shorter answer.",
|
||||
AgentSteps: types.AgentSteps{{
|
||||
Thought: "Long answer.",
|
||||
IntermediateAnswer: true,
|
||||
ReasoningContent: "intermediate round thinking",
|
||||
}},
|
||||
})
|
||||
require.Len(t, steered, 2)
|
||||
assert.Equal(t, "intermediate round thinking", steered[0].ReasoningContent)
|
||||
assert.Empty(t, steered[1].ReasoningContent,
|
||||
"the intermediate answer already carries this step's artifacts")
|
||||
}
|
||||
|
||||
func TestMCPProxyHistoryRetainsProtocolCallAndTarget(t *testing.T) {
|
||||
msg := &types.Message{Role: "assistant", AgentSteps: types.AgentSteps{{ToolCalls: []types.ToolCall{{
|
||||
ID: "proxy-id", Name: "call_mcp_tool",
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
|
|||
return nil, nil, err
|
||||
}
|
||||
|
||||
effort := chat.SanitizeReasoningEffort(ctx, chatManage.SummaryConfig.ReasoningEffort, "session summary config")
|
||||
opt := &chat.ChatOptions{
|
||||
Temperature: chatManage.SummaryConfig.Temperature,
|
||||
TopP: chatManage.SummaryConfig.TopP,
|
||||
|
|
@ -52,11 +53,13 @@ func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
|
|||
FrequencyPenalty: chatManage.SummaryConfig.FrequencyPenalty,
|
||||
PresencePenalty: chatManage.SummaryConfig.PresencePenalty,
|
||||
Thinking: chatManage.SummaryConfig.Thinking,
|
||||
ReasoningEffort: effort,
|
||||
PromptCacheKey: chatManage.SessionID,
|
||||
}
|
||||
if opt.Thinking != nil {
|
||||
if level, requested := opt.Reasoning(); requested {
|
||||
pipelineInfo(ctx, "Stream", "thinking_option", map[string]interface{}{
|
||||
"enabled": *opt.Thinking,
|
||||
"enabled": level.Enabled(),
|
||||
"level": string(level),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -326,6 +326,7 @@ func (s *sessionService) buildAgentConfig(
|
|||
MCPServices: customAgent.Config.MCPServices,
|
||||
MCPAuthWaitTimeout: customAgent.Config.MCPAuthWaitTimeout,
|
||||
Thinking: customAgent.Config.Thinking,
|
||||
ReasoningEffort: customAgent.Config.ReasoningEffort,
|
||||
CitationEnabled: customAgent.Config.CitationEnabled,
|
||||
RetrieveKBOnlyWhenMentioned: customAgent.Config.RetrieveKBOnlyWhenMentioned,
|
||||
LLMCallTimeout: customAgent.Config.LLMCallTimeout,
|
||||
|
|
|
|||
|
|
@ -235,6 +235,7 @@ func (s *sessionService) applyAgentOverridesToChatManage(
|
|||
// EnsureDefaults pins nil to explicit false so thinking_control wire formats
|
||||
// always receive a value.
|
||||
cm.SummaryConfig.Thinking = customAgent.Config.Thinking
|
||||
cm.SummaryConfig.ReasoningEffort = customAgent.Config.ReasoningEffort
|
||||
cm.CitationEnabled = customAgent.Config.CitationEnabled
|
||||
if customAgent.Config.Thinking != nil {
|
||||
logger.Infof(ctx, "Using custom agent's thinking: %v", *customAgent.Config.Thinking)
|
||||
|
|
|
|||
|
|
@ -84,10 +84,12 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/mcpserver"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/models/limiter"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
_ "github.com/Tencent/WeKnora/internal/models/vendors" // register built-in vendors
|
||||
"github.com/Tencent/WeKnora/internal/router"
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
"github.com/Tencent/WeKnora/internal/storageallowlist"
|
||||
|
|
@ -111,6 +113,12 @@ import (
|
|||
// Returns:
|
||||
// - Configured container with all application dependencies registered
|
||||
func BuildContainer(container *dig.Container) *dig.Container {
|
||||
// Deployment-level model catalog overlay (config/models.json, optional).
|
||||
// Built-in vendors register themselves through the vendors package
|
||||
// import; the overlay may add vendors or patch built-in ones.
|
||||
if err := catalog.LoadOverlay(config.ConfigDir()); err != nil {
|
||||
logger.Warnf(context.Background(), "Load models catalog overlay failed: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
logger.Debugf(ctx, "[Container] Starting container initialization...")
|
||||
|
||||
|
|
@ -595,7 +603,7 @@ func registerChatLocalImageResolver(
|
|||
storageResolver interfaces.StorageBackendResolver,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
) {
|
||||
chat.LocalImageResolver = func(storageURL string) ([]byte, bool) {
|
||||
api.LocalImageResolver = func(storageURL string) ([]byte, bool) {
|
||||
// The object storage clients bound connection setup but leave the
|
||||
// transfer to this context, so give it a deadline: a chat turn must
|
||||
// not hang on one image whose download stalls.
|
||||
|
|
@ -879,6 +887,9 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
|||
migrateLegacyStorageBackends(db)
|
||||
|
||||
// Post-migration: declarative built-in models from config/builtin_models.yaml (optional).
|
||||
// The loader validates each row's catalog parameters through this hook;
|
||||
// the wiring lives here because internal/types cannot import the catalog.
|
||||
types.ValidateModelParameters = catalog.ValidateRow
|
||||
if err := types.LoadBuiltinModelsConfig(context.Background(), db, config.ConfigDir()); err != nil {
|
||||
logger.Warnf(context.Background(), "Load builtin models config failed: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package handler
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
|
@ -11,6 +12,7 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
|
|
@ -106,6 +108,10 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
|
|||
c.Error(err)
|
||||
return
|
||||
}
|
||||
if err := normalizeAgentReasoningEffort(&req.Config); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
|
|
@ -372,6 +378,10 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
|
|||
c.Error(err)
|
||||
return
|
||||
}
|
||||
if err := normalizeAgentReasoningEffort(&req.Config); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Only a sent avatar is validated: nil means the caller never touched the
|
||||
// field, so there is no value to bound. Checking the length here is what
|
||||
|
|
@ -751,6 +761,30 @@ func (h *CustomAgentHandler) validateAgentSandboxConfig(
|
|||
return nil
|
||||
}
|
||||
|
||||
// normalizeAgentReasoningEffort validates config.reasoning_effort and rewrites
|
||||
// it to its canonical spelling.
|
||||
//
|
||||
// Without this the field was stored verbatim and cast straight to
|
||||
// api.ReasoningEffort in agent/think.go and chat_pipeline/common.go. A typo
|
||||
// there does not disable thinking, it silently enables it: ReasoningEffort
|
||||
// wins over the legacy boolean and anything non-empty other than "off" counts
|
||||
// as enabled, so `"reasoning_effort": "hgih"` turns thinking on for a vendor
|
||||
// that then receives a level it rejects (or clamps in an unpredictable way).
|
||||
func normalizeAgentReasoningEffort(cfg *types.CustomAgentConfig) error {
|
||||
if cfg == nil || cfg.ReasoningEffort == "" {
|
||||
return nil
|
||||
}
|
||||
level, ok := api.ParseReasoningEffort(cfg.ReasoningEffort)
|
||||
if !ok {
|
||||
return errors.NewBadRequestError(
|
||||
fmt.Sprintf("reasoning_effort must be one of %v", api.AllReasoningEfforts))
|
||||
}
|
||||
// Store the canonical value so EnsureDefaults and the editor never have to
|
||||
// know about the accepted aliases ("none", "true", ...).
|
||||
cfg.ReasoningEffort = string(level)
|
||||
return nil
|
||||
}
|
||||
|
||||
func authorizeAgentKnowledgeScope(ctx context.Context, cfg types.CustomAgentConfig) error {
|
||||
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// TestNormalizeAgentReasoningEffortRejectsUnknownLevel pins the create/update
|
||||
// guard. An unvalidated level does not degrade to "off": ReasoningEffort wins
|
||||
// over the legacy boolean and every non-empty value other than "off" counts as
|
||||
// thinking-on, so a typo used to enable thinking and hand the vendor a level
|
||||
// it never documented.
|
||||
func TestNormalizeAgentReasoningEffortRejectsUnknownLevel(t *testing.T) {
|
||||
cfg := types.CustomAgentConfig{ReasoningEffort: "hgih"}
|
||||
if err := normalizeAgentReasoningEffort(&cfg); err == nil {
|
||||
t.Fatal("expected an error for an unknown reasoning_effort")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeAgentReasoningEffortCanonicalizes checks the accepted aliases
|
||||
// are rewritten, so EnsureDefaults and the editor only ever see canonical
|
||||
// values.
|
||||
func TestNormalizeAgentReasoningEffortCanonicalizes(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"": "",
|
||||
"high": "high",
|
||||
"off": "off",
|
||||
"none": "off",
|
||||
"false": "off",
|
||||
"true": "auto",
|
||||
"on": "auto",
|
||||
}
|
||||
for in, want := range cases {
|
||||
cfg := types.CustomAgentConfig{ReasoningEffort: in}
|
||||
if err := normalizeAgentReasoningEffort(&cfg); err != nil {
|
||||
t.Errorf("normalize(%q): unexpected error %v", in, err)
|
||||
continue
|
||||
}
|
||||
if cfg.ReasoningEffort != want {
|
||||
t.Errorf("normalize(%q) = %q, want %q", in, cfg.ReasoningEffort, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeAgentReasoningEffortNilConfig keeps the helper safe for the
|
||||
// zero-value paths.
|
||||
func TestNormalizeAgentReasoningEffortNilConfig(t *testing.T) {
|
||||
if err := normalizeAgentReasoningEffort(nil); err != nil {
|
||||
t.Fatalf("nil config should be a no-op, got %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -2,11 +2,172 @@ package dto
|
|||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// VendorRef identifies the vendor a set of model parameters belongs to.
|
||||
// BaseURL covers legacy rows saved before provider was stored; the vendor is
|
||||
// then detected from the endpoint.
|
||||
type VendorRef struct {
|
||||
Provider string
|
||||
BaseURL string
|
||||
}
|
||||
|
||||
// vendorID resolves the ref to a comparable vendor id. An id that matches no
|
||||
// registered vendor is returned as typed, so two rows pinned to the same
|
||||
// hand-written provider still compare equal.
|
||||
func (r VendorRef) vendorID() string {
|
||||
id := strings.ToLower(strings.TrimSpace(r.Provider))
|
||||
if id == "" {
|
||||
id = catalog.DetectByURL(r.BaseURL)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// names reports whether the ref identifies a vendor at all. A PUT body that
|
||||
// carries neither provider nor base URL names none, and must not be read as
|
||||
// "the user moved this row to another vendor".
|
||||
func (r VendorRef) names() bool {
|
||||
return strings.TrimSpace(r.Provider) != "" || strings.TrimSpace(r.BaseURL) != ""
|
||||
}
|
||||
|
||||
func secretKeysOf(v *catalog.Vendor, into map[string]bool) map[string]bool {
|
||||
for _, f := range v.ExtraFields {
|
||||
if !f.Secret && f.Type != "password" {
|
||||
continue
|
||||
}
|
||||
if into == nil {
|
||||
into = map[string]bool{}
|
||||
}
|
||||
into[f.Key] = true
|
||||
}
|
||||
return into
|
||||
}
|
||||
|
||||
// SecretExtraConfigKeys returns the extra_config keys the vendor declares as
|
||||
// secret (catalog.ExtraField.Secret, or a password input). These are real
|
||||
// credentials — LKEAP and Volcengine rerank keep an IAM/CAM secret key there
|
||||
// — so they get the same treatment as api_key / app_secret: never echoed,
|
||||
// only reported as present.
|
||||
//
|
||||
// The field's ModelTypes restriction is deliberately ignored: a key that is
|
||||
// secret for any model type of the vendor is redacted for every row of that
|
||||
// vendor.
|
||||
func SecretExtraConfigKeys(provider, baseURL string) map[string]bool {
|
||||
v, ok := catalog.Get(VendorRef{Provider: provider, BaseURL: baseURL}.vendorID())
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return secretKeysOf(v, nil)
|
||||
}
|
||||
|
||||
// AllSecretExtraConfigKeys returns every extra_config key any registered
|
||||
// vendor declares secret.
|
||||
//
|
||||
// Redaction must not depend on the row's own provider being the one that
|
||||
// declared the key: a row whose provider was switched, hand-edited or never
|
||||
// stored would otherwise echo a credential in plaintext simply because its
|
||||
// current vendor declares no secret field. Treating a name that is secret
|
||||
// somewhere as secret everywhere is the safe direction — the worst case is
|
||||
// withholding a value that happened to reuse the name.
|
||||
func AllSecretExtraConfigKeys() map[string]bool {
|
||||
var keys map[string]bool
|
||||
for _, v := range catalog.List() {
|
||||
keys = secretKeysOf(v, keys)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// redactedSecretPlaceholder reports whether an incoming extra_config value
|
||||
// carries no new secret: empty, or a mask the UI shows for a value it never
|
||||
// received (GET omits the key entirely, but forms happily render bullets).
|
||||
func redactedSecretPlaceholder(v string) bool {
|
||||
t := strings.TrimSpace(v)
|
||||
return t == "" || strings.Trim(t, "*•·●") == ""
|
||||
}
|
||||
|
||||
// PreserveStoredSecretExtras merges the stored secret extra_config values
|
||||
// into an incoming map.
|
||||
//
|
||||
// PUT /models/{id} replaces extra_config wholesale and the frontend always
|
||||
// sends the map for remote rows, but GET redacts the vendor's secret fields,
|
||||
// so a plain edit-and-save round-trip carries no value for them. Without this
|
||||
// merge the first save after any unrelated edit would erase the stored secret
|
||||
// key and break rerank for that row. An incoming value that is absent, empty
|
||||
// or a mask means "unchanged"; anything else replaces the stored secret.
|
||||
//
|
||||
// storedVendor identifies the vendor the stored values belong to; edited is
|
||||
// the vendor the incoming values are for. They differ when the user moves the
|
||||
// row to another vendor, and then the stored credential must be dropped
|
||||
// rather than carried over: it belongs to the previous integration's account,
|
||||
// the editor no longer renders a field for it, and the new vendor may not
|
||||
// declare it secret at all — which is how it ended up echoed in plaintext.
|
||||
//
|
||||
// incoming is filled in place and returned.
|
||||
func PreserveStoredSecretExtras(
|
||||
stored, incoming map[string]string, storedVendor, edited VendorRef,
|
||||
) map[string]string {
|
||||
keys := SecretExtraConfigKeys(storedVendor.Provider, storedVendor.BaseURL)
|
||||
// A request that names no vendor at all changed none: keep the old
|
||||
// contract, which rerank rows rely on for their redacted secret.
|
||||
switched := edited.names() && edited.vendorID() != storedVendor.vendorID()
|
||||
if incoming == nil {
|
||||
if !switched || len(keys) == 0 || len(stored) == 0 {
|
||||
return stored
|
||||
}
|
||||
// extra_config omitted entirely still keeps the rest of the stored
|
||||
// map, but not the previous vendor's credential.
|
||||
out := make(map[string]string, len(stored))
|
||||
for k, v := range stored {
|
||||
if !keys[k] {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return incoming
|
||||
}
|
||||
if switched {
|
||||
// Only a value the user actually typed survives a vendor switch; an
|
||||
// absent or masked one would otherwise resurrect the old secret when
|
||||
// the new vendor happens to reuse the key name.
|
||||
for key := range keys {
|
||||
if redactedSecretPlaceholder(incoming[key]) {
|
||||
delete(incoming, key)
|
||||
}
|
||||
}
|
||||
return incoming
|
||||
}
|
||||
for key := range keys {
|
||||
storedValue := stored[key]
|
||||
if storedValue == "" {
|
||||
continue
|
||||
}
|
||||
if redactedSecretPlaceholder(incoming[key]) {
|
||||
incoming[key] = storedValue
|
||||
}
|
||||
}
|
||||
return incoming
|
||||
}
|
||||
|
||||
// HasAllSecretExtras reports whether extra already carries a usable value for
|
||||
// every secret extra field the vendor declares. Callers that would otherwise
|
||||
// skip a lookup of the stored row use it to notice that the request is
|
||||
// missing a redacted secret.
|
||||
func HasAllSecretExtras(provider, baseURL string, extra map[string]string) bool {
|
||||
for key := range SecretExtraConfigKeys(provider, baseURL) {
|
||||
if redactedSecretPlaceholder(extra[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ModelResponse mirrors types.Model for response bodies, with all secret
|
||||
// fields (APIKey, AppSecret) removed by construction. Credential presence
|
||||
// metadata lives behind the /credentials subresource, not inlined here.
|
||||
|
|
@ -32,6 +193,9 @@ type ModelResponse struct {
|
|||
// Per-field "configured?" map. Omitted for builtin models unless the
|
||||
// caller is a system administrator. See MCPServiceResponse.Credentials.
|
||||
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
|
||||
// Capabilities is the catalog view of the model: protocol, whether it
|
||||
// can think and at which levels, context window. Chat models only.
|
||||
Capabilities *catalog.Capabilities `json:"capabilities,omitempty"`
|
||||
}
|
||||
|
||||
// ModelParametersDTO carries every parameter field EXCEPT the two secret
|
||||
|
|
@ -51,6 +215,7 @@ type ModelParametersDTO struct {
|
|||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
MaxConcurrency int `json:"max_concurrency,omitempty"`
|
||||
AppID string `json:"app_id,omitempty"`
|
||||
Spec *types.ModelSpecOverride `json:"spec,omitempty"`
|
||||
}
|
||||
|
||||
// NewModelResponse converts a stored Model into its response shape.
|
||||
|
|
@ -74,12 +239,18 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
|
|||
MaxOutputTokens: m.Parameters.MaxOutputTokens,
|
||||
MaxConcurrency: m.Parameters.MaxConcurrency,
|
||||
AppID: m.Parameters.AppID,
|
||||
Spec: m.Parameters.Spec,
|
||||
}
|
||||
canManageBuiltin := m.IsBuiltin && types.IsSystemAdminFromContext(ctx)
|
||||
if !CanViewIntegrationSecrets(ctx) && !canManageBuiltin {
|
||||
params.ExtraConfig = nil
|
||||
params.CustomHeaders = nil
|
||||
params.BaseURL = ""
|
||||
// Spec is deployment configuration of the same kind: it pins the
|
||||
// protocol and carries the compat overlay, whose extra_body is
|
||||
// merged verbatim into every request. It belongs with ExtraConfig,
|
||||
// not with the capability fields kept below.
|
||||
params.Spec = nil
|
||||
}
|
||||
if m.IsBuiltin && !canManageBuiltin {
|
||||
// Builtin: strip everything that could reveal per-tenant config.
|
||||
|
|
@ -91,6 +262,27 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
|
|||
params.ExtraConfig = nil
|
||||
params.CustomHeaders = nil
|
||||
params.AppID = ""
|
||||
params.Spec = nil
|
||||
}
|
||||
// Vendor-declared secret extra fields are credentials that happen to be
|
||||
// stored in extra_config. Drop them from the echoed map — even for
|
||||
// callers allowed to see integration detail, exactly as api_key is
|
||||
// withheld from an admin — and report presence instead. The stored map is
|
||||
// never mutated: params.ExtraConfig still aliases it here.
|
||||
//
|
||||
// Redaction spans every registered vendor, not just this row's: a row
|
||||
// whose provider was switched or hand-edited must not leak a leftover
|
||||
// credential just because its current vendor declares no secret field.
|
||||
secretKeys := SecretExtraConfigKeys(m.Parameters.Provider, m.Parameters.BaseURL)
|
||||
redactKeys := AllSecretExtraConfigKeys()
|
||||
if len(redactKeys) > 0 && len(params.ExtraConfig) > 0 {
|
||||
sanitized := make(map[string]string, len(params.ExtraConfig))
|
||||
for k, v := range params.ExtraConfig {
|
||||
if !redactKeys[k] {
|
||||
sanitized[k] = v
|
||||
}
|
||||
}
|
||||
params.ExtraConfig = sanitized
|
||||
}
|
||||
var creds map[string]CredentialFieldMetadata
|
||||
if !m.IsBuiltin || canManageBuiltin {
|
||||
|
|
@ -98,22 +290,49 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
|
|||
"api_key": {Configured: m.Parameters.APIKey != ""},
|
||||
"app_secret": {Configured: m.Parameters.AppSecret != ""},
|
||||
}
|
||||
for key := range secretKeys {
|
||||
creds[key] = CredentialFieldMetadata{
|
||||
Configured: strings.TrimSpace(m.Parameters.ExtraConfig[key]) != "",
|
||||
}
|
||||
}
|
||||
// A key this row's vendor does not declare was still withheld above,
|
||||
// so say it is there — otherwise the value silently vanishes from the
|
||||
// editor with nothing to explain why.
|
||||
for key := range redactKeys {
|
||||
if _, reported := creds[key]; reported {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(m.Parameters.ExtraConfig[key]) != "" {
|
||||
creds[key] = CredentialFieldMetadata{Configured: true}
|
||||
}
|
||||
}
|
||||
}
|
||||
var caps *catalog.Capabilities
|
||||
if m.Type == types.ModelTypeKnowledgeQA || m.Type == types.ModelTypeVLLM {
|
||||
if resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: m.Parameters.Provider, Model: m.Name, BaseURL: m.Parameters.BaseURL,
|
||||
ModelType: m.Type, Extra: m.Parameters.ExtraConfig, Override: m.Parameters.Spec,
|
||||
}); err == nil && m.Source == types.ModelSourceRemote {
|
||||
c := resolved.Capabilities()
|
||||
caps = &c
|
||||
}
|
||||
}
|
||||
return &ModelResponse{
|
||||
ID: m.ID,
|
||||
TenantID: m.TenantID,
|
||||
Name: m.Name,
|
||||
DisplayName: m.DisplayName,
|
||||
Type: m.Type,
|
||||
Source: m.Source,
|
||||
Description: m.Description,
|
||||
Parameters: params,
|
||||
IsDefault: m.IsDefault,
|
||||
IsBuiltin: m.IsBuiltin,
|
||||
Status: m.Status,
|
||||
CreatedAt: m.CreatedAt,
|
||||
UpdatedAt: m.UpdatedAt,
|
||||
Credentials: creds,
|
||||
ID: m.ID,
|
||||
TenantID: m.TenantID,
|
||||
Name: m.Name,
|
||||
DisplayName: m.DisplayName,
|
||||
Type: m.Type,
|
||||
Source: m.Source,
|
||||
Description: m.Description,
|
||||
Parameters: params,
|
||||
IsDefault: m.IsDefault,
|
||||
IsBuiltin: m.IsBuiltin,
|
||||
Status: m.Status,
|
||||
CreatedAt: m.CreatedAt,
|
||||
UpdatedAt: m.UpdatedAt,
|
||||
Credentials: creds,
|
||||
Capabilities: caps,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
|
@ -116,7 +117,224 @@ func TestModelResponse_ViewerStripsIntegrationDetail(t *testing.T) {
|
|||
assert.Nil(t, resp.Parameters.ExtraConfig)
|
||||
}
|
||||
|
||||
// registerSecretExtraVendor adds a vendor whose extra_config carries a real
|
||||
// credential, the way LKEAP / Volcengine rerank declare secret_key.
|
||||
func registerSecretExtraVendor(t *testing.T) string {
|
||||
t.Helper()
|
||||
id := "dto-secret-extra-vendor"
|
||||
catalog.Register(&catalog.Vendor{
|
||||
ID: id,
|
||||
Name: "Secret Extra Vendor",
|
||||
ModelTypes: []types.ModelType{types.ModelTypeRerank},
|
||||
URLPatterns: []string{"secret-extra-vendor.example.com"},
|
||||
ExtraFields: []catalog.ExtraField{
|
||||
{Key: "secret_key", Label: "Secret Key", Type: "password", Secret: true},
|
||||
{Key: "region", Label: "Region", Type: "string"},
|
||||
},
|
||||
})
|
||||
return id
|
||||
}
|
||||
|
||||
// A vendor-declared secret extra field is a credential that happens to live
|
||||
// in extra_config: GET must report its presence, never its value — even to a
|
||||
// caller allowed to see integration detail, exactly like api_key.
|
||||
func TestModelResponse_RedactsVendorSecretExtraConfig(t *testing.T) {
|
||||
provider := registerSecretExtraVendor(t)
|
||||
m := &types.Model{
|
||||
ID: "m-rerank",
|
||||
Type: types.ModelTypeRerank,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: provider,
|
||||
BaseURL: "https://secret-extra-vendor.example.com",
|
||||
APIKey: "AKID-public-id",
|
||||
ExtraConfig: map[string]string{
|
||||
"secret_key": "cam-secret-do-not-leak",
|
||||
"region": "ap-guangzhou",
|
||||
},
|
||||
},
|
||||
}
|
||||
resp := NewModelResponse(adminContext(), m)
|
||||
|
||||
assert.NotContains(t, resp.Parameters.ExtraConfig, "secret_key")
|
||||
assert.Equal(t, "ap-guangzhou", resp.Parameters.ExtraConfig["region"],
|
||||
"non-secret extra fields still round-trip")
|
||||
assert.True(t, resp.Credentials["secret_key"].Configured,
|
||||
"presence is reported in the same shape as api_key")
|
||||
|
||||
body, err := json.Marshal(resp)
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, string(body), "cam-secret-do-not-leak")
|
||||
|
||||
assert.Equal(t, "cam-secret-do-not-leak", m.Parameters.ExtraConfig["secret_key"],
|
||||
"the stored model must not be mutated by rendering a response")
|
||||
}
|
||||
|
||||
func TestModelResponse_SecretExtraConfigReportsAbsence(t *testing.T) {
|
||||
provider := registerSecretExtraVendor(t)
|
||||
m := &types.Model{
|
||||
ID: "m-rerank",
|
||||
Type: types.ModelTypeRerank,
|
||||
Parameters: types.ModelParameters{Provider: provider, ExtraConfig: map[string]string{"region": "ap-beijing"}},
|
||||
}
|
||||
resp := NewModelResponse(adminContext(), m)
|
||||
assert.False(t, resp.Credentials["secret_key"].Configured)
|
||||
assert.Equal(t, "ap-beijing", resp.Parameters.ExtraConfig["region"])
|
||||
}
|
||||
|
||||
// Legacy rows saved before provider was stored are matched by endpoint.
|
||||
func TestModelResponse_RedactsSecretExtraConfigForLegacyRowWithoutProvider(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
m := &types.Model{
|
||||
ID: "m-legacy",
|
||||
Type: types.ModelTypeRerank,
|
||||
Parameters: types.ModelParameters{
|
||||
BaseURL: "https://secret-extra-vendor.example.com/v1",
|
||||
ExtraConfig: map[string]string{"secret_key": "cam-secret-do-not-leak"},
|
||||
},
|
||||
}
|
||||
resp := NewModelResponse(adminContext(), m)
|
||||
assert.NotContains(t, resp.Parameters.ExtraConfig, "secret_key")
|
||||
assert.True(t, resp.Credentials["secret_key"].Configured)
|
||||
}
|
||||
|
||||
// PUT replaces extra_config wholesale and GET redacts the secret, so the
|
||||
// save that follows an unrelated edit must not erase the stored key.
|
||||
func TestPreserveStoredSecretExtras(t *testing.T) {
|
||||
provider := registerSecretExtraVendor(t)
|
||||
stored := map[string]string{"secret_key": "cam-secret-stored", "region": "ap-guangzhou"}
|
||||
sameVendor := VendorRef{Provider: provider}
|
||||
|
||||
t.Run("incoming omits the key", func(t *testing.T) {
|
||||
got := PreserveStoredSecretExtras(
|
||||
stored, map[string]string{"region": "ap-beijing"}, sameVendor, sameVendor)
|
||||
assert.Equal(t, "cam-secret-stored", got["secret_key"])
|
||||
assert.Equal(t, "ap-beijing", got["region"], "non-secret edits still apply")
|
||||
})
|
||||
t.Run("incoming carries an empty or masked value", func(t *testing.T) {
|
||||
for _, masked := range []string{"", " ", "******", "••••"} {
|
||||
got := PreserveStoredSecretExtras(
|
||||
stored, map[string]string{"secret_key": masked}, sameVendor, sameVendor)
|
||||
assert.Equal(t, "cam-secret-stored", got["secret_key"], "masked value %q means unchanged", masked)
|
||||
}
|
||||
})
|
||||
t.Run("incoming carries a new value", func(t *testing.T) {
|
||||
got := PreserveStoredSecretExtras(
|
||||
stored, map[string]string{"secret_key": "cam-secret-rotated"}, sameVendor, sameVendor)
|
||||
assert.Equal(t, "cam-secret-rotated", got["secret_key"])
|
||||
})
|
||||
t.Run("nil incoming keeps the whole stored map", func(t *testing.T) {
|
||||
assert.Equal(t, stored, PreserveStoredSecretExtras(stored, nil, sameVendor, sameVendor))
|
||||
})
|
||||
t.Run("unknown stored provider passes the map through", func(t *testing.T) {
|
||||
in := map[string]string{"secret_key": ""}
|
||||
assert.Equal(t, in,
|
||||
PreserveStoredSecretExtras(stored, in, VendorRef{Provider: "no-such-vendor"}, sameVendor))
|
||||
})
|
||||
t.Run("a request naming no vendor is not a vendor change", func(t *testing.T) {
|
||||
got := PreserveStoredSecretExtras(stored, map[string]string{}, sameVendor, VendorRef{})
|
||||
assert.Equal(t, "cam-secret-stored", got["secret_key"])
|
||||
})
|
||||
|
||||
// Switching the row to another vendor leaves the credential behind: it
|
||||
// authenticates the account of the integration being replaced.
|
||||
t.Run("vendor change drops the stored secret", func(t *testing.T) {
|
||||
other := VendorRef{Provider: "openai"}
|
||||
got := PreserveStoredSecretExtras(stored, map[string]string{"api": "openai_completions"}, sameVendor, other)
|
||||
assert.NotContains(t, got, "secret_key")
|
||||
assert.Equal(t, "openai_completions", got["api"])
|
||||
})
|
||||
t.Run("vendor change drops a masked secret instead of refilling it", func(t *testing.T) {
|
||||
other := VendorRef{Provider: "openai"}
|
||||
got := PreserveStoredSecretExtras(stored, map[string]string{"secret_key": "****"}, sameVendor, other)
|
||||
assert.NotContains(t, got, "secret_key")
|
||||
})
|
||||
t.Run("vendor change keeps a value the user typed", func(t *testing.T) {
|
||||
other := VendorRef{Provider: "openai"}
|
||||
got := PreserveStoredSecretExtras(stored, map[string]string{"secret_key": "typed-now"}, sameVendor, other)
|
||||
assert.Equal(t, "typed-now", got["secret_key"])
|
||||
})
|
||||
t.Run("vendor change with no extra_config at all", func(t *testing.T) {
|
||||
got := PreserveStoredSecretExtras(stored, nil, sameVendor, VendorRef{Provider: "openai"})
|
||||
assert.NotContains(t, got, "secret_key")
|
||||
assert.Equal(t, "ap-guangzhou", got["region"], "non-secret settings are not credentials")
|
||||
assert.Equal(t, "cam-secret-stored", stored["secret_key"], "the stored map is not mutated")
|
||||
})
|
||||
t.Run("a legacy row is matched by endpoint, not treated as a switch", func(t *testing.T) {
|
||||
legacy := VendorRef{BaseURL: "https://secret-extra-vendor.example.com/v1"}
|
||||
got := PreserveStoredSecretExtras(stored, map[string]string{}, legacy, legacy)
|
||||
assert.Equal(t, "cam-secret-stored", got["secret_key"])
|
||||
})
|
||||
}
|
||||
|
||||
// Redaction may not depend on the row's provider being the one that declared
|
||||
// the key: a hand-edited or emptied provider would otherwise echo a stored
|
||||
// credential in plaintext.
|
||||
func TestModelResponse_RedactsSecretExtraDeclaredByAnotherVendor(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
for _, provider := range []string{"openai", ""} {
|
||||
m := &types.Model{
|
||||
ID: "m-switched",
|
||||
Type: types.ModelTypeRerank,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: provider,
|
||||
ExtraConfig: map[string]string{"secret_key": "cam-secret-do-not-leak", "region": "ap-beijing"},
|
||||
},
|
||||
}
|
||||
resp := NewModelResponse(adminContext(), m)
|
||||
body, err := json.Marshal(resp)
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, string(body), "cam-secret-do-not-leak", "provider %q", provider)
|
||||
assert.Equal(t, "ap-beijing", resp.Parameters.ExtraConfig["region"])
|
||||
assert.True(t, resp.Credentials["secret_key"].Configured,
|
||||
"a withheld value is still reported as present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasAllSecretExtras(t *testing.T) {
|
||||
provider := registerSecretExtraVendor(t)
|
||||
assert.True(t, HasAllSecretExtras(provider, "", map[string]string{"secret_key": "cam-secret"}))
|
||||
assert.False(t, HasAllSecretExtras(provider, "", map[string]string{"region": "ap-guangzhou"}))
|
||||
assert.False(t, HasAllSecretExtras(provider, "", map[string]string{"secret_key": "****"}))
|
||||
assert.True(t, HasAllSecretExtras("no-such-vendor", "", nil), "a vendor with no secret extras is complete")
|
||||
}
|
||||
|
||||
func TestModelResponse_NilSafe(t *testing.T) {
|
||||
assert.Nil(t, NewModelResponse(adminContext(), nil))
|
||||
assert.Equal(t, []*ModelResponse{}, NewModelResponses(adminContext(), nil))
|
||||
}
|
||||
|
||||
func TestNewModelResponseStripsSpecFromNonAdmins(t *testing.T) {
|
||||
// Spec pins the protocol and carries the compat overlay, whose
|
||||
// extra_body is merged verbatim into every request. It is deployment
|
||||
// configuration, like base_url and extra_config beside it, not part of
|
||||
// the capability surface a viewer is shown.
|
||||
spec := &types.ModelSpecOverride{
|
||||
API: "anthropic-messages",
|
||||
Compat: map[string]any{"extra_body": map[string]any{"internal_route": "eu-gateway"}},
|
||||
}
|
||||
model := &types.Model{
|
||||
ID: "m1", Name: "claude-sonnet-4-5", Type: types.ModelTypeKnowledgeQA,
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: "anthropic", BaseURL: "https://gateway.internal/v1", Spec: spec,
|
||||
},
|
||||
}
|
||||
|
||||
admin := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
|
||||
if got := NewModelResponse(admin, model).Parameters.Spec; got == nil {
|
||||
t.Fatalf("an admin configures this; it must still be returned")
|
||||
}
|
||||
|
||||
viewer := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
params := NewModelResponse(viewer, model).Parameters
|
||||
if params.Spec != nil {
|
||||
t.Errorf("viewer should not see the protocol override, got %+v", params.Spec)
|
||||
}
|
||||
if params.BaseURL != "" || params.ExtraConfig != nil {
|
||||
t.Errorf("the neighbouring fields should still be stripped")
|
||||
}
|
||||
// The stored model is shared; stripping must not mutate it.
|
||||
if model.Parameters.Spec == nil {
|
||||
t.Errorf("NewModelResponse must not clear the stored spec")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -603,7 +603,12 @@ func (h *InitializationHandler) InitializeByKB(c *gin.Context) {
|
|||
"success": true,
|
||||
"message": "知识库配置更新成功",
|
||||
"data": gin.H{
|
||||
"models": processedModels,
|
||||
// Through the response DTO, like every other body carrying a
|
||||
// model: types.Model marshals api_key in plaintext, and now that
|
||||
// the reuse path keeps the stored credential instead of
|
||||
// overwriting it, echoing the row would hand back a key the
|
||||
// caller never submitted. KnowledgeBase redacts itself.
|
||||
"models": dto.NewModelResponses(ctx, processedModels),
|
||||
"knowledge_base": kb,
|
||||
},
|
||||
})
|
||||
|
|
@ -855,7 +860,7 @@ func (h *InitializationHandler) processInitializationModels(
|
|||
existingModel.Name = model.Name
|
||||
existingModel.Source = model.Source
|
||||
existingModel.Description = model.Description
|
||||
existingModel.Parameters = model.Parameters
|
||||
descriptor.applyToStoredParameters(&existingModel.Parameters)
|
||||
existingModel.UpdatedAt = time.Now()
|
||||
|
||||
if err := h.modelService.UpdateModel(ctx, existingModel); err != nil {
|
||||
|
|
@ -882,6 +887,32 @@ func (h *InitializationHandler) processInitializationModels(
|
|||
return processedModels, nil
|
||||
}
|
||||
|
||||
// applyToStoredParameters merges the initialization payload into the
|
||||
// parameters of a model row that already exists.
|
||||
//
|
||||
// The wizard collects four fields (endpoint, key, interface type, embedding
|
||||
// dimension); everything else on the row — provider, extra_config, custom
|
||||
// headers, spec, concurrency, context window — was configured in the model
|
||||
// editor. Assigning toModel()'s parameters wholesale erased all of it, and
|
||||
// blanked the stored API key whenever the payload carried none, so a KB that
|
||||
// was merely re-initialized came back with a model nobody could call. Only
|
||||
// the fields the payload actually carries are written; an empty one means
|
||||
// "not submitted", not "clear it".
|
||||
func (descriptor modelDescriptor) applyToStoredParameters(params *types.ModelParameters) {
|
||||
if descriptor.baseURL != "" {
|
||||
params.BaseURL = descriptor.baseURL
|
||||
}
|
||||
if descriptor.apiKey != "" {
|
||||
params.APIKey = descriptor.apiKey
|
||||
}
|
||||
if descriptor.interfaceType != "" {
|
||||
params.InterfaceType = descriptor.interfaceType
|
||||
}
|
||||
if descriptor.modelType == types.ModelTypeEmbedding && descriptor.dimension > 0 {
|
||||
params.EmbeddingParameters.Dimension = descriptor.dimension
|
||||
}
|
||||
}
|
||||
|
||||
func (descriptor modelDescriptor) toModel() *types.Model {
|
||||
model := &types.Model{
|
||||
Type: descriptor.modelType,
|
||||
|
|
@ -1770,7 +1801,12 @@ func (h *InitializationHandler) fillSecretsFromStoredModel(ctx context.Context,
|
|||
if req == nil || req.ModelID == "" {
|
||||
return
|
||||
}
|
||||
if req.APIKey != "" && req.AppSecret != "" && req.ExtraConfig != nil {
|
||||
// A request that already carries every secret needs no lookup — but a
|
||||
// secret stored in extra_config (LKEAP / Volcengine secret_key) is
|
||||
// redacted by GET, so "extraConfig is present" does not mean it is
|
||||
// complete.
|
||||
if req.APIKey != "" && req.AppSecret != "" && req.ExtraConfig != nil &&
|
||||
dto.HasAllSecretExtras(req.Provider, req.BaseURL, req.ExtraConfig) {
|
||||
return
|
||||
}
|
||||
stored, err := h.modelService.GetModelByID(ctx, req.ModelID)
|
||||
|
|
@ -1785,9 +1821,15 @@ func (h *InitializationHandler) fillSecretsFromStoredModel(ctx context.Context,
|
|||
if req.AppSecret == "" {
|
||||
req.AppSecret = stored.Parameters.AppSecret
|
||||
}
|
||||
if req.ExtraConfig == nil {
|
||||
req.ExtraConfig = stored.Parameters.ExtraConfig
|
||||
}
|
||||
// Same contract as PUT /models/{id}: an absent or masked secret extra
|
||||
// falls back to the stored value, a real one the user just typed wins —
|
||||
// and a test against a different vendor gets no stored credential, which
|
||||
// belongs to the integration the row is being moved away from.
|
||||
req.ExtraConfig = dto.PreserveStoredSecretExtras(
|
||||
stored.Parameters.ExtraConfig, req.ExtraConfig,
|
||||
dto.VendorRef{Provider: stored.Parameters.Provider, BaseURL: stored.Parameters.BaseURL},
|
||||
dto.VendorRef{Provider: req.Provider, BaseURL: req.BaseURL},
|
||||
)
|
||||
}
|
||||
|
||||
// RemoteModelCheckRequest 兼容旧 swagger 定义。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,215 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Re-initializing a KB used to assign the wizard's four fields over the whole
|
||||
// parameter struct of the stored row, erasing everything the model editor
|
||||
// owns (provider, extra_config, custom headers, spec, concurrency, context
|
||||
// window) and blanking the API key whenever the payload carried none.
|
||||
|
||||
func storedEditorConfiguredModel() *types.Model {
|
||||
return &types.Model{
|
||||
ID: "m-llm", Type: types.ModelTypeKnowledgeQA, Name: "gpt-4o",
|
||||
TenantID: 10042, Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: "azure",
|
||||
BaseURL: "https://old.example.com/v1",
|
||||
APIKey: "stored-key",
|
||||
ExtraConfig: map[string]string{
|
||||
"api_version": "2024-06-01",
|
||||
"secret_key": "cam-secret-stored",
|
||||
},
|
||||
CustomHeaders: map[string]string{"X-Team": "rag"},
|
||||
MaxConcurrency: 4,
|
||||
ContextWindow: 128000,
|
||||
Spec: &types.ModelSpecOverride{API: "openai-completions"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// initExistingLLM runs processInitializationModels against a KB whose LLM
|
||||
// slot already points at stored, and returns the row it persisted.
|
||||
func initExistingLLM(t *testing.T, stored *types.Model, mutate func(*InitializationRequest)) *types.Model {
|
||||
t.Helper()
|
||||
svc := &stubTenantStampModelService{}
|
||||
svc.getModelByID = func(_ context.Context, id string) (*types.Model, error) {
|
||||
if id == stored.ID {
|
||||
return stored, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
h := &InitializationHandler{modelService: svc}
|
||||
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042, SummaryModelID: stored.ID}
|
||||
|
||||
req := newTenantStampRequest()
|
||||
if mutate != nil {
|
||||
mutate(req)
|
||||
}
|
||||
_, err := h.processInitializationModels(context.Background(), kb, "kb-1", req)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, svc.updated, "the existing model was not updated")
|
||||
return svc.updated[0]
|
||||
}
|
||||
|
||||
func TestProcessInitializationModelsKeepsEditorOwnedParameters(t *testing.T) {
|
||||
stored := storedEditorConfiguredModel()
|
||||
updated := initExistingLLM(t, stored, func(req *InitializationRequest) {
|
||||
req.LLM.APIKey = "" // the wizard re-submits without re-typing the key
|
||||
req.LLM.BaseURL = "https://new.example.com/v1"
|
||||
})
|
||||
|
||||
p := updated.Parameters
|
||||
assert.Equal(t, "https://new.example.com/v1", p.BaseURL, "the endpoint edit must still land")
|
||||
assert.Equal(t, "stored-key", p.APIKey, "an omitted key means unchanged, not cleared")
|
||||
assert.Equal(t, "azure", p.Provider)
|
||||
assert.Equal(t, "2024-06-01", p.ExtraConfig["api_version"])
|
||||
assert.Equal(t, "cam-secret-stored", p.ExtraConfig["secret_key"])
|
||||
assert.Equal(t, map[string]string{"X-Team": "rag"}, p.CustomHeaders)
|
||||
assert.Equal(t, 4, p.MaxConcurrency)
|
||||
assert.Equal(t, 128000, p.ContextWindow)
|
||||
assert.NotNil(t, p.Spec)
|
||||
}
|
||||
|
||||
// Initialization's own purpose still works: endpoint and key are writable.
|
||||
func TestProcessInitializationModelsStillAppliesSubmittedFields(t *testing.T) {
|
||||
stored := storedEditorConfiguredModel()
|
||||
updated := initExistingLLM(t, stored, func(req *InitializationRequest) {
|
||||
req.LLM.APIKey = "rotated-key"
|
||||
req.LLM.BaseURL = "https://new.example.com/v1"
|
||||
})
|
||||
assert.Equal(t, "rotated-key", updated.Parameters.APIKey)
|
||||
assert.Equal(t, "https://new.example.com/v1", updated.Parameters.BaseURL)
|
||||
}
|
||||
|
||||
// The embedding slot carries a dimension, and changing it is the one reason
|
||||
// an operator re-runs initialization against an existing embedding row.
|
||||
func TestProcessInitializationModelsAppliesEmbeddingDimension(t *testing.T) {
|
||||
stored := &types.Model{
|
||||
ID: "m-embed", Type: types.ModelTypeEmbedding, Name: "bge-m3", TenantID: 10042,
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: "siliconflow",
|
||||
BaseURL: "https://old.example.com/v1",
|
||||
APIKey: "stored-key",
|
||||
ExtraConfig: map[string]string{"remote_model_name": "BAAI/bge-m3"},
|
||||
EmbeddingParameters: types.EmbeddingParameters{Dimension: 768, TruncatePromptTokens: 512},
|
||||
},
|
||||
}
|
||||
svc := &stubTenantStampModelService{}
|
||||
svc.getModelByID = func(_ context.Context, id string) (*types.Model, error) {
|
||||
if id == "m-embed" {
|
||||
return stored, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
h := &InitializationHandler{modelService: svc}
|
||||
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042, EmbeddingModelID: "m-embed"}
|
||||
|
||||
req := newTenantStampRequest()
|
||||
req.Embedding.Dimension = 1024
|
||||
req.Embedding.APIKey = ""
|
||||
_, err := h.processInitializationModels(context.Background(), kb, "kb-1", req)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, svc.updated)
|
||||
|
||||
p := svc.updated[0].Parameters
|
||||
assert.Equal(t, 1024, p.EmbeddingParameters.Dimension, "the dimension edit must still land")
|
||||
assert.Equal(t, 512, p.EmbeddingParameters.TruncatePromptTokens,
|
||||
"the rest of the embedding parameters is not part of the payload")
|
||||
assert.Equal(t, "BAAI/bge-m3", p.ExtraConfig["remote_model_name"])
|
||||
assert.Equal(t, "stored-key", p.APIKey)
|
||||
}
|
||||
|
||||
type stubInitKBService struct {
|
||||
interfaces.KnowledgeBaseService
|
||||
kb *types.KnowledgeBase
|
||||
}
|
||||
|
||||
func (s *stubInitKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
|
||||
return s.kb, nil
|
||||
}
|
||||
|
||||
type stubInitKBRepository struct {
|
||||
interfaces.KnowledgeBaseRepository
|
||||
}
|
||||
|
||||
func (s *stubInitKBRepository) UpdateKnowledgeBase(context.Context, *types.KnowledgeBase) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// POST /initialization/initialize/{kbId} used to marshal the raw model rows,
|
||||
// and types.Model carries api_key in plaintext. Now that the reuse path keeps
|
||||
// the stored credential rather than overwriting it with the payload's, that
|
||||
// body would hand back a key the caller never submitted.
|
||||
func TestInitializeByKB_ResponseDoesNotEchoStoredAPIKey(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
stored := storedEditorConfiguredModel()
|
||||
svc := &stubTenantStampModelService{}
|
||||
svc.getModelByID = func(_ context.Context, id string) (*types.Model, error) {
|
||||
if id == stored.ID {
|
||||
return stored, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042, SummaryModelID: stored.ID}
|
||||
h := &InitializationHandler{
|
||||
modelService: svc,
|
||||
kbService: &stubInitKBService{kb: kb},
|
||||
kbRepository: &stubInitKBRepository{},
|
||||
}
|
||||
|
||||
req := newTenantStampRequest()
|
||||
req.LLM.APIKey = ""
|
||||
// The full handler runs SSRF validation, which would otherwise resolve
|
||||
// the host over the network. Whitelist one name of our own and clear it
|
||||
// again, so no other test in this package sees a relaxed check.
|
||||
secutils.SetSSRFWhitelistFromRaw("init-merge-test.example.com")
|
||||
t.Cleanup(func() { secutils.SetSSRFWhitelistFromRaw("") })
|
||||
req.LLM.BaseURL = "https://init-merge-test.example.com/v1"
|
||||
req.Embedding.BaseURL = "https://init-merge-test.example.com/v1"
|
||||
req.DocumentSplitting.ChunkSize = 512
|
||||
req.DocumentSplitting.ChunkOverlap = 64
|
||||
req.DocumentSplitting.Separators = []string{"\n"}
|
||||
body, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/initialization/initialize/kb-1", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request = c.Request.WithContext(types.WithCaller(c.Request.Context(), types.Caller{
|
||||
TenantID: 10042, UserID: "u-1", Role: types.TenantRoleAdmin,
|
||||
}))
|
||||
c.Params = gin.Params{{Key: "kbId", Value: "kb-1"}}
|
||||
|
||||
h.InitializeByKB(c)
|
||||
require.Empty(t, c.Errors.Errors())
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
assert.NotContains(t, w.Body.String(), "stored-key")
|
||||
assert.NotContains(t, w.Body.String(), "cam-secret-stored")
|
||||
assert.Contains(t, w.Body.String(), stored.ID, "the model ids the caller needs are still returned")
|
||||
}
|
||||
|
||||
// A rerank row is never reached by this path at all: the KB has no rerank
|
||||
// slot, so findExistingModelID has nothing to return and every run creates a
|
||||
// fresh row. Pinning it keeps the reasoning above honest if a slot is added.
|
||||
func TestFindExistingModelIDHasNoRerankSlot(t *testing.T) {
|
||||
h := &InitializationHandler{}
|
||||
kb := &types.KnowledgeBase{SummaryModelID: "m-llm", EmbeddingModelID: "m-embed"}
|
||||
assert.Empty(t, h.findExistingModelID(kb, types.ModelTypeRerank))
|
||||
assert.Equal(t, "m-llm", h.findExistingModelID(kb, types.ModelTypeKnowledgeQA))
|
||||
}
|
||||
|
|
@ -12,8 +12,9 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/handler/dto"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/provider"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
|
|
@ -92,6 +93,10 @@ func (h *ModelHandler) CreateModel(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
}
|
||||
if err := validateCatalogParameters(req.Name, req.Type, &req.Parameters); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
model := &types.Model{
|
||||
TenantID: tenantID,
|
||||
|
|
@ -215,6 +220,8 @@ type ModelDebugOptions struct {
|
|||
TopP *float64 `json:"top_p,omitempty"`
|
||||
MaxTokens *int `json:"max_tokens,omitempty"`
|
||||
Thinking *bool `json:"thinking,omitempty"`
|
||||
// ReasoningEffort is the graded level; when set it overrides Thinking.
|
||||
ReasoningEffort string `json:"reasoning_effort,omitempty"`
|
||||
}
|
||||
|
||||
func parseModelDebugOptions(raw string) (ModelDebugOptions, error) {
|
||||
|
|
@ -234,15 +241,29 @@ func parseModelDebugOptions(raw string) (ModelDebugOptions, error) {
|
|||
if opts.TopP != nil && (*opts.TopP <= 0 || *opts.TopP > 1) {
|
||||
return opts, fmt.Errorf("top_p must be greater than 0 and at most 1")
|
||||
}
|
||||
if _, ok := api.ParseReasoningEffort(opts.ReasoningEffort); !ok {
|
||||
return opts, fmt.Errorf("reasoning_effort must be one of %v", api.AllReasoningEfforts)
|
||||
}
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
// redactedDebugConfig masks the credentials inside an extra_config before it
|
||||
// is echoed in the debug preview. The catalog's own Secret declaration is the
|
||||
// source of truth — the same one the read path uses — so a new vendor field
|
||||
// is covered by declaring it, whatever it is called. The name heuristic stays
|
||||
// as a net under it, for keys no vendor declares (deployment overlays,
|
||||
// hand-written rows).
|
||||
func redactedDebugConfig(config map[string]string) map[string]string {
|
||||
if len(config) == 0 {
|
||||
return nil
|
||||
}
|
||||
declared := dto.AllSecretExtraConfigKeys()
|
||||
out := make(map[string]string, len(config))
|
||||
for key, value := range config {
|
||||
if declared[key] {
|
||||
out[key] = "[REDACTED]"
|
||||
continue
|
||||
}
|
||||
lower := strings.ToLower(key)
|
||||
if strings.Contains(lower, "secret") ||
|
||||
strings.Contains(lower, "token") ||
|
||||
|
|
@ -454,12 +475,21 @@ func (h *ModelHandler) DebugModel(c *gin.Context) {
|
|||
chatOpts.MaxTokens = *opts.MaxTokens
|
||||
}
|
||||
chatOpts.Thinking = opts.Thinking
|
||||
if level, _ := api.ParseReasoningEffort(opts.ReasoningEffort); level != "" {
|
||||
chatOpts.ReasoningEffort = level
|
||||
}
|
||||
chatConfig := chat.ConfigFromModel(model, "", "")
|
||||
thinkingControl := chat.EffectiveThinkingControl(chatConfig)
|
||||
requestedLevel, requested := chatOpts.Reasoning()
|
||||
observations["stream"] = true
|
||||
observations["requested_thinking"] = opts.Thinking != nil && *opts.Thinking
|
||||
observations["requested_thinking"] = requested && requestedLevel.Enabled()
|
||||
observations["requested_reasoning_effort"] = string(requestedLevel)
|
||||
observations["thinking_control"] = thinkingControl
|
||||
observations["thinking_parameter_sent"] = opts.Thinking != nil && thinkingControl != "none"
|
||||
observations["thinking_parameter_sent"] = requested && thinkingControl != "none"
|
||||
if resolved, err := chat.Resolve(chatConfig); err == nil {
|
||||
observations["api"] = string(resolved.API)
|
||||
observations["capabilities"] = resolved.Capabilities()
|
||||
}
|
||||
|
||||
stream, callErr := instance.ChatStream(ctx, messages, chatOpts)
|
||||
if callErr != nil {
|
||||
|
|
@ -606,6 +636,17 @@ func (h *ModelHandler) UpdateModel(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
}
|
||||
effectiveName, effectiveType := req.Name, req.Type
|
||||
if effectiveName == "" {
|
||||
effectiveName = model.Name
|
||||
}
|
||||
if effectiveType == "" {
|
||||
effectiveType = model.Type
|
||||
}
|
||||
if err := validateCatalogParameters(effectiveName, effectiveType, &req.Parameters); err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
// Credentials (api_key, app_secret) NEVER flow through this endpoint —
|
||||
// they live behind the /credentials subresource. Force-preserve them by
|
||||
// snapshotting the stored values before copying request fields in, so
|
||||
|
|
@ -632,9 +673,17 @@ func (h *ModelHandler) UpdateModel(c *gin.Context) {
|
|||
if newParams.AppID == "" {
|
||||
newParams.AppID = model.Parameters.AppID
|
||||
}
|
||||
if newParams.ExtraConfig == nil {
|
||||
newParams.ExtraConfig = model.Parameters.ExtraConfig
|
||||
}
|
||||
// extra_config is replaced wholesale here, but GET redacts the vendor's
|
||||
// secret extra fields (dto.NewModelResponse), so a UI round-trip carries
|
||||
// no value for them — keep the stored secret unless the caller sent a new
|
||||
// one. This also covers the request that omits extra_config entirely.
|
||||
// Both vendor identities are passed: moving the row to another vendor
|
||||
// must drop the old credential, not merge it back in.
|
||||
newParams.ExtraConfig = dto.PreserveStoredSecretExtras(
|
||||
model.Parameters.ExtraConfig, newParams.ExtraConfig,
|
||||
dto.VendorRef{Provider: model.Parameters.Provider, BaseURL: model.Parameters.BaseURL},
|
||||
dto.VendorRef{Provider: newParams.Provider, BaseURL: newParams.BaseURL},
|
||||
)
|
||||
model.Parameters = newParams
|
||||
|
||||
model.Source = req.Source
|
||||
|
|
@ -707,108 +756,10 @@ func (h *ModelHandler) DeleteModel(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
// ModelProviderDTO 模型厂商信息 DTO
|
||||
type ModelProviderDTO struct {
|
||||
Value string `json:"value"` // provider 标识符
|
||||
Label string `json:"label"` // 显示名称
|
||||
Description string `json:"description"` // 描述
|
||||
DefaultURLs map[string]string `json:"defaultUrls"` // 按模型类型区分的默认 URL
|
||||
ModelTypes []string `json:"modelTypes"` // 支持的模型类型
|
||||
}
|
||||
|
||||
// modelTypeToFrontend 将后端 ModelType 转换为前端兼容的字符串
|
||||
// KnowledgeQA -> chat, Embedding -> embedding, Rerank -> rerank, VLLM -> vllm
|
||||
func modelTypeToFrontend(mt types.ModelType) string {
|
||||
switch mt {
|
||||
case types.ModelTypeKnowledgeQA:
|
||||
return "chat"
|
||||
case types.ModelTypeEmbedding:
|
||||
return "embedding"
|
||||
case types.ModelTypeRerank:
|
||||
return "rerank"
|
||||
case types.ModelTypeVLLM:
|
||||
return "vllm"
|
||||
case types.ModelTypeASR:
|
||||
return "asr"
|
||||
default:
|
||||
return string(mt)
|
||||
}
|
||||
}
|
||||
|
||||
// ListModelProviders godoc
|
||||
// @Summary 获取模型厂商列表
|
||||
// @Description 根据模型类型获取支持的厂商列表及配置信息
|
||||
// @Tags 模型管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param model_type query string false "模型类型 (chat, embedding, rerank, vllm)"
|
||||
// @Success 200 {object} map[string]interface{} "厂商列表"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /models/providers [get]
|
||||
func (h *ModelHandler) ListModelProviders(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
modelType := c.Query("model_type")
|
||||
logger.Infof(ctx, "Listing model providers for type: %s", secutils.SanitizeForLog(modelType))
|
||||
|
||||
// 将前端类型映射到后端类型
|
||||
// 前端: chat, embedding, rerank, vllm
|
||||
// 后端: KnowledgeQA, Embedding, Rerank, VLLM
|
||||
var backendModelType types.ModelType
|
||||
switch modelType {
|
||||
case "chat":
|
||||
backendModelType = types.ModelTypeKnowledgeQA
|
||||
case "embedding":
|
||||
backendModelType = types.ModelTypeEmbedding
|
||||
case "rerank":
|
||||
backendModelType = types.ModelTypeRerank
|
||||
case "vllm":
|
||||
backendModelType = types.ModelTypeVLLM
|
||||
case "asr":
|
||||
backendModelType = types.ModelTypeASR
|
||||
default:
|
||||
backendModelType = types.ModelType(modelType)
|
||||
}
|
||||
|
||||
var providers []provider.ProviderInfo
|
||||
if modelType != "" {
|
||||
// 按模型类型过滤
|
||||
providers = provider.ListByModelType(backendModelType)
|
||||
} else {
|
||||
// 返回所有 provider
|
||||
providers = provider.List()
|
||||
}
|
||||
|
||||
// 转换为 DTO
|
||||
result := make([]ModelProviderDTO, 0, len(providers))
|
||||
for _, p := range providers {
|
||||
// 转换 DefaultURLs map[types.ModelType]string -> map[string]string
|
||||
// 使用前端兼容的 key (chat 而不是 KnowledgeQA)
|
||||
defaultURLs := make(map[string]string)
|
||||
for mt, url := range p.DefaultURLs {
|
||||
frontendType := modelTypeToFrontend(mt)
|
||||
defaultURLs[frontendType] = url
|
||||
}
|
||||
|
||||
// 转换 ModelTypes 为前端兼容格式
|
||||
modelTypes := make([]string, 0, len(p.ModelTypes))
|
||||
for _, mt := range p.ModelTypes {
|
||||
modelTypes = append(modelTypes, modelTypeToFrontend(mt))
|
||||
}
|
||||
|
||||
result = append(result, ModelProviderDTO{
|
||||
Value: string(p.Name),
|
||||
Label: p.DisplayName,
|
||||
Description: p.Description,
|
||||
DefaultURLs: defaultURLs,
|
||||
ModelTypes: modelTypes,
|
||||
})
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieved %d providers", len(result))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": result,
|
||||
})
|
||||
// validateCatalogParameters rejects protocol / compat overrides the catalog
|
||||
// cannot interpret (unknown extra_config.api, unknown compat keys, bad
|
||||
// reasoning levels) so a typo fails at save time instead of at the first
|
||||
// chat call. Only chat and VLM rows carry these fields.
|
||||
func validateCatalogParameters(name string, modelType types.ModelType, params *types.ModelParameters) error {
|
||||
return catalog.ValidateRow(name, modelType, params)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,316 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/handler/dto"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ModelProviderDTO is the vendor definition the model editor renders from.
|
||||
// Everything the UI shows for a vendor (name, icon, URLs, extra fields,
|
||||
// catalog models, thinking capabilities) comes from here; the frontend keeps
|
||||
// no vendor table of its own.
|
||||
type ModelProviderDTO struct {
|
||||
Value string `json:"value"`
|
||||
Label string `json:"label"`
|
||||
Labels map[string]string `json:"labels,omitempty"`
|
||||
Description string `json:"description"`
|
||||
Descriptions map[string]string `json:"descriptions,omitempty"`
|
||||
Website string `json:"website,omitempty"`
|
||||
// Icon is a data: URI (image/svg+xml;base64) ready for <img src>.
|
||||
Icon string `json:"icon,omitempty"`
|
||||
API api.API `json:"api"`
|
||||
Auth catalog.AuthStyle `json:"auth"`
|
||||
RequiresAuth bool `json:"requiresAuth"`
|
||||
DefaultURLs map[string]string `json:"defaultUrls"`
|
||||
ModelTypes []string `json:"modelTypes"`
|
||||
ExtraFields []catalog.ExtraField `json:"extraFields,omitempty"`
|
||||
// CredentialLabels rename the primary credential input for the model
|
||||
// types that do not take a plain API key (signed rerank APIs).
|
||||
CredentialLabels []catalog.CredentialLabel `json:"credentialLabels,omitempty"`
|
||||
Models []ModelCatalogEntryDTO `json:"models,omitempty"`
|
||||
Thinking ProviderThinkingDTO `json:"thinking"`
|
||||
Order int `json:"order"`
|
||||
}
|
||||
|
||||
// ProviderThinkingDTO summarizes how the vendor encodes thinking so the UI
|
||||
// can explain the reasoning selector.
|
||||
type ProviderThinkingDTO struct {
|
||||
Format string `json:"format"`
|
||||
Levels []api.ReasoningEffort `json:"levels"`
|
||||
}
|
||||
|
||||
// ModelCatalogEntryDTO is one catalog model for the picker.
|
||||
type ModelCatalogEntryDTO struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
API api.API `json:"api,omitempty"`
|
||||
Reasoning bool `json:"reasoning"`
|
||||
Input []string `json:"input,omitempty"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
Dimension int `json:"dimension,omitempty"`
|
||||
ThinkingLevels []api.ReasoningEffort `json:"thinking_levels"`
|
||||
Cost *catalog.ModelCost `json:"cost,omitempty"`
|
||||
// Source is the vendor page these facts were read from, so the editor can
|
||||
// send an operator to the documentation for this exact model.
|
||||
Source string `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
// modelTypeToFrontend 将后端 ModelType 转换为前端兼容的字符串
|
||||
// KnowledgeQA -> chat, Embedding -> embedding, Rerank -> rerank, VLLM -> vllm
|
||||
func modelTypeToFrontend(mt types.ModelType) string {
|
||||
switch mt {
|
||||
case types.ModelTypeKnowledgeQA:
|
||||
return "chat"
|
||||
case types.ModelTypeEmbedding:
|
||||
return "embedding"
|
||||
case types.ModelTypeRerank:
|
||||
return "rerank"
|
||||
case types.ModelTypeVLLM:
|
||||
return "vllm"
|
||||
case types.ModelTypeASR:
|
||||
return "asr"
|
||||
default:
|
||||
return string(mt)
|
||||
}
|
||||
}
|
||||
|
||||
func iconDataURI(svg []byte) string {
|
||||
if len(svg) == 0 {
|
||||
return ""
|
||||
}
|
||||
return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString(svg)
|
||||
}
|
||||
|
||||
func providerDTO(v *catalog.Vendor, modelType types.ModelType, includeModels bool) ModelProviderDTO {
|
||||
defaultURLs := make(map[string]string, len(v.DefaultBaseURLs))
|
||||
for mt, url := range v.DefaultBaseURLs {
|
||||
defaultURLs[modelTypeToFrontend(mt)] = url
|
||||
}
|
||||
modelTypes := make([]string, 0, len(v.ModelTypes))
|
||||
for _, mt := range v.ModelTypes {
|
||||
modelTypes = append(modelTypes, modelTypeToFrontend(mt))
|
||||
}
|
||||
dto := ModelProviderDTO{
|
||||
Value: v.ID,
|
||||
Label: v.Name,
|
||||
Labels: v.Names,
|
||||
Description: v.Description,
|
||||
Descriptions: v.Descriptions,
|
||||
Website: v.Website,
|
||||
Icon: iconDataURI(v.Icon),
|
||||
API: v.API,
|
||||
Auth: v.Auth,
|
||||
RequiresAuth: v.RequiresAuth,
|
||||
DefaultURLs: defaultURLs,
|
||||
ModelTypes: modelTypes,
|
||||
ExtraFields: v.ExtraFields,
|
||||
// Passed through raw, like ExtraFields: the editor resolves the
|
||||
// locale and the model type, so a new vendor needs no UI change.
|
||||
CredentialLabels: v.CredentialLabels,
|
||||
Order: v.Order,
|
||||
}
|
||||
// Vendor-level thinking summary: resolve an unknown model so only the
|
||||
// vendor defaults contribute.
|
||||
if resolved, err := catalog.Resolve(catalog.Ref{Provider: v.ID, Model: "__vendor_default__"}); err == nil {
|
||||
caps := resolved.Capabilities()
|
||||
dto.Thinking = ProviderThinkingDTO{Format: caps.ThinkingFormat, Levels: caps.ThinkingLevels}
|
||||
}
|
||||
if dto.Thinking.Levels == nil {
|
||||
dto.Thinking.Levels = []api.ReasoningEffort{}
|
||||
}
|
||||
if !includeModels {
|
||||
return dto
|
||||
}
|
||||
wanted := []types.ModelType{modelType}
|
||||
if modelType == "" {
|
||||
wanted = v.ModelTypes
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, mt := range wanted {
|
||||
for _, m := range v.ModelsByType(mt) {
|
||||
if seen[m.ID] {
|
||||
continue
|
||||
}
|
||||
seen[m.ID] = true
|
||||
entry := ModelCatalogEntryDTO{
|
||||
ID: m.ID,
|
||||
Name: m.DisplayName(),
|
||||
Type: modelTypeToFrontend(m.Type),
|
||||
API: m.API,
|
||||
Reasoning: m.Reasoning,
|
||||
Input: m.Input,
|
||||
ContextWindow: m.ContextWindow,
|
||||
MaxOutputTokens: m.MaxOutputTokens,
|
||||
Dimension: m.Dimension,
|
||||
Cost: m.Cost,
|
||||
ThinkingLevels: []api.ReasoningEffort{},
|
||||
Source: m.Source,
|
||||
}
|
||||
// A vision chat model keeps Type KnowledgeQA (VLM eligibility is
|
||||
// derived from Input), so this covers reasoning VLMs too;
|
||||
// embedding / rerank / ASR entries have no thinking levels.
|
||||
if m.Type == "" || m.Type == "KnowledgeQA" {
|
||||
if resolved, err := catalog.Resolve(catalog.Ref{Provider: v.ID, Model: m.ID}); err == nil {
|
||||
entry.ThinkingLevels = resolved.Capabilities().ThinkingLevels
|
||||
}
|
||||
}
|
||||
dto.Models = append(dto.Models, entry)
|
||||
}
|
||||
}
|
||||
return dto
|
||||
}
|
||||
|
||||
// ListModelProviders godoc
|
||||
// @Summary 获取模型厂商列表
|
||||
// @Description 根据模型类型获取支持的厂商定义(含图标、默认地址、额外字段、内置模型目录与思考能力)
|
||||
// @Tags 模型管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param model_type query string false "模型类型 (chat, embedding, rerank, vllm, asr)"
|
||||
// @Success 200 {object} map[string]interface{} "厂商列表"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /models/providers [get]
|
||||
func (h *ModelHandler) ListModelProviders(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
modelType := c.Query("model_type")
|
||||
logger.Infof(ctx, "Listing model providers for type: %s", secutils.SanitizeForLog(modelType))
|
||||
|
||||
var backendType types.ModelType
|
||||
if modelType != "" {
|
||||
parsed, ok := catalog.ParseModelType(modelType)
|
||||
if !ok {
|
||||
_ = c.Error(errors.NewBadRequestError("unknown model_type"))
|
||||
return
|
||||
}
|
||||
backendType = parsed
|
||||
}
|
||||
|
||||
var vendors []*catalog.Vendor
|
||||
if backendType != "" {
|
||||
vendors = catalog.ListByType(backendType)
|
||||
} else {
|
||||
vendors = catalog.List()
|
||||
}
|
||||
// Default base URLs are the editor's prefill, and only a caller who may
|
||||
// configure integrations can use them. A deployment overlay may also
|
||||
// repoint a vendor at an internal gateway, which would otherwise reach
|
||||
// every viewer here while the same URL is stripped from the model rows
|
||||
// themselves (dto.NewModelResponse).
|
||||
includeURLs := dto.CanViewIntegrationSecrets(ctx)
|
||||
result := make([]ModelProviderDTO, 0, len(vendors))
|
||||
for _, v := range vendors {
|
||||
p := providerDTO(v, backendType, true)
|
||||
if !includeURLs {
|
||||
p.DefaultURLs = nil
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
logger.Infof(ctx, "Retrieved %d providers", len(result))
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
|
||||
}
|
||||
|
||||
// ResolveModelCatalog godoc
|
||||
// @Summary 解析模型的有效接入配置
|
||||
// @Description 根据厂商、模型名、Base URL 与 extra_config 返回目录解析结果(协议、思考等级、上下文等),供模型编辑器实时展示
|
||||
// @Tags 模型管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param provider query string true "厂商标识"
|
||||
// @Param model query string false "模型名"
|
||||
// @Param base_url query string false "Base URL"
|
||||
// @Param model_type query string false "模型类型"
|
||||
// @Success 200 {object} map[string]interface{} "解析结果"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /models/catalog/resolve [get]
|
||||
func (h *ModelHandler) ResolveModelCatalog(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
providerID := strings.TrimSpace(c.Query("provider"))
|
||||
modelName := strings.TrimSpace(c.Query("model"))
|
||||
baseURL := strings.TrimSpace(c.Query("base_url"))
|
||||
modelType := types.ModelTypeKnowledgeQA
|
||||
if raw := c.Query("model_type"); raw != "" {
|
||||
if parsed, ok := catalog.ParseModelType(raw); ok {
|
||||
modelType = parsed
|
||||
}
|
||||
}
|
||||
// The preview must resolve against the same inputs the runtime will see,
|
||||
// or it describes a different request than the one the row will make —
|
||||
// Azure is the sharp case: api_version alone decides between the v1 data
|
||||
// plane and the dated deployments path. Forward the vendor's own declared
|
||||
// fields rather than a hardcoded list, so a new vendor needs no change
|
||||
// here. Secret fields are never accepted: this is a GET, and a credential
|
||||
// in a query string lands in access logs and browser history.
|
||||
extra := map[string]string{}
|
||||
for _, key := range []string{catalog.ExtraAPI, catalog.ExtraThinkingControl, catalog.ExtraRemoteModelName} {
|
||||
if v := strings.TrimSpace(c.Query(key)); v != "" {
|
||||
extra[key] = v
|
||||
}
|
||||
}
|
||||
if vendor, ok := catalog.Get(providerID); ok {
|
||||
for _, field := range vendor.ExtraFields {
|
||||
if field.Secret || field.Type == "password" {
|
||||
continue
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query(field.Key)); v != "" {
|
||||
extra[field.Key] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: providerID, Model: modelName, BaseURL: baseURL, ModelType: modelType, Extra: extra,
|
||||
})
|
||||
if err != nil {
|
||||
_ = c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
caps := resolved.Capabilities()
|
||||
data := gin.H{
|
||||
"provider": resolved.Vendor.ID,
|
||||
"api": resolved.API,
|
||||
"remote_model": resolved.RemoteModel,
|
||||
"cataloged": resolved.Cataloged,
|
||||
"model": resolved.Spec,
|
||||
"capabilities": caps,
|
||||
}
|
||||
// base_url and the resolved endpoint are configuration, and with no
|
||||
// base_url in the query they fall back to the vendor default — which a
|
||||
// deployment overlay may have repointed at an internal gateway. Same
|
||||
// gate as the vendor list and as the model rows themselves.
|
||||
if dto.CanViewIntegrationSecrets(ctx) {
|
||||
data["base_url"] = resolved.BaseURL
|
||||
// Only the vendors that compute their own URL report one. Azure is
|
||||
// why this is here: api_version alone decides between the v1 data
|
||||
// plane and the dated deployments path, and nothing else in this
|
||||
// response would show which one the row will call. The protocols
|
||||
// that build their URL inside the client (Anthropic, Gemini
|
||||
// normalise several base-URL shapes) report nothing rather than a
|
||||
// path this endpoint would have to guess.
|
||||
if resolved.Vendor.Endpoint != nil {
|
||||
endpointURL, query := resolved.Vendor.Endpoint(catalog.EndpointRequest{
|
||||
BaseURL: resolved.BaseURL,
|
||||
Model: resolved.RemoteModel,
|
||||
ModelType: modelType,
|
||||
API: resolved.API,
|
||||
Extra: extra,
|
||||
})
|
||||
if endpointURL != "" {
|
||||
data["url"] = api.Endpoint{URL: endpointURL, Query: query}.Resolve("")
|
||||
}
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": data})
|
||||
}
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "github.com/Tencent/WeKnora/internal/models/vendors"
|
||||
)
|
||||
|
||||
// listProvidersAs drives the real handler with one tenant role.
|
||||
func listProvidersAs(t *testing.T, role types.TenantRole) []map[string]any {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/models/providers", nil)
|
||||
ctx := context.WithValue(req.Context(), types.TenantRoleContextKey, role)
|
||||
c.Request = req.WithContext(ctx)
|
||||
|
||||
(&ModelHandler{}).ListModelProviders(c)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if len(body.Data) == 0 {
|
||||
t.Fatalf("expected the vendor catalog to be registered")
|
||||
}
|
||||
return body.Data
|
||||
}
|
||||
|
||||
// A deployment overlay can repoint a vendor at an internal gateway, and the
|
||||
// same URL is stripped from model rows for a viewer (dto.NewModelResponse),
|
||||
// so the vendor list must not hand it out either. Everything else on a vendor
|
||||
// is public product information and stays.
|
||||
func TestListModelProvidersHidesDefaultURLsFromViewers(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
role types.TenantRole
|
||||
wantURL bool
|
||||
}{
|
||||
{"admin configures models, so it needs the prefill", types.TenantRoleAdmin, true},
|
||||
{"viewer cannot configure models", types.TenantRoleViewer, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
providers := listProvidersAs(t, tc.role)
|
||||
sawURL := false
|
||||
for _, p := range providers {
|
||||
if urls, ok := p["defaultUrls"].(map[string]any); ok && len(urls) > 0 {
|
||||
sawURL = true
|
||||
}
|
||||
// The rest of the vendor definition is what the picker needs.
|
||||
if p["value"] == "" || p["label"] == "" {
|
||||
t.Errorf("vendor identity should always be present: %+v", p)
|
||||
}
|
||||
}
|
||||
if sawURL != tc.wantURL {
|
||||
t.Errorf("defaultUrls present = %v, want %v", sawURL, tc.wantURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// resolveAs drives ResolveModelCatalog with a query string.
|
||||
func resolveAs(t *testing.T, query string) map[string]any {
|
||||
t.Helper()
|
||||
return resolveAsRole(t, query, types.TenantRoleAdmin)
|
||||
}
|
||||
|
||||
func resolveAsRole(t *testing.T, query string, role types.TenantRole) map[string]any {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/models/catalog/resolve?"+query, nil)
|
||||
ctx := context.WithValue(req.Context(), types.TenantRoleContextKey, role)
|
||||
c.Request = req.WithContext(ctx)
|
||||
|
||||
(&ModelHandler{}).ResolveModelCatalog(c)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
return body.Data
|
||||
}
|
||||
|
||||
// The editor's "接入诊断" panel must resolve the same request the row will
|
||||
// actually make. Azure is the sharp case: api_version alone decides between
|
||||
// the v1 data plane and the dated deployments path, so a preview that drops
|
||||
// it describes the wrong endpoint.
|
||||
func TestResolveModelCatalogForwardsVendorExtraFields(t *testing.T) {
|
||||
base := "provider=azure_openai&model=gpt-4o&base_url=https://acme.openai.azure.com&model_type=chat"
|
||||
|
||||
withoutVersion := resolveAs(t, base)
|
||||
withVersion := resolveAs(t, base+"&api_version=2025-04-01-preview")
|
||||
|
||||
url1, _ := withoutVersion["url"].(string)
|
||||
url2, _ := withVersion["url"].(string)
|
||||
if url1 == "" || url2 == "" {
|
||||
t.Fatalf("expected a resolved url, got %+v / %+v", withoutVersion, withVersion)
|
||||
}
|
||||
if url1 == url2 {
|
||||
t.Fatalf("api_version must change the resolved endpoint, both were %q", url1)
|
||||
}
|
||||
if !strings.Contains(url1, "/openai/v1") {
|
||||
t.Errorf("no api_version should resolve to the v1 data plane, got %q", url1)
|
||||
}
|
||||
if !strings.Contains(url2, "/openai/deployments/") || !strings.Contains(url2, "2025-04-01-preview") {
|
||||
t.Errorf("an explicit api_version should resolve to the dated path, got %q", url2)
|
||||
}
|
||||
}
|
||||
|
||||
// Omitting base_url makes the resolution fall back to the vendor default,
|
||||
// which a deployment overlay may have repointed at an internal gateway — so
|
||||
// the same gate that hides defaultUrls has to cover this response.
|
||||
func TestResolveModelCatalogHidesEndpointFromViewers(t *testing.T) {
|
||||
query := "provider=azure_openai&model=gpt-4o&base_url=https://acme.openai.azure.com&model_type=chat"
|
||||
|
||||
admin := resolveAsRole(t, query, types.TenantRoleAdmin)
|
||||
if admin["base_url"] == nil || admin["url"] == nil {
|
||||
t.Fatalf("an admin should see the endpoint, got %+v", admin)
|
||||
}
|
||||
|
||||
viewer := resolveAsRole(t, query, types.TenantRoleViewer)
|
||||
if viewer["base_url"] != nil || viewer["url"] != nil {
|
||||
t.Errorf("viewer should not see the endpoint, got %+v", viewer)
|
||||
}
|
||||
// The capability answer itself is not configuration and still resolves.
|
||||
if viewer["api"] == nil || viewer["capabilities"] == nil {
|
||||
t.Errorf("viewer should still get the protocol and capabilities, got %+v", viewer)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// stubUpdateModelService serves one stored model and records the row the
|
||||
// handler tried to persist.
|
||||
type stubUpdateModelService struct {
|
||||
interfaces.ModelService
|
||||
stored *types.Model
|
||||
updated *types.Model
|
||||
}
|
||||
|
||||
func (s *stubUpdateModelService) GetModelByID(context.Context, string) (*types.Model, error) {
|
||||
return s.stored, nil
|
||||
}
|
||||
|
||||
func (s *stubUpdateModelService) UpdateModel(_ context.Context, m *types.Model) error {
|
||||
copied := *m
|
||||
s.updated = &copied
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
secretExtraProvider = "handler-secret-extra-vendor"
|
||||
// plainExtraProvider declares no secret extra field at all — the vendor a
|
||||
// row is switched *to* in the provider-change tests below.
|
||||
plainExtraProvider = "handler-plain-extra-vendor"
|
||||
)
|
||||
|
||||
func registerSecretExtraVendor(t *testing.T) {
|
||||
t.Helper()
|
||||
catalog.Register(&catalog.Vendor{
|
||||
ID: secretExtraProvider,
|
||||
Name: "Secret Extra Vendor",
|
||||
ModelTypes: []types.ModelType{types.ModelTypeRerank},
|
||||
ExtraFields: []catalog.ExtraField{
|
||||
{Key: "secret_key", Label: "Secret Key", Type: "password", Secret: true},
|
||||
{Key: "region", Label: "Region", Type: "string"},
|
||||
},
|
||||
})
|
||||
catalog.Register(&catalog.Vendor{
|
||||
ID: plainExtraProvider,
|
||||
Name: "Plain Extra Vendor",
|
||||
ModelTypes: []types.ModelType{types.ModelTypeRerank},
|
||||
})
|
||||
}
|
||||
|
||||
func storedSecretExtraModel() *types.Model {
|
||||
return &types.Model{
|
||||
ID: "m-rerank",
|
||||
Name: "rerank-v1",
|
||||
Type: types.ModelTypeRerank,
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: secretExtraProvider,
|
||||
APIKey: "AKID-public-id",
|
||||
ExtraConfig: map[string]string{
|
||||
"secret_key": "cam-secret-stored",
|
||||
"region": "ap-guangzhou",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// putModelAs drives PUT /models/{id} against the stored rerank row with the
|
||||
// given provider and extra_config, as a workspace admin (the only role whose
|
||||
// response carries integration detail at all). It returns the row the handler
|
||||
// persisted and the response body.
|
||||
func putModelAs(t *testing.T, provider string, extraConfig map[string]string) (*types.Model, string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := &stubUpdateModelService{stored: storedSecretExtraModel()}
|
||||
h := NewModelHandler(svc)
|
||||
|
||||
body, err := json.Marshal(UpdateModelRequest{
|
||||
Name: "rerank-v1",
|
||||
Type: types.ModelTypeRerank,
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
Provider: provider,
|
||||
ExtraConfig: extraConfig,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPut, "/api/v1/models/m-rerank", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(c.Request.Context(), types.TenantRoleContextKey, types.TenantRoleAdmin),
|
||||
)
|
||||
c.Params = gin.Params{{Key: "id", Value: "m-rerank"}}
|
||||
|
||||
h.UpdateModel(c)
|
||||
require.Empty(t, c.Errors.Errors(), "handler reported an error")
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.NotNil(t, svc.updated, "UpdateModel was never called")
|
||||
return svc.updated, w.Body.String()
|
||||
}
|
||||
|
||||
// putModel keeps the row on its own vendor, the ordinary edit.
|
||||
func putModel(t *testing.T, extraConfig map[string]string) *types.Model {
|
||||
t.Helper()
|
||||
updated, _ := putModelAs(t, secretExtraProvider, extraConfig)
|
||||
return updated
|
||||
}
|
||||
|
||||
// The frontend always sends extra_config for remote rows, but GET redacts
|
||||
// the vendor's secret fields — so the map it sends back carries no
|
||||
// secret_key. Saving must not wipe the stored one.
|
||||
func TestUpdateModel_KeepsStoredSecretExtraWhenRequestOmitsIt(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
updated := putModel(t, map[string]string{"region": "ap-beijing"})
|
||||
assert.Equal(t, "cam-secret-stored", updated.Parameters.ExtraConfig["secret_key"])
|
||||
assert.Equal(t, "ap-beijing", updated.Parameters.ExtraConfig["region"],
|
||||
"the edit the user actually made still lands")
|
||||
}
|
||||
|
||||
func TestUpdateModel_KeepsStoredSecretExtraWhenRequestSendsBlank(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
updated := putModel(t, map[string]string{"secret_key": "", "region": "ap-guangzhou"})
|
||||
assert.Equal(t, "cam-secret-stored", updated.Parameters.ExtraConfig["secret_key"])
|
||||
}
|
||||
|
||||
func TestUpdateModel_ReplacesSecretExtraWhenRequestSendsNewValue(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
updated := putModel(t, map[string]string{"secret_key": "cam-secret-rotated", "region": "ap-guangzhou"})
|
||||
assert.Equal(t, "cam-secret-rotated", updated.Parameters.ExtraConfig["secret_key"])
|
||||
}
|
||||
|
||||
// The PUT response goes through the same redaction as GET.
|
||||
func TestUpdateModel_ResponseDoesNotEchoSecretExtra(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
_, body := putModelAs(t, secretExtraProvider, map[string]string{"secret_key": "cam-secret-rotated"})
|
||||
assert.NotContains(t, body, "cam-secret-rotated")
|
||||
assert.Contains(t, body, `"secret_key":{"configured":true}`)
|
||||
}
|
||||
|
||||
// Switching the row to a vendor that declares no secret field used to write
|
||||
// the previous vendor's CAM/IAM key back into the row — the merge looked at
|
||||
// the stored provider while the redactor looked at the new one, so the key
|
||||
// came back in plaintext in this response and in every later GET.
|
||||
func TestUpdateModel_ProviderChangeDoesNotEchoOldSecretExtra(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
updated, body := putModelAs(t, plainExtraProvider, map[string]string{"api": "openai_completions"})
|
||||
|
||||
assert.NotContains(t, updated.Parameters.ExtraConfig, "secret_key",
|
||||
"the previous vendor's credential must not survive the move")
|
||||
assert.Equal(t, "openai_completions", updated.Parameters.ExtraConfig["api"],
|
||||
"the edit the user actually made still lands")
|
||||
assert.NotContains(t, body, "cam-secret-stored")
|
||||
}
|
||||
|
||||
// Even a row that somehow still carries the key — hand-edited provider, or a
|
||||
// provider that was never stored — must not have it echoed: redaction asks
|
||||
// every registered vendor, not just this row's.
|
||||
func TestUpdateModel_ResponseRedactsSecretExtraOfAnotherVendor(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
_, body := putModelAs(t, plainExtraProvider, map[string]string{"secret_key": "cam-secret-typed"})
|
||||
assert.NotContains(t, body, "cam-secret-typed")
|
||||
assert.Contains(t, body, `"secret_key":{"configured":true}`)
|
||||
}
|
||||
|
||||
// A body that names no vendor at all is not a vendor change: it carries no
|
||||
// new integration identity, and the stored secret still has to survive it.
|
||||
func TestUpdateModel_KeepsSecretExtraWhenRequestNamesNoProvider(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
updated, _ := putModelAs(t, "", map[string]string{"region": "ap-beijing"})
|
||||
assert.Equal(t, "cam-secret-stored", updated.Parameters.ExtraConfig["secret_key"])
|
||||
}
|
||||
|
||||
// The "test connection" path must see the secret the UI never received,
|
||||
// otherwise verifying an existing rerank row fails with a missing key.
|
||||
func TestFillSecretsFromStoredModel_FillsRedactedSecretExtra(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
stored := storedSecretExtraModel()
|
||||
h := &InitializationHandler{
|
||||
modelService: &stubFillSecretsModelService{
|
||||
getModelByID: func(context.Context, string) (*types.Model, error) { return stored, nil },
|
||||
},
|
||||
}
|
||||
req := &ModelTestRequest{
|
||||
ModelID: "m-rerank",
|
||||
Provider: secretExtraProvider,
|
||||
APIKey: "AKID-typed-by-user",
|
||||
AppSecret: "unused",
|
||||
ExtraConfig: map[string]string{"region": "ap-beijing"},
|
||||
}
|
||||
|
||||
h.fillSecretsFromStoredModel(context.Background(), req)
|
||||
|
||||
assert.Equal(t, "cam-secret-stored", req.ExtraConfig["secret_key"])
|
||||
assert.Equal(t, "ap-beijing", req.ExtraConfig["region"])
|
||||
assert.Equal(t, "AKID-typed-by-user", req.APIKey, "a value the user typed always wins")
|
||||
}
|
||||
|
||||
// Testing the row against a different vendor must not reach for the stored
|
||||
// credential: it authenticates the integration being replaced.
|
||||
func TestFillSecretsFromStoredModel_SkipsSecretExtraOfAnotherVendor(t *testing.T) {
|
||||
registerSecretExtraVendor(t)
|
||||
stored := storedSecretExtraModel()
|
||||
h := &InitializationHandler{
|
||||
modelService: &stubFillSecretsModelService{
|
||||
getModelByID: func(context.Context, string) (*types.Model, error) { return stored, nil },
|
||||
},
|
||||
}
|
||||
req := &ModelTestRequest{
|
||||
ModelID: "m-rerank",
|
||||
Provider: plainExtraProvider,
|
||||
ExtraConfig: map[string]string{"api": "openai_completions"},
|
||||
}
|
||||
|
||||
h.fillSecretsFromStoredModel(context.Background(), req)
|
||||
|
||||
assert.NotContains(t, req.ExtraConfig, "secret_key")
|
||||
assert.Equal(t, "AKID-public-id", req.APIKey, "the api_key still comes from the stored row")
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
|
@ -47,6 +48,26 @@ func TestRedactedDebugConfig(t *testing.T) {
|
|||
assert.Equal(t, "[REDACTED]", got["access_token"])
|
||||
}
|
||||
|
||||
// The debug preview asks the catalog, not only the key name: a vendor whose
|
||||
// credential field is called something the name heuristic cannot guess is
|
||||
// still redacted, because the vendor declared it Secret.
|
||||
func TestRedactedDebugConfigUsesVendorDeclaration(t *testing.T) {
|
||||
catalog.Register(&catalog.Vendor{
|
||||
ID: "handler-debug-redaction-vendor",
|
||||
Name: "Debug Redaction Vendor",
|
||||
ModelTypes: []types.ModelType{types.ModelTypeRerank},
|
||||
ExtraFields: []catalog.ExtraField{
|
||||
{Key: "signing_material", Label: "Signing Material", Secret: true},
|
||||
},
|
||||
})
|
||||
got := redactedDebugConfig(map[string]string{
|
||||
"signing_material": "do-not-leak",
|
||||
"region": "ap-guangzhou",
|
||||
})
|
||||
assert.Equal(t, "[REDACTED]", got["signing_material"])
|
||||
assert.Equal(t, "ap-guangzhou", got["region"])
|
||||
}
|
||||
|
||||
func TestConsumeModelDebugChatStream(t *testing.T) {
|
||||
stream := make(chan types.StreamResponse, 5)
|
||||
stream <- types.StreamResponse{ResponseType: types.ResponseTypeThinking, Content: "reason "}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
|
@ -175,7 +176,17 @@ func (r *Registry) DecodeResponse(response *types.ChatResponse) {
|
|||
return
|
||||
}
|
||||
response.Content = r.DecodeOutputText(response.Content)
|
||||
reasoningBefore := response.ReasoningContent
|
||||
response.ReasoningContent = r.DecodeOutputText(response.ReasoningContent)
|
||||
if response.ReasoningContent != reasoningBefore &&
|
||||
api.SignatureFor(api.APIAnthropicMessages, response.ReasoningSignature) != "" {
|
||||
// Same reason and same protocol limit as dropStaleReasoningSignature:
|
||||
// the decoded text is no longer what Claude signed, and this response
|
||||
// is what lands on the agent step. Anthropic turns replay from
|
||||
// ReasoningMetadata, which decoding never touches, so this only
|
||||
// affects turns stored before that metadata existed.
|
||||
response.ReasoningSignature = ""
|
||||
}
|
||||
r.DecodeToolCalls(response.ToolCalls)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -395,9 +395,10 @@ func TestModelToolResultProtectsSummarySlugBeforeSourceCompaction(t *testing.T)
|
|||
registry.RegisterDocument(knowledgeID)
|
||||
registry.RegisterKnowledgeBase(kbID)
|
||||
|
||||
got := registry.ModelToolResult(&types.ToolResult{Success: true, Output: "<knowledge_base_id>" + kbID + "</knowledge_base_id>\n" +
|
||||
"<link>[[summary/" + knowledgeID + "|Summary]]</link>\n" +
|
||||
"<knowledge_id>" + knowledgeID + "</knowledge_id>",
|
||||
got := registry.ModelToolResult(&types.ToolResult{
|
||||
Success: true, Output: "<knowledge_base_id>" + kbID + "</knowledge_base_id>\n" +
|
||||
"<link>[[summary/" + knowledgeID + "|Summary]]</link>\n" +
|
||||
"<knowledge_id>" + knowledgeID + "</knowledge_id>",
|
||||
})
|
||||
require.Contains(t, got, "[[res://0001|Summary]]")
|
||||
require.Contains(t, got, "<knowledge_base_id>b1</knowledge_base_id>")
|
||||
|
|
@ -679,3 +680,27 @@ func TestModelOutputReportsSearchModeAndFallbacks(t *testing.T) {
|
|||
}})
|
||||
require.Contains(t, legacy, `mode="semantic"`, "legacy knowledge_search payloads were semantic")
|
||||
}
|
||||
|
||||
func TestDecodeResponseDropsSignatureWhenReasoningIsDecoded(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
// The handle only exists after the outbound half assigned it.
|
||||
registry.EncodeMessages([]chat.Message{{Role: "assistant", Content: ref}})
|
||||
|
||||
decoded := &types.ChatResponse{
|
||||
Content: "done",
|
||||
ReasoningContent: "read res://0001",
|
||||
ReasoningSignature: "anthropic-messages:sig",
|
||||
}
|
||||
registry.DecodeResponse(decoded)
|
||||
require.Equal(t, "read "+ref, decoded.ReasoningContent)
|
||||
require.Empty(t, decoded.ReasoningSignature, "decoded text is no longer what the provider signed")
|
||||
|
||||
untouched := &types.ChatResponse{
|
||||
Content: "done",
|
||||
ReasoningContent: "no handles here",
|
||||
ReasoningSignature: "anthropic-messages:sig",
|
||||
}
|
||||
registry.DecodeResponse(untouched)
|
||||
require.Equal(t, "anthropic-messages:sig", untouched.ReasoningSignature)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
|
@ -99,7 +100,9 @@ func (r *resourceRegistry) EncodeMessages(messages []chat.Message) []chat.Messag
|
|||
copy(encoded, messages)
|
||||
for i := range encoded {
|
||||
encoded[i].Content = r.EncodeText(encoded[i].Content)
|
||||
reasoningBefore := encoded[i].ReasoningContent
|
||||
encoded[i].ReasoningContent = r.EncodeText(encoded[i].ReasoningContent)
|
||||
dropStaleReasoningSignature(&encoded[i], reasoningBefore)
|
||||
if len(encoded[i].MultiContent) > 0 {
|
||||
encoded[i].MultiContent = append([]chat.MessageContentPart(nil), encoded[i].MultiContent...)
|
||||
for j := range encoded[i].MultiContent {
|
||||
|
|
@ -155,3 +158,27 @@ func (r *resourceRegistry) handles() []string {
|
|||
}
|
||||
return handles
|
||||
}
|
||||
|
||||
// dropStaleReasoningSignature clears a reasoning signature this registry just
|
||||
// invalidated by rewriting the text it covers.
|
||||
//
|
||||
// It applies only to Anthropic. Claude signs the exact thinking text, so a
|
||||
// block replayed with rewritten text and its original signature fails
|
||||
// verification. Gemini is deliberately excluded: its thought signatures ride
|
||||
// on the answer text and on each tool call's metadata, neither of which this
|
||||
// registry touches, so dropping one there would throw away a signature
|
||||
// Gemini 3 requires back.
|
||||
//
|
||||
// This is a safety net for assistant turns stored before
|
||||
// anthropicmessages.MetadataThinkingBlocks existed. Current turns replay from
|
||||
// that metadata, which carries the signed bytes verbatim and is opaque to
|
||||
// every rewrite here, so they do not depend on this at all.
|
||||
func dropStaleReasoningSignature(msg *chat.Message, before string) {
|
||||
if msg.ReasoningContent == before {
|
||||
return
|
||||
}
|
||||
if api.SignatureFor(api.APIAnthropicMessages, msg.ReasoningSignature) == "" {
|
||||
return
|
||||
}
|
||||
msg.ReasoningSignature = ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
|
|
@ -108,3 +109,69 @@ func TestResourceVersionsStayImmutableAcrossRounds(t *testing.T) {
|
|||
require.Equal(t, "res://0001", nextRequest.EncodeText(latest))
|
||||
require.Equal(t, old, r.DecodeText("res://0003"))
|
||||
}
|
||||
|
||||
func TestEncodeMessagesDropsSignatureOnlyWhenReasoningIsRewritten(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "I looked at " + ref,
|
||||
ReasoningSignature: "anthropic-messages:sig-1",
|
||||
},
|
||||
{
|
||||
Role: "assistant",
|
||||
Content: "see " + ref,
|
||||
ReasoningContent: "plain thought with nothing to encode",
|
||||
ReasoningSignature: "anthropic-messages:sig-2",
|
||||
},
|
||||
}
|
||||
|
||||
encoded := r.EncodeMessages(messages)
|
||||
|
||||
// The first message's thinking text was rewritten, so its signature no
|
||||
// longer covers what would go on the wire.
|
||||
require.Equal(t, "I looked at res://0001", encoded[0].ReasoningContent)
|
||||
require.Empty(t, encoded[0].ReasoningSignature)
|
||||
// The second one's thinking text is untouched (only Content changed), so
|
||||
// the block stays replayable.
|
||||
require.Equal(t, "plain thought with nothing to encode", encoded[1].ReasoningContent)
|
||||
require.Equal(t, "anthropic-messages:sig-2", encoded[1].ReasoningSignature)
|
||||
// Callers' own slice is never mutated.
|
||||
require.Equal(t, "anthropic-messages:sig-1", messages[0].ReasoningSignature)
|
||||
}
|
||||
|
||||
func TestEncodeMessagesKeepsGeminiSignatureWhenReasoningIsRewritten(t *testing.T) {
|
||||
r := newResourceRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
messages := []chat.Message{{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "I looked at " + ref,
|
||||
// Gemini replays this signature on the answer text and on each tool
|
||||
// call's own metadata; it never replays the reasoning text, so a
|
||||
// rewrite here does not invalidate it.
|
||||
ReasoningSignature: "google-generative-ai:thought-sig",
|
||||
}}
|
||||
|
||||
encoded := r.EncodeMessages(messages)
|
||||
|
||||
require.Equal(t, "I looked at res://0001", encoded[0].ReasoningContent)
|
||||
require.Equal(t, "google-generative-ai:thought-sig", encoded[0].ReasoningSignature)
|
||||
}
|
||||
|
||||
func TestDecodeResponseKeepsGeminiSignature(t *testing.T) {
|
||||
registry := NewRegistry(true)
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
registry.EncodeMessages([]chat.Message{{Role: "assistant", Content: ref}})
|
||||
|
||||
decoded := &types.ChatResponse{
|
||||
Content: "done",
|
||||
ReasoningContent: "read res://0001",
|
||||
ReasoningSignature: "google-generative-ai:thought-sig",
|
||||
}
|
||||
registry.DecodeResponse(decoded)
|
||||
require.Equal(t, "read "+ref, decoded.ReasoningContent)
|
||||
require.Equal(t, "google-generative-ai:thought-sig", decoded.ReasoningSignature)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -298,7 +298,9 @@ func (r *sourceRegistry) EncodeMessagesWithPolicies(
|
|||
processToolResult := out[i].Role == "tool" && (resultPolicy == nil || resultPolicy(out[i].Name))
|
||||
if out[i].Role == "assistant" || processToolResult {
|
||||
out[i].Content = r.CompactPublicCitations(out[i].Content, false)
|
||||
reasoningBefore := out[i].ReasoningContent
|
||||
out[i].ReasoningContent = r.CompactPublicCitations(out[i].ReasoningContent, false)
|
||||
dropStaleReasoningSignature(&out[i], reasoningBefore)
|
||||
}
|
||||
if len(out[i].MultiContent) > 0 {
|
||||
out[i].MultiContent = append([]chat.MessageContentPart(nil), out[i].MultiContent...)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,646 @@
|
|||
package anthropicmessages
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {
|
||||
t.Helper()
|
||||
cfg := Config{
|
||||
Endpoint: api.Endpoint{
|
||||
BaseURL: baseURL, Model: "claude-sonnet-4-5", ModelID: "m1",
|
||||
Auth: api.HeaderAuth("x-api-key", "test-key"),
|
||||
Headers: map[string]string{"anthropic-beta": "test-beta"},
|
||||
},
|
||||
Settings: catalog.DefaultAnthropicMessages(),
|
||||
ThinkingLevels: api.ThinkingLevelMap{},
|
||||
Reasoning: true,
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&cfg)
|
||||
}
|
||||
return New(cfg)
|
||||
}
|
||||
|
||||
func bodyJSON(t *testing.T, c *Client, msgs []api.Message, opts *api.Options, stream bool) map[string]any {
|
||||
t.Helper()
|
||||
body, err := c.BuildRequestBody(msgs, opts, stream)
|
||||
require.NoError(t, err)
|
||||
data, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &out))
|
||||
return out
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_BudgetThinkingAndTools(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msgs := []api.Message{
|
||||
{Role: "system", Content: "You are helpful."},
|
||||
{Role: "user", Content: "Hi"},
|
||||
{
|
||||
Role: "assistant", Content: "", ReasoningContent: "let me think",
|
||||
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "sig1"),
|
||||
ToolCalls: []api.ToolCall{{
|
||||
ID: "toolu_1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"x"}`},
|
||||
}},
|
||||
},
|
||||
{Role: "tool", ToolCallID: "toolu_1", Content: "result"},
|
||||
}
|
||||
opts := &api.Options{
|
||||
MaxTokens: 2000, Temperature: 0.3, ReasoningEffort: api.ReasoningHigh,
|
||||
Tools: []api.Tool{{Type: "function", Function: api.FunctionDef{
|
||||
Name: "search", Description: "d", Parameters: json.RawMessage(`{"type":"object"}`),
|
||||
}}},
|
||||
}
|
||||
out := bodyJSON(t, c, msgs, opts, true)
|
||||
|
||||
assert.Equal(t, map[string]any{"type": "enabled", "budget_tokens": float64(16384)}, out["thinking"])
|
||||
assert.Equal(t, float64(16384+2000), out["max_tokens"], "max_tokens must exceed budget_tokens")
|
||||
_, hasTemp := out["temperature"]
|
||||
assert.False(t, hasTemp, "temperature is rejected alongside thinking")
|
||||
assert.Equal(t, true, out["stream"])
|
||||
|
||||
system := out["system"].([]any)[0].(map[string]any)
|
||||
assert.Equal(t, "You are helpful.", system["text"])
|
||||
assert.Equal(t, "ephemeral", system["cache_control"].(map[string]any)["type"])
|
||||
|
||||
messages := out["messages"].([]any)
|
||||
require.Len(t, messages, 3)
|
||||
assistant := messages[1].(map[string]any)
|
||||
blocks := assistant["content"].([]any)
|
||||
assert.Equal(t, "thinking", blocks[0].(map[string]any)["type"])
|
||||
assert.Equal(t, "sig1", blocks[0].(map[string]any)["signature"])
|
||||
assert.Equal(t, "tool_use", blocks[1].(map[string]any)["type"])
|
||||
toolResult := messages[2].(map[string]any)["content"].([]any)[0].(map[string]any)
|
||||
assert.Equal(t, "tool_result", toolResult["type"])
|
||||
assert.Equal(t, "toolu_1", toolResult["tool_use_id"])
|
||||
assert.NotNil(t, toolResult["cache_control"], "last conversation block carries the breakpoint")
|
||||
|
||||
tools := out["tools"].([]any)
|
||||
assert.NotNil(t, tools[0].(map[string]any)["cache_control"])
|
||||
assert.Equal(t, map[string]any{"type": "auto"}, out["tool_choice"])
|
||||
|
||||
beta := c.betaHeader(c.planThinking(opts), opts, "test-beta")
|
||||
assert.Equal(t, "interleaved-thinking-2025-05-14,test-beta", beta)
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_AdaptiveEffort(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", func(cfg *Config) {
|
||||
cfg.Settings.ThinkingMode = catalog.AnthropicThinkingAdaptive
|
||||
cfg.Settings.SupportsEffort = true
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningXHigh: api.StringPtr("max")}
|
||||
})
|
||||
out := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningXHigh}, false)
|
||||
assert.Equal(t, map[string]any{"type": "adaptive"}, out["thinking"])
|
||||
assert.Equal(t, map[string]any{"effort": "max"}, out["output_config"])
|
||||
assert.Equal(t, float64(4096), out["max_tokens"])
|
||||
|
||||
off := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningOff}, false)
|
||||
assert.Equal(t, map[string]any{"type": "disabled"}, off["thinking"])
|
||||
_, hasEffort := off["output_config"]
|
||||
assert.False(t, hasEffort)
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_NoThinkingKeepsSampling(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
out := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{Temperature: 0.2, TopP: 0.9, MaxTokens: 7, CacheRetention: api.CacheRetentionNone}, false)
|
||||
assert.Equal(t, 0.2, out["temperature"])
|
||||
_, hasTopP := out["top_p"]
|
||||
assert.False(t, hasTopP, "temperature wins over top_p")
|
||||
assert.Equal(t, float64(7), out["max_tokens"])
|
||||
assert.Equal(t, "Hi", out["messages"].([]any)[0].(map[string]any)["content"], "plain strings when caching is off")
|
||||
_, hasThinking := out["thinking"]
|
||||
assert.False(t, hasThinking)
|
||||
}
|
||||
|
||||
func TestURLResolution(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"https://api.anthropic.com": "https://api.anthropic.com/v1/messages",
|
||||
"https://api.anthropic.com/v1": "https://api.anthropic.com/v1/messages",
|
||||
"https://api.minimaxi.com/anthropic": "https://api.minimaxi.com/anthropic/v1/messages",
|
||||
"https://open.bigmodel.cn/api/anthropic": "https://open.bigmodel.cn/api/anthropic/v1/messages",
|
||||
"https://proxy.example.com/v1/messages": "https://proxy.example.com/v1/messages",
|
||||
}
|
||||
for base, want := range cases {
|
||||
c := newClient(t, base, nil)
|
||||
assert.Equal(t, want, c.URL(), base)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChat_NonStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var captured http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "/v1/messages", r.URL.Path)
|
||||
captured = r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":"msg_1","type":"message","role":"assistant",
|
||||
"content":[{"type":"thinking","thinking":"hmm","signature":"sig"},{"type":"text","text":"hello"},
|
||||
{"type":"tool_use","id":"toolu_1","name":"search","input":{"q":"x"}}],
|
||||
"stop_reason":"tool_use",
|
||||
"usage":{"input_tokens":24,"output_tokens":2,
|
||||
"cache_creation_input_tokens":100,"cache_read_input_tokens":900}
|
||||
}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, &api.Options{MaxTokens: 7})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "test-key", captured.Get("x-api-key"))
|
||||
assert.Equal(t, "2023-06-01", captured.Get("anthropic-version"))
|
||||
assert.Equal(t, "test-beta", captured.Get("anthropic-beta"))
|
||||
assert.Equal(t, "hello", resp.Content)
|
||||
assert.Equal(t, "hmm", resp.ReasoningContent)
|
||||
assert.Equal(t, "anthropic-messages:sig", resp.ReasoningSignature)
|
||||
assert.Equal(t, "tool_calls", resp.FinishReason)
|
||||
require.Len(t, resp.ToolCalls, 1)
|
||||
assert.Equal(t, `{"q":"x"}`, resp.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, 1024, resp.Usage.PromptTokens)
|
||||
assert.Equal(t, 900, resp.Usage.CacheReadTokens)
|
||||
assert.Equal(t, 100, resp.Usage.CacheWriteTokens)
|
||||
assert.Equal(t, types.PromptCacheStatusHit, resp.Usage.CacheStatus)
|
||||
}
|
||||
|
||||
func TestChat_HTTPError(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":{"type":"invalid_request_error","message":"bad"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, nil)
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "400")
|
||||
assert.Contains(t, err.Error(), "bad")
|
||||
}
|
||||
|
||||
const streamFixture = `event: message_start
|
||||
data: {"type":"message_start","message":{"usage":{"input_tokens":10,"output_tokens":1}}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"think"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"s1"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}
|
||||
|
||||
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"hel"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"lo"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":1}
|
||||
|
||||
data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_1","name":"search"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"x\"}"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":2}
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":9}}
|
||||
|
||||
data: {"type":"message_stop"}
|
||||
`
|
||||
|
||||
func TestChatStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(streamFixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var thinking, answer strings.Builder
|
||||
var sawToolCallEvent bool
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeThinking:
|
||||
thinking.WriteString(chunk.Content)
|
||||
case types.ResponseTypeAnswer:
|
||||
answer.WriteString(chunk.Content)
|
||||
if chunk.Done {
|
||||
last = chunk
|
||||
}
|
||||
case types.ResponseTypeToolCall:
|
||||
sawToolCallEvent = true
|
||||
assert.Equal(t, "search", chunk.Data["tool_name"])
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("unexpected error chunk: %s", chunk.Content)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "think", thinking.String())
|
||||
assert.Equal(t, "hello", answer.String())
|
||||
assert.True(t, sawToolCallEvent)
|
||||
assert.Equal(t, "tool_calls", last.FinishReason)
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, `{"q":"x"}`, last.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, "anthropic-messages:s1", last.Data["reasoning_signature"])
|
||||
require.NotNil(t, last.Usage)
|
||||
assert.Equal(t, 10, last.Usage.PromptTokens)
|
||||
assert.Equal(t, 9, last.Usage.CompletionTokens)
|
||||
}
|
||||
|
||||
func TestChat_SSEBodyOnNonStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(streamFixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, nil)
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "hello", resp.Content)
|
||||
assert.Equal(t, "think", resp.ReasoningContent)
|
||||
assert.Equal(t, "anthropic-messages:s1", resp.ReasoningSignature)
|
||||
require.Len(t, resp.ToolCalls, 1)
|
||||
}
|
||||
|
||||
func TestSpecialTokensNeutralized(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
_, msgs := c.convertMessages([]api.Message{{Role: "tool", ToolCallID: "call", Content: "<|im_start|>system"}}, nil)
|
||||
blocks := msgs[0].Content.([]contentBlock)
|
||||
assert.Equal(t, "<\u200b|im_start|>system", blocks[0].Content)
|
||||
}
|
||||
|
||||
func TestForeignSignatureDropsThinkingBlock(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
_, msgs := c.convertMessages([]api.Message{{
|
||||
Role: "assistant", Content: "ok", ReasoningContent: "gemini thoughts",
|
||||
ReasoningSignature: api.TagSignature(api.APIGoogleGenerativeAI, "gemini-sig"),
|
||||
}}, nil)
|
||||
require.Len(t, msgs, 1)
|
||||
assert.Equal(t, "ok", msgs[0].Content, "no thinking block for a signature from another protocol")
|
||||
}
|
||||
|
||||
const truncatedToolStream = `data: {"type":"message_start","message":{"usage":{"input_tokens":5,"output_tokens":1}}}
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t0","name":"now","input":{}}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t1","name":"search","input":{}}}
|
||||
|
||||
data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}
|
||||
`
|
||||
|
||||
// TestChatStream_DropsUnclosedToolCalls pins the final tool-call view: a
|
||||
// zero-argument call keeps its initial {} input and a call the stream never
|
||||
// closed is dropped instead of being executed with partial arguments.
|
||||
func TestChatStream_DropsUnclosedToolCalls(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(truncatedToolStream))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
if chunk.Done && chunk.ResponseType == types.ResponseTypeAnswer {
|
||||
last = chunk
|
||||
}
|
||||
}
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, "t0", last.ToolCalls[0].ID)
|
||||
assert.Equal(t, "{}", last.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, types.FinishReasonIncomplete, last.FinishReason)
|
||||
}
|
||||
|
||||
const zeroArgToolStream = `data: {"type":"message_start","message":{"usage":{"input_tokens":5,"output_tokens":1}}}
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t0","name":"now","input":{}}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":7}}
|
||||
|
||||
data: {"type":"message_stop"}
|
||||
`
|
||||
|
||||
// A tool call that never receives an input_json_delta (an argument-less tool)
|
||||
// must still announce itself: the old Anthropic implementation emitted the
|
||||
// ResponseTypeToolCall marker straight from content_block_start, and the UI
|
||||
// relies on it to show the call as it starts.
|
||||
func TestChatStream_ZeroArgumentToolStillAnnouncesToolCall(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(zeroArgToolStream))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var marker types.StreamResponse
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeToolCall:
|
||||
marker = chunk
|
||||
case types.ResponseTypeAnswer:
|
||||
if chunk.Done {
|
||||
last = chunk
|
||||
}
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("unexpected error chunk: %s", chunk.Content)
|
||||
}
|
||||
}
|
||||
require.NotNil(t, marker.Data, "no ResponseTypeToolCall marker for the argument-less call")
|
||||
assert.Equal(t, "now", marker.Data["tool_name"])
|
||||
assert.Equal(t, "t0", marker.Data["tool_call_id"])
|
||||
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, "{}", last.ToolCalls[0].Function.Arguments, "arguments unchanged by the replay")
|
||||
assert.Equal(t, "tool_calls", last.FinishReason)
|
||||
}
|
||||
|
||||
// message_delta carries only cumulative output_tokens; the input counters from
|
||||
// message_start must survive the merge instead of being reset to zero.
|
||||
func TestChatStream_MessageDeltaKeepsInputTokens(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
const fixture = `data: {"type":"message_start","message":{"usage":` +
|
||||
`{"input_tokens":100,"cache_read_input_tokens":40,"cache_creation_input_tokens":10,"output_tokens":1}}}
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":55}}
|
||||
|
||||
data: {"type":"message_stop"}
|
||||
`
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(fixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
var usage *types.TokenUsage
|
||||
for chunk := range ch {
|
||||
if chunk.Usage != nil {
|
||||
usage = chunk.Usage
|
||||
}
|
||||
}
|
||||
require.NotNil(t, usage)
|
||||
assert.Equal(t, 150, usage.PromptTokens, "input + cache read + cache write from message_start")
|
||||
assert.Equal(t, 55, usage.CompletionTokens, "cumulative output tokens from message_delta")
|
||||
assert.Equal(t, 40, usage.CacheReadTokens)
|
||||
assert.Equal(t, 10, usage.CacheWriteTokens)
|
||||
assert.True(t, usage.CacheReported)
|
||||
}
|
||||
|
||||
// "messages" is required and must be an array. A conversation that produced no
|
||||
// turns (only system prompts) used to marshal a nil slice as null.
|
||||
func TestBuildRequestBody_MessagesNeverNull(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
for _, msgs := range [][]api.Message{nil, {{Role: "system", Content: "be brief"}}} {
|
||||
body, err := c.BuildRequestBody(msgs, nil, false)
|
||||
require.NoError(t, err)
|
||||
data, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(data), `"messages":[]`)
|
||||
assert.NotContains(t, string(data), `"messages":null`)
|
||||
}
|
||||
}
|
||||
|
||||
// anthropic-version is mandatory on every request; an empty header is a 400.
|
||||
func TestSend_DefaultsAnthropicVersion(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var got string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got = r.Header.Get("anthropic-version")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, func(cfg *Config) { cfg.Settings.Version = "" })
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, defaultAnthropicVersion, got)
|
||||
}
|
||||
|
||||
// storedThinking renders what the client persists on an assistant turn, so
|
||||
// the replay tests start from the same bytes production would have stored.
|
||||
func storedThinking(t *testing.T, blocks ...thinkingBlock) types.ProviderMetadata {
|
||||
t.Helper()
|
||||
raw := thinkingBlocksMetadata(blocks)
|
||||
require.NotNil(t, raw)
|
||||
return types.ProviderMetadata{MetadataThinkingBlocks: raw}
|
||||
}
|
||||
|
||||
func assistantContent(t *testing.T, body map[string]any) []any {
|
||||
t.Helper()
|
||||
messages, ok := body["messages"].([]any)
|
||||
require.True(t, ok, "messages should be a list")
|
||||
require.NotEmpty(t, messages)
|
||||
first, ok := messages[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "assistant", first["role"])
|
||||
blocks, ok := first["content"].([]any)
|
||||
require.True(t, ok, "assistant content should be a block list")
|
||||
return blocks
|
||||
}
|
||||
|
||||
func blockTypes(blocks []any) []string {
|
||||
out := make([]string, 0, len(blocks))
|
||||
for _, b := range blocks {
|
||||
if m, ok := b.(map[string]any); ok {
|
||||
out = append(out, m["type"].(string))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestInterleavedThinkingReplaysEveryBlockWithItsOwnSignature(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
// The concatenation readers see; deliberately different from the
|
||||
// signed text below so a replay built from it would be detectable.
|
||||
ReasoningContent: "first thoughtsecond thought",
|
||||
ReasoningMetadata: storedThinking(t,
|
||||
newThinkingBlock("first thought", "sig-1"),
|
||||
newThinkingBlock("second thought", "sig-2"),
|
||||
),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"a"}`}},
|
||||
{ID: "t2", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"b"}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "thinking", "tool_use", "tool_use"}, blockTypes(blocks))
|
||||
|
||||
first := blocks[0].(map[string]any)
|
||||
second := blocks[1].(map[string]any)
|
||||
assert.Equal(t, "first thought", first["thinking"])
|
||||
assert.Equal(t, "sig-1", first["signature"])
|
||||
assert.Equal(t, "second thought", second["thinking"])
|
||||
assert.Equal(t, "sig-2", second["signature"])
|
||||
}
|
||||
|
||||
func TestReplayKeepsSignedTextWhenReasoningContentWasRewritten(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// internal/modelcontext rewrites ReasoningContent (resource handles,
|
||||
// citation compaction) and clears the now-stale signature. The signed
|
||||
// bytes survive in the metadata, so the turn still replays — which
|
||||
// matters because dropping the thinking block while keeping tool_use is
|
||||
// a 400 from Claude, not a degradation.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningContent: "I read res://0001",
|
||||
ReasoningMetadata: storedThinking(t, newThinkingBlock("I read resource://Ab12", "sig-1")),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "read", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "tool_use"}, blockTypes(blocks))
|
||||
first := blocks[0].(map[string]any)
|
||||
assert.Equal(t, "I read resource://Ab12", first["thinking"], "the signed text, not the rewritten one")
|
||||
assert.Equal(t, "sig-1", first["signature"])
|
||||
}
|
||||
|
||||
func TestReplayFallsBackToLegacySingleBlockTurns(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// Assistant turns stored before the metadata existed carry only the
|
||||
// single pair, and must keep replaying.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningContent: "one thought",
|
||||
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "legacy-sig"),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "tool_use"}, blockTypes(blocks))
|
||||
assert.Equal(t, "legacy-sig", blocks[0].(map[string]any)["signature"])
|
||||
}
|
||||
|
||||
func TestReplayIgnoresAnotherProvidersSignature(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "one thought",
|
||||
ReasoningSignature: api.TagSignature(api.APIGoogleGenerativeAI, "gemini-sig"),
|
||||
}
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
assert.NotContains(t, blockTypes(blocks), "thinking")
|
||||
}
|
||||
|
||||
func TestStreamKeepsOneSignaturePerThinkingBlock(t *testing.T) {
|
||||
s := newStreamState()
|
||||
// Two interleaved thinking blocks at different content-block indices.
|
||||
s.thinkingAt(0, "thinking").Thinking = "first"
|
||||
s.thinkingAt(0, "thinking").Signature = "sig-1"
|
||||
s.thinkingAt(2, "thinking").Thinking = "second"
|
||||
s.thinkingAt(2, "thinking").Signature = "sig-2"
|
||||
|
||||
blocks := s.thinkingBlocks()
|
||||
require.Len(t, blocks, 2)
|
||||
assert.Equal(t, thinkingBlock{Type: "thinking", Thinking: "first", Signature: "sig-1"}, blocks[0])
|
||||
assert.Equal(t, thinkingBlock{Type: "thinking", Thinking: "second", Signature: "sig-2"}, blocks[1])
|
||||
}
|
||||
|
||||
func TestTruncatedInterleavedTurnStillReplaysItsSignedBlocks(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// thinking(signed) → tool_use(completed) → thinking(stream cut before
|
||||
// signature_delta). Claude rejects an unsigned thinking block, and it
|
||||
// also rejects a tool_use that is not preceded by thinking — so the
|
||||
// signed block must survive the unsigned one.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningContent: "first thoughtcut off",
|
||||
ReasoningMetadata: storedThinking(t,
|
||||
newThinkingBlock("first thought", "sig-1"),
|
||||
newThinkingBlock("cut off", ""),
|
||||
),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "tool_use"}, blockTypes(blocks),
|
||||
"a tool_use must still be preceded by a thinking block")
|
||||
first := blocks[0].(map[string]any)
|
||||
assert.Equal(t, "first thought", first["thinking"])
|
||||
assert.Equal(t, "sig-1", first["signature"])
|
||||
}
|
||||
|
||||
func TestUnsignedThinkingIsNeverSentOnItsOwn(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// A turn whose only thinking block lost its signature: the block cannot
|
||||
// be replayed at all, so nothing thinking-shaped goes out.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "cut off",
|
||||
ReasoningMetadata: storedThinking(t, newThinkingBlock("cut off", "")),
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
assert.Equal(t, []string{"text"}, blockTypes(blocks))
|
||||
}
|
||||
|
||||
func TestRedactedThinkingSurvivesAnUnsignedNeighbour(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningMetadata: storedThinking(t,
|
||||
newRedactedThinkingBlock("opaque-1"),
|
||||
newThinkingBlock("cut off", ""),
|
||||
),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"redacted_thinking", "tool_use"}, blockTypes(blocks))
|
||||
assert.Equal(t, "opaque-1", blocks[0].(map[string]any)["data"])
|
||||
}
|
||||
|
|
@ -0,0 +1,606 @@
|
|||
package anthropicmessages
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// defaultAnthropicVersion is the anthropic-version value used when the
|
||||
// catalog supplies none.
|
||||
const defaultAnthropicVersion = "2023-06-01"
|
||||
|
||||
// Client talks the Messages protocol to one endpoint.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
}
|
||||
|
||||
// New creates a client.
|
||||
func New(cfg Config) *Client {
|
||||
if cfg.ThinkingLevels == nil {
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
}
|
||||
return &Client{cfg: cfg}
|
||||
}
|
||||
|
||||
// GetModelName returns the wire model name.
|
||||
func (c *Client) GetModelName() string { return c.cfg.Endpoint.Model }
|
||||
|
||||
// GetModelID returns WeKnora's model identifier.
|
||||
func (c *Client) GetModelID() string { return c.cfg.Endpoint.ModelID }
|
||||
|
||||
// Settings exposes the resolved configuration.
|
||||
func (c *Client) Settings() Config { return c.cfg }
|
||||
|
||||
// URL resolves the messages endpoint. Operators paste base URLs in three
|
||||
// shapes: a host ("https://api.anthropic.com"), a versioned root
|
||||
// (".../v1", ".../anthropic/v1") or the full messages URL.
|
||||
func (c *Client) URL() string {
|
||||
if c.cfg.Endpoint.URL != "" {
|
||||
return c.cfg.Endpoint.Resolve("")
|
||||
}
|
||||
base := strings.TrimRight(c.cfg.Endpoint.BaseURL, "/")
|
||||
u, err := url.Parse(base)
|
||||
path := ""
|
||||
if err == nil {
|
||||
path = strings.TrimRight(u.Path, "/")
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(path, "/messages"):
|
||||
return base
|
||||
case strings.HasSuffix(path, "/v1") || strings.HasSuffix(path, "/v1beta"):
|
||||
return base + "/messages"
|
||||
default:
|
||||
return base + "/v1/messages"
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) send(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
|
||||
) (*httpResponse, error) {
|
||||
body, err := c.BuildRequestBody(messages, opts, stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target := c.URL()
|
||||
req, data, err := c.cfg.Endpoint.NewRequest(ctx, target, body, stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// anthropic-version is mandatory; an empty value is rejected with 400, so
|
||||
// fall back to the baseline version when the catalog left it unset.
|
||||
version := c.cfg.Settings.Version
|
||||
if version == "" {
|
||||
version = defaultAnthropicVersion
|
||||
}
|
||||
req.Header.Set("anthropic-version", version)
|
||||
if beta := c.betaHeader(c.planThinking(opts), opts, req.Header.Get("anthropic-beta")); beta != "" {
|
||||
req.Header.Set("anthropic-beta", beta)
|
||||
}
|
||||
api.LogRequest(ctx, target, c.cfg.Endpoint.Model, data, stream)
|
||||
resp, err := c.cfg.Endpoint.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &httpResponse{body: resp.Body, contentType: resp.Header.Get("Content-Type"), data: data}, nil
|
||||
}
|
||||
|
||||
type httpResponse struct {
|
||||
body io.ReadCloser
|
||||
contentType string
|
||||
data []byte
|
||||
}
|
||||
|
||||
// Chat performs a non-streaming call.
|
||||
func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Options) (*types.ChatResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultChatTimeout)
|
||||
defer cancel()
|
||||
resp, err := c.send(ctx, messages, opts, false)
|
||||
if err != nil {
|
||||
// Claude's own models all accept images, but this protocol is also
|
||||
// the compatibility surface of vendors whose text-only models do
|
||||
// not, and the other three clients already degrade this way.
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, false)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.body.Close() }()
|
||||
raw, err := io.ReadAll(resp.body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
var result *types.ChatResponse
|
||||
if strings.Contains(strings.ToLower(resp.contentType), "text/event-stream") {
|
||||
// Some proxies answer non-stream calls with SSE; consume it fully.
|
||||
result, err = c.collectStream(ctx, strings.NewReader(string(raw)))
|
||||
} else {
|
||||
result, err = c.parseResponse(raw)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api.LogUsage(ctx, c.cfg.Endpoint.Model, &result.Usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ChatStream performs a streaming call.
|
||||
func (c *Client) ChatStream(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultStreamTimeout)
|
||||
resp, err := c.send(ctx, messages, opts, true)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ch := make(chan types.StreamResponse)
|
||||
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(resp.data))
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer close(ch)
|
||||
defer func() { _ = resp.body.Close() }()
|
||||
if dumper != nil {
|
||||
defer dumper.Close()
|
||||
}
|
||||
c.processStream(ctx, resp.body, ch, dumper)
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// --- decoding ---
|
||||
|
||||
type usageBlock struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
}
|
||||
|
||||
type responseBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
Type string `json:"type"`
|
||||
Content []responseBlock `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage usageBlock `json:"usage"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type streamEvent struct {
|
||||
Type string `json:"type"`
|
||||
Index int `json:"index"`
|
||||
ContentBlock *responseBlock `json:"content_block,omitempty"`
|
||||
Message *struct {
|
||||
Usage usageBlock `json:"usage"`
|
||||
} `json:"message,omitempty"`
|
||||
Delta *struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
PartialJSON string `json:"partial_json"`
|
||||
} `json:"delta,omitempty"`
|
||||
Usage *usageBlock `json:"usage,omitempty"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) usageFrom(u usageBlock) types.TokenUsage {
|
||||
read := valueOrZero(u.CacheReadInputTokens)
|
||||
write := valueOrZero(u.CacheCreationInputTokens)
|
||||
prompt := u.InputTokens + read + write
|
||||
out := types.TokenUsage{
|
||||
PromptTokens: prompt, CompletionTokens: u.OutputTokens, TotalTokens: prompt + u.OutputTokens,
|
||||
}
|
||||
reported := u.CacheReadInputTokens != nil || u.CacheCreationInputTokens != nil
|
||||
if !reported && !c.cfg.Settings.PromptCacheAccounting {
|
||||
out.MarkPromptCacheUnsupported()
|
||||
return out
|
||||
}
|
||||
out.SetPromptCacheUsage(read, write, max(0, prompt-read), reported)
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
|
||||
var resp response
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
if resp.Error != nil && resp.Error.Message != "" {
|
||||
return nil, fmt.Errorf("API error: %s", resp.Error.Message)
|
||||
}
|
||||
result := &types.ChatResponse{Usage: c.usageFrom(resp.Usage)}
|
||||
var text, thinking []string
|
||||
// Interleaved thinking puts several signed thinking blocks in one reply,
|
||||
// each signed over its own text, so they are kept separately for replay.
|
||||
// ReasoningContent / ReasoningSignature stay filled for readers and for
|
||||
// older stored turns, but they are no longer what goes back on the wire.
|
||||
var stored []thinkingBlock
|
||||
for _, block := range resp.Content {
|
||||
switch block.Type {
|
||||
case "text":
|
||||
if block.Text != "" {
|
||||
text = append(text, block.Text)
|
||||
}
|
||||
case "thinking":
|
||||
thinking = append(thinking, block.Thinking)
|
||||
stored = append(stored, newThinkingBlock(block.Thinking, block.Signature))
|
||||
if block.Signature != "" {
|
||||
result.ReasoningSignature = api.TagSignature(api.APIAnthropicMessages, block.Signature)
|
||||
}
|
||||
case "redacted_thinking":
|
||||
stored = append(stored, newRedactedThinkingBlock(block.Data))
|
||||
case "tool_use":
|
||||
input := string(block.Input)
|
||||
if input == "" {
|
||||
input = "{}"
|
||||
}
|
||||
result.ToolCalls = append(result.ToolCalls, types.LLMToolCall{
|
||||
ID: block.ID, Type: "function",
|
||||
Function: types.FunctionCall{Name: block.Name, Arguments: input},
|
||||
})
|
||||
}
|
||||
}
|
||||
result.Content = strings.Join(text, "")
|
||||
result.ReasoningContent = strings.Join(thinking, "")
|
||||
if blocks := thinkingBlocksMetadata(stored); blocks != nil {
|
||||
result.ReasoningMetadata = types.ProviderMetadata{MetadataThinkingBlocks: blocks}
|
||||
}
|
||||
result.FinishReason = mapStopReason(resp.StopReason, len(result.ToolCalls), false)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// toolInput accumulates one streamed tool_use block.
|
||||
type toolInput struct {
|
||||
call types.LLMToolCall
|
||||
initial string
|
||||
json strings.Builder
|
||||
closed bool
|
||||
}
|
||||
|
||||
// streamState tracks per-index content blocks of one streamed message.
|
||||
type streamState struct {
|
||||
tools map[int]*toolInput
|
||||
toolOrder []int
|
||||
blockType map[int]string
|
||||
signature string
|
||||
// thinking accumulates each thinking / redacted_thinking block by its
|
||||
// content-block index, and thinkingOrder keeps the order they started in.
|
||||
// Interleaved thinking sends several, each with its own signature_delta;
|
||||
// accumulating into one string would splice two signatures together and
|
||||
// produce one that verifies against nothing.
|
||||
thinking map[int]*thinkingBlock
|
||||
thinkingOrder []int
|
||||
stop string
|
||||
usage *types.TokenUsage
|
||||
}
|
||||
|
||||
func newStreamState() *streamState {
|
||||
return &streamState{
|
||||
tools: map[int]*toolInput{},
|
||||
blockType: map[int]string{},
|
||||
thinking: map[int]*thinkingBlock{},
|
||||
}
|
||||
}
|
||||
|
||||
// thinkingAt returns the block being streamed at this content-block index,
|
||||
// creating it on first use. A vendor that sends deltas without a
|
||||
// content_block_start still gets a block rather than losing the text.
|
||||
func (s *streamState) thinkingAt(index int, blockType string) *thinkingBlock {
|
||||
if b, ok := s.thinking[index]; ok {
|
||||
return b
|
||||
}
|
||||
b := &thinkingBlock{Type: blockType}
|
||||
s.thinking[index] = b
|
||||
s.thinkingOrder = append(s.thinkingOrder, index)
|
||||
return b
|
||||
}
|
||||
|
||||
// thinkingBlocks returns the finished blocks in the order Claude sent them.
|
||||
func (s *streamState) thinkingBlocks() []thinkingBlock {
|
||||
blocks := make([]thinkingBlock, 0, len(s.thinkingOrder))
|
||||
for _, index := range s.thinkingOrder {
|
||||
if b := s.thinking[index]; b != nil {
|
||||
blocks = append(blocks, *b)
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func (s *streamState) calls() []types.LLMToolCall {
|
||||
indexes := make([]int, 0, len(s.tools))
|
||||
for index := range s.tools {
|
||||
indexes = append(indexes, index)
|
||||
}
|
||||
sort.Ints(indexes)
|
||||
var calls []types.LLMToolCall
|
||||
for _, index := range indexes {
|
||||
t := s.tools[index]
|
||||
if !t.closed {
|
||||
// A cut-off stream often starts the next tool_use with {}. Executing
|
||||
// that empty object is worse than omitting it.
|
||||
continue
|
||||
}
|
||||
call := t.call
|
||||
call.Function.Arguments = t.initial
|
||||
if t.json.Len() > 0 {
|
||||
call.Function.Arguments = t.json.String()
|
||||
}
|
||||
calls = append(calls, call)
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
func (s *streamState) incomplete() bool {
|
||||
for _, t := range s.tools {
|
||||
if !t.closed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *streamState) toolIndex(blockIndex int) int {
|
||||
for i, idx := range s.toolOrder {
|
||||
if idx == blockIndex {
|
||||
return i
|
||||
}
|
||||
}
|
||||
s.toolOrder = append(s.toolOrder, blockIndex)
|
||||
return len(s.toolOrder) - 1
|
||||
}
|
||||
|
||||
// consume folds one event into the state and returns the protocol-neutral
|
||||
// delta to hand to the assembler (may be empty).
|
||||
func (c *Client) consume(s *streamState, ev streamEvent) api.Delta {
|
||||
var d api.Delta
|
||||
switch ev.Type {
|
||||
case "message_start":
|
||||
if ev.Message != nil {
|
||||
u := c.usageFrom(ev.Message.Usage)
|
||||
s.usage = &u
|
||||
}
|
||||
case "content_block_start":
|
||||
if ev.ContentBlock == nil {
|
||||
break
|
||||
}
|
||||
s.blockType[ev.Index] = ev.ContentBlock.Type
|
||||
switch ev.ContentBlock.Type {
|
||||
case "tool_use":
|
||||
initial := string(ev.ContentBlock.Input)
|
||||
if initial == "" || initial == "null" {
|
||||
initial = "{}"
|
||||
}
|
||||
s.tools[ev.Index] = &toolInput{
|
||||
initial: initial,
|
||||
call: types.LLMToolCall{
|
||||
ID: ev.ContentBlock.ID, Type: "function",
|
||||
Function: types.FunctionCall{Name: ev.ContentBlock.Name},
|
||||
},
|
||||
}
|
||||
d.ToolCalls = []api.ToolCallDelta{{
|
||||
Index: s.toolIndex(ev.Index), ID: ev.ContentBlock.ID, Type: "function", Name: ev.ContentBlock.Name,
|
||||
}}
|
||||
case "redacted_thinking":
|
||||
s.thinkingAt(ev.Index, "redacted_thinking").Data = ev.ContentBlock.Data
|
||||
case "thinking":
|
||||
block := s.thinkingAt(ev.Index, "thinking")
|
||||
if ev.ContentBlock.Thinking != "" {
|
||||
block.Thinking += ev.ContentBlock.Thinking
|
||||
d.Reasoning = ev.ContentBlock.Thinking
|
||||
}
|
||||
case "text":
|
||||
if ev.ContentBlock.Text != "" {
|
||||
d.Content = ev.ContentBlock.Text
|
||||
}
|
||||
}
|
||||
case "content_block_delta":
|
||||
if ev.Delta == nil {
|
||||
break
|
||||
}
|
||||
switch ev.Delta.Type {
|
||||
case "text_delta":
|
||||
d.Content = ev.Delta.Text
|
||||
case "thinking_delta":
|
||||
d.Reasoning = ev.Delta.Thinking
|
||||
s.thinkingAt(ev.Index, "thinking").Thinking += ev.Delta.Thinking
|
||||
case "signature_delta":
|
||||
// The signature belongs to the block at this index; the top-level
|
||||
// field keeps carrying the last one for readers that still use it.
|
||||
block := s.thinkingAt(ev.Index, "thinking")
|
||||
block.Signature += ev.Delta.Signature
|
||||
s.signature = block.Signature
|
||||
case "input_json_delta":
|
||||
if t := s.tools[ev.Index]; t != nil {
|
||||
t.json.WriteString(ev.Delta.PartialJSON)
|
||||
d.ToolCalls = []api.ToolCallDelta{{Index: s.toolIndex(ev.Index), Arguments: ev.Delta.PartialJSON}}
|
||||
}
|
||||
}
|
||||
case "content_block_stop":
|
||||
if t := s.tools[ev.Index]; t != nil {
|
||||
t.closed = true
|
||||
if t.json.Len() == 0 {
|
||||
// No input_json_delta carried any payload — an argument-less
|
||||
// tool, or a vendor that puts the whole input on
|
||||
// content_block_start. The assembler only emits its early
|
||||
// ResponseTypeToolCall marker once a chunk updates the
|
||||
// arguments of an already-named call, so replay the initial
|
||||
// input here. Without it the UI never learns the call started.
|
||||
// The final arguments are unchanged: calls() uses t.initial too.
|
||||
d.ToolCalls = []api.ToolCallDelta{{Index: s.toolIndex(ev.Index), Arguments: t.initial}}
|
||||
}
|
||||
}
|
||||
case "message_delta":
|
||||
if ev.Delta != nil && ev.Delta.StopReason != "" {
|
||||
s.stop = ev.Delta.StopReason
|
||||
}
|
||||
if ev.Usage != nil {
|
||||
u := c.usageFrom(*ev.Usage)
|
||||
if s.usage != nil {
|
||||
// message_delta carries cumulative output tokens; input
|
||||
// counters arrived on message_start.
|
||||
u.PromptTokens = max(u.PromptTokens, s.usage.PromptTokens)
|
||||
u.SetPromptCacheUsage(
|
||||
max(u.CacheReadTokens, s.usage.CacheReadTokens),
|
||||
max(u.CacheWriteTokens, s.usage.CacheWriteTokens),
|
||||
max(0, u.PromptTokens-max(u.CacheReadTokens, s.usage.CacheReadTokens)),
|
||||
u.CacheReported || s.usage.CacheReported,
|
||||
)
|
||||
u.TotalTokens = u.PromptTokens + u.CompletionTokens
|
||||
}
|
||||
s.usage = &u
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func (c *Client) processStream(
|
||||
ctx context.Context, body io.Reader, ch chan<- types.StreamResponse, dumper *api.StreamPacketDumper,
|
||||
) {
|
||||
assembler := api.NewStreamAssembler(ctx, c.cfg.Endpoint.Model)
|
||||
state := newStreamState()
|
||||
reader := api.NewSSEReader(body)
|
||||
finish := func() {
|
||||
calls := state.calls()
|
||||
assembler.ReplaceToolCalls(calls)
|
||||
assembler.ReasoningSignature = api.TagSignature(api.APIAnthropicMessages, state.signature)
|
||||
if blocks := thinkingBlocksMetadata(state.thinkingBlocks()); blocks != nil {
|
||||
assembler.ReasoningMetadata = types.ProviderMetadata{MetadataThinkingBlocks: blocks}
|
||||
}
|
||||
if state.usage != nil {
|
||||
assembler.SetUsage(*state.usage)
|
||||
}
|
||||
assembler.Process(ch, api.Delta{FinishReason: mapStopReason(state.stop, len(calls), state.incomplete())})
|
||||
assembler.End(ch)
|
||||
}
|
||||
for {
|
||||
// The consumer went away (client disconnect, aborted agent turn): stop
|
||||
// decoding a stream nobody will read instead of spinning to EOF.
|
||||
if assembler.Aborted() {
|
||||
return
|
||||
}
|
||||
event, err := reader.ReadEvent()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
finish()
|
||||
} else {
|
||||
assembler.Fail(ch, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if event == nil || event.Done {
|
||||
if event != nil && event.Done {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(event.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
if dumper != nil {
|
||||
raw := make([]byte, len(event.Data))
|
||||
copy(raw, event.Data)
|
||||
dumper.WritePacketRaw(raw)
|
||||
}
|
||||
var ev streamEvent
|
||||
if err := json.Unmarshal(event.Data, &ev); err != nil {
|
||||
assembler.Fail(ch, fmt.Errorf("decode SSE response: %w", err))
|
||||
return
|
||||
}
|
||||
if ev.Error != nil && ev.Error.Message != "" {
|
||||
assembler.Fail(ch, fmt.Errorf("API stream error: %s", ev.Error.Message))
|
||||
return
|
||||
}
|
||||
delta := c.consume(state, ev)
|
||||
if delta.Content != "" || delta.Reasoning != "" || len(delta.ToolCalls) > 0 {
|
||||
assembler.Process(ch, delta)
|
||||
}
|
||||
if ev.Type == "message_stop" {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// collectStream folds an SSE body into one ChatResponse (used when a proxy
|
||||
// answers a non-stream request with SSE).
|
||||
func (c *Client) collectStream(ctx context.Context, body io.Reader) (*types.ChatResponse, error) {
|
||||
ch := make(chan types.StreamResponse, 64)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
c.processStream(ctx, body, ch, nil)
|
||||
}()
|
||||
result := &types.ChatResponse{}
|
||||
var content, reasoning strings.Builder
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeError:
|
||||
return nil, fmt.Errorf("%s", chunk.Content)
|
||||
case types.ResponseTypeThinking:
|
||||
reasoning.WriteString(chunk.Content)
|
||||
case types.ResponseTypeAnswer:
|
||||
content.WriteString(chunk.Content)
|
||||
if len(chunk.ToolCalls) > 0 {
|
||||
result.ToolCalls = chunk.ToolCalls
|
||||
}
|
||||
if chunk.Usage != nil {
|
||||
result.Usage = *chunk.Usage
|
||||
}
|
||||
if chunk.FinishReason != "" {
|
||||
result.FinishReason = chunk.FinishReason
|
||||
}
|
||||
if sig, ok := chunk.Data["reasoning_signature"].(string); ok {
|
||||
result.ReasoningSignature = sig
|
||||
}
|
||||
if md, ok := chunk.Data["reasoning_metadata"].(types.ProviderMetadata); ok {
|
||||
result.ReasoningMetadata = md
|
||||
}
|
||||
}
|
||||
}
|
||||
result.Content = content.String()
|
||||
result.ReasoningContent = reasoning.String()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func valueOrZero(v *int) int {
|
||||
if v == nil {
|
||||
return 0
|
||||
}
|
||||
return *v
|
||||
}
|
||||
|
|
@ -0,0 +1,529 @@
|
|||
// Package anthropicmessages implements the Anthropic Messages wire protocol
|
||||
// (https://docs.anthropic.com/en/api/messages). MiniMax, Zhipu, Moonshot and
|
||||
// Volcengine expose the same protocol on an ".../anthropic" base URL, so the
|
||||
// package contains no vendor names: every deviation is a
|
||||
// catalog.AnthropicMessagesSettings field.
|
||||
package anthropicmessages
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Config is everything the client needs, already resolved by the catalog.
|
||||
type Config struct {
|
||||
Endpoint api.Endpoint
|
||||
Settings catalog.AnthropicMessagesSettings
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
Reasoning bool
|
||||
}
|
||||
|
||||
// Metadata keys used on messages and tool calls.
|
||||
const (
|
||||
// MetadataRedactedThinking stores redacted_thinking blocks (JSON array
|
||||
// of {"data": ...}) that must be replayed verbatim. Superseded by
|
||||
// MetadataThinkingBlocks; still read so assistant turns stored by an
|
||||
// earlier build keep replaying.
|
||||
MetadataRedactedThinking = "anthropic_redacted_thinking"
|
||||
// MetadataThinkingBlocks stores the turn's thinking and
|
||||
// redacted_thinking blocks exactly as Claude emitted them, in order.
|
||||
//
|
||||
// Two properties make this the only correct source for replay. First,
|
||||
// Claude signs the exact text of each block, so one assistant turn with
|
||||
// interleaved thinking carries several (text, signature) pairs that a
|
||||
// single ReasoningContent / ReasoningSignature pair cannot represent —
|
||||
// concatenating them produces a signature that matches nothing. Second,
|
||||
// ReasoningContent is rewritten downstream (resource-handle encoding,
|
||||
// citation compaction, special-token neutralisation) for the benefit of
|
||||
// readers and of the next prompt, which invalidates the signature over
|
||||
// it. This metadata is opaque to all of that and travels unchanged.
|
||||
MetadataThinkingBlocks = "anthropic_thinking_blocks"
|
||||
)
|
||||
|
||||
// thinkingBlock is one stored thinking or redacted_thinking block. It is the
|
||||
// wire shape, so replay is a copy rather than a reconstruction.
|
||||
type thinkingBlock struct {
|
||||
Type string `json:"type"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// thinkingBlocksMetadata renders the blocks for storage on the assistant
|
||||
// message. It returns nil when there is nothing to replay.
|
||||
func thinkingBlocksMetadata(blocks []thinkingBlock) json.RawMessage {
|
||||
if len(blocks) == 0 {
|
||||
return nil
|
||||
}
|
||||
data, err := json.Marshal(blocks)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// newThinkingBlock records a signed thinking block.
|
||||
func newThinkingBlock(thinking, signature string) thinkingBlock {
|
||||
return thinkingBlock{Type: "thinking", Thinking: thinking, Signature: signature}
|
||||
}
|
||||
|
||||
// newRedactedThinkingBlock records an opaque redacted_thinking block.
|
||||
func newRedactedThinkingBlock(data string) thinkingBlock {
|
||||
return thinkingBlock{Type: "redacted_thinking", Data: data}
|
||||
}
|
||||
|
||||
type cacheControl struct {
|
||||
Type string `json:"type"`
|
||||
TTL string `json:"ttl,omitempty"`
|
||||
}
|
||||
|
||||
type contentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
CacheControl *cacheControl `json:"cache_control,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Input json.RawMessage `json:"input,omitempty"`
|
||||
ToolUseID string `json:"tool_use_id,omitempty"`
|
||||
Content any `json:"content,omitempty"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
Source *imageSource `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
type imageSource struct {
|
||||
Type string `json:"type"` // "base64" | "url"
|
||||
MediaType string `json:"media_type,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
||||
type message struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
}
|
||||
|
||||
type tool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema json.RawMessage `json:"input_schema"`
|
||||
CacheControl *cacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
type toolChoice struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name,omitempty"`
|
||||
DisableParallelToolUse *bool `json:"disable_parallel_tool_use,omitempty"`
|
||||
}
|
||||
|
||||
// thinkingPlan is the resolved thinking request for one call.
|
||||
type thinkingPlan struct {
|
||||
enabled bool
|
||||
body map[string]any // the "thinking" object, nil when omitted
|
||||
effort string // output_config.effort, "" when omitted
|
||||
budget int // budget_tokens in budget mode
|
||||
}
|
||||
|
||||
func (c *Client) planThinking(opts *api.Options) thinkingPlan {
|
||||
s := c.cfg.Settings
|
||||
levels := c.cfg.ThinkingLevels
|
||||
level, requested := opts.Reasoning()
|
||||
if !requested {
|
||||
return thinkingPlan{}
|
||||
}
|
||||
if level.Graded() {
|
||||
level = levels.Clamp(level)
|
||||
}
|
||||
if !level.Enabled() {
|
||||
if levels.Supports(api.ReasoningOff) && s.ThinkingMode == catalog.AnthropicThinkingAdaptive {
|
||||
return thinkingPlan{body: map[string]any{"type": "disabled"}}
|
||||
}
|
||||
// Budget mode: omitting the thinking object disables it.
|
||||
return thinkingPlan{}
|
||||
}
|
||||
plan := thinkingPlan{enabled: true}
|
||||
switch s.ThinkingMode {
|
||||
case catalog.AnthropicThinkingAdaptive:
|
||||
plan.body = map[string]any{"type": "adaptive"}
|
||||
if level.Graded() && s.SupportsEffort {
|
||||
plan.effort = levels.Value(level)
|
||||
}
|
||||
default:
|
||||
budget := 0
|
||||
if opts != nil && opts.ThinkingBudgetTokens > 0 {
|
||||
budget = opts.ThinkingBudgetTokens
|
||||
} else {
|
||||
key := level
|
||||
if !key.Graded() {
|
||||
key = api.ReasoningMedium
|
||||
}
|
||||
budget = s.ThinkingBudgets[key]
|
||||
}
|
||||
if budget < 1024 {
|
||||
budget = 1024
|
||||
}
|
||||
plan.budget = budget
|
||||
plan.body = map[string]any{"type": "enabled", "budget_tokens": budget}
|
||||
}
|
||||
return plan
|
||||
}
|
||||
|
||||
// BuildRequestBody is the golden-test entry point.
|
||||
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
s := c.cfg.Settings
|
||||
body := map[string]any{"model": c.cfg.Endpoint.Model}
|
||||
if stream {
|
||||
body["stream"] = true
|
||||
}
|
||||
plan := c.planThinking(opts)
|
||||
|
||||
maxTokens := opts.CompletionBudget()
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = s.DefaultMaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = 4096
|
||||
}
|
||||
}
|
||||
if plan.budget > 0 && maxTokens <= plan.budget {
|
||||
// max_tokens must exceed budget_tokens; keep the caller's answer
|
||||
// budget on top of the thinking budget.
|
||||
maxTokens = plan.budget + max(maxTokens, 1024)
|
||||
}
|
||||
body["max_tokens"] = maxTokens
|
||||
|
||||
if opts != nil {
|
||||
if s.SupportsTemperature && opts.Temperature > 0 && (!plan.enabled || s.TemperatureWithThinking) {
|
||||
body["temperature"] = opts.Temperature
|
||||
} else if s.SupportsTopP && opts.TopP > 0 && !plan.enabled {
|
||||
// temperature and top_p are mutually exclusive on current models;
|
||||
// temperature wins when both are set.
|
||||
body["top_p"] = opts.TopP
|
||||
}
|
||||
}
|
||||
|
||||
retention := api.ResolveCacheRetention(opts)
|
||||
var marker *cacheControl
|
||||
if s.SupportsCacheControl {
|
||||
if m := api.CacheControlFor(retention, s.LongCacheTTL); m != nil {
|
||||
marker = &cacheControl{Type: m.Type, TTL: m.TTL}
|
||||
}
|
||||
}
|
||||
|
||||
if opts != nil && len(opts.Tools) > 0 {
|
||||
tools := make([]tool, 0, len(opts.Tools))
|
||||
for _, t := range opts.Tools {
|
||||
schema := t.Function.Parameters
|
||||
if len(schema) == 0 {
|
||||
schema = json.RawMessage(`{"type":"object","properties":{}}`)
|
||||
}
|
||||
tools = append(tools, tool{Name: t.Function.Name, Description: t.Function.Description, InputSchema: schema})
|
||||
}
|
||||
if marker != nil && s.SupportsCacheControlOnTool {
|
||||
tools[len(tools)-1].CacheControl = marker
|
||||
}
|
||||
body["tools"] = tools
|
||||
choice := &toolChoice{Type: "auto"}
|
||||
switch opts.ToolChoice {
|
||||
case "", "auto":
|
||||
case "required":
|
||||
choice.Type = "any"
|
||||
case "none":
|
||||
choice.Type = "none"
|
||||
default:
|
||||
choice.Type, choice.Name = "tool", opts.ToolChoice
|
||||
}
|
||||
if opts.ParallelToolCalls != nil && choice.Type != "none" {
|
||||
disable := !*opts.ParallelToolCalls
|
||||
choice.DisableParallelToolUse = &disable
|
||||
}
|
||||
body["tool_choice"] = choice
|
||||
}
|
||||
|
||||
systemParts, converted := c.convertMessages(messages, opts)
|
||||
systemText := strings.Join(systemParts, "\n\n")
|
||||
if marker == nil {
|
||||
if systemText != "" {
|
||||
body["system"] = systemText
|
||||
}
|
||||
} else {
|
||||
if systemText != "" {
|
||||
body["system"] = []contentBlock{{Type: "text", Text: systemText, CacheControl: marker}}
|
||||
}
|
||||
if len(converted) > 0 {
|
||||
last := &converted[len(converted)-1]
|
||||
switch content := last.Content.(type) {
|
||||
case string:
|
||||
if content != "" {
|
||||
last.Content = []contentBlock{{Type: "text", Text: content, CacheControl: marker}}
|
||||
}
|
||||
case []contentBlock:
|
||||
if len(content) > 0 {
|
||||
content[len(content)-1].CacheControl = marker
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if converted == nil {
|
||||
// "messages" is required and must be an array: a nil slice would
|
||||
// marshal to null and the API answers 400. A request whose only
|
||||
// entries were system messages legitimately produces no turns.
|
||||
converted = []message{}
|
||||
}
|
||||
body["messages"] = converted
|
||||
|
||||
if plan.body != nil {
|
||||
body["thinking"] = plan.body
|
||||
}
|
||||
if plan.effort != "" {
|
||||
body["output_config"] = map[string]any{"effort": plan.effort}
|
||||
}
|
||||
for k, v := range s.ExtraBody {
|
||||
if _, exists := body[k]; !exists {
|
||||
body[k] = v
|
||||
}
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// betaHeader composes the anthropic-beta header for this request.
|
||||
func (c *Client) betaHeader(plan thinkingPlan, opts *api.Options, userValue string) string {
|
||||
s := c.cfg.Settings
|
||||
seen := map[string]bool{}
|
||||
var betas []string
|
||||
add := func(v string) {
|
||||
for _, part := range strings.Split(v, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part != "" && !seen[part] {
|
||||
seen[part] = true
|
||||
betas = append(betas, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, b := range s.BetaHeaders {
|
||||
add(b)
|
||||
}
|
||||
if plan.enabled && s.ThinkingMode != catalog.AnthropicThinkingAdaptive && s.InterleavedThinkingBeta != "" &&
|
||||
opts != nil && len(opts.Tools) > 0 {
|
||||
add(s.InterleavedThinkingBeta)
|
||||
}
|
||||
add(userValue)
|
||||
return strings.Join(betas, ",")
|
||||
}
|
||||
|
||||
// convertMessages maps neutral messages onto Anthropic messages. System
|
||||
// messages are lifted out; tool calls become tool_use blocks; consecutive
|
||||
// tool results merge into one user message; thinking blocks are replayed
|
||||
// only when they carry a signature (the API rejects unsigned ones).
|
||||
func (c *Client) convertMessages(messages []api.Message, _ *api.Options) ([]string, []message) {
|
||||
var system []string
|
||||
var result []message
|
||||
for _, msg := range messages {
|
||||
msg = api.NeutralizeMessageSpecialTokens(msg)
|
||||
content := strings.TrimSpace(msg.Content)
|
||||
switch msg.Role {
|
||||
case "system":
|
||||
if content == "" {
|
||||
content = textFromMultiContent(msg.MultiContent)
|
||||
}
|
||||
if content != "" {
|
||||
system = append(system, content)
|
||||
}
|
||||
case "assistant":
|
||||
blocks := c.assistantBlocks(msg, content)
|
||||
if len(blocks) == 0 {
|
||||
continue
|
||||
}
|
||||
if len(blocks) == 1 && blocks[0].Type == "text" && len(msg.ToolCalls) == 0 {
|
||||
result = append(result, message{Role: "assistant", Content: blocks[0].Text})
|
||||
continue
|
||||
}
|
||||
result = append(result, message{Role: "assistant", Content: blocks})
|
||||
case "tool":
|
||||
block := contentBlock{Type: "tool_result", ToolUseID: msg.ToolCallID, Content: msg.Content}
|
||||
if len(result) > 0 && result[len(result)-1].Role == "user" {
|
||||
if blocks, ok := result[len(result)-1].Content.([]contentBlock); ok && len(blocks) > 0 &&
|
||||
blocks[0].Type == "tool_result" {
|
||||
result[len(result)-1].Content = append(blocks, block)
|
||||
continue
|
||||
}
|
||||
}
|
||||
result = append(result, message{Role: "user", Content: []contentBlock{block}})
|
||||
default:
|
||||
blocks := userBlocks(msg, content)
|
||||
if len(blocks) == 0 {
|
||||
continue
|
||||
}
|
||||
if len(blocks) == 1 && blocks[0].Type == "text" {
|
||||
result = append(result, message{Role: "user", Content: blocks[0].Text})
|
||||
continue
|
||||
}
|
||||
result = append(result, message{Role: "user", Content: blocks})
|
||||
}
|
||||
}
|
||||
return system, result
|
||||
}
|
||||
|
||||
func (c *Client) assistantBlocks(msg api.Message, content string) []contentBlock {
|
||||
blocks := replayThinkingBlocks(msg)
|
||||
if content == "" {
|
||||
content = textFromMultiContent(msg.MultiContent)
|
||||
}
|
||||
if content != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: content})
|
||||
}
|
||||
for _, call := range msg.ToolCalls {
|
||||
input := json.RawMessage(call.Function.Arguments)
|
||||
if len(input) == 0 || !json.Valid(input) {
|
||||
input = json.RawMessage(`{}`)
|
||||
}
|
||||
blocks = append(blocks, contentBlock{Type: "tool_use", ID: call.ID, Name: call.Function.Name, Input: input})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// replayThinkingBlocks rebuilds the leading thinking / redacted_thinking
|
||||
// blocks of a stored assistant turn.
|
||||
//
|
||||
// Claude requires them back verbatim whenever that turn also carries tool_use
|
||||
// and extended thinking was on: dropping them answers 400 ("Expected
|
||||
// `thinking` or `redacted_thinking`, but found `tool_use`"), and altering the
|
||||
// signed text answers 400 as well. Preference order is therefore the verbatim
|
||||
// metadata first, then the legacy single-block fields for turns stored before
|
||||
// that metadata existed.
|
||||
func replayThinkingBlocks(msg api.Message) []contentBlock {
|
||||
if raw, ok := msg.ReasoningMetadata[MetadataThinkingBlocks]; ok && len(raw) > 0 {
|
||||
var stored []thinkingBlock
|
||||
if err := json.Unmarshal(raw, &stored); err == nil {
|
||||
blocks := make([]contentBlock, 0, len(stored))
|
||||
for _, b := range stored {
|
||||
switch b.Type {
|
||||
case "thinking":
|
||||
// An unsigned block cannot go back: Claude rejects a
|
||||
// thinking block without a signature. It means the stream
|
||||
// ended inside that block (truncation), so it is the last
|
||||
// one and produced no tool_use of its own. Skip just it —
|
||||
// discarding the whole turn's blocks instead would strip
|
||||
// the signed ones that a completed tool_use in the same
|
||||
// turn still needs, which is the 400 this replay exists
|
||||
// to prevent.
|
||||
if b.Signature == "" {
|
||||
continue
|
||||
}
|
||||
blocks = append(blocks, contentBlock{
|
||||
Type: "thinking", Thinking: b.Thinking, Signature: b.Signature,
|
||||
})
|
||||
case "redacted_thinking":
|
||||
blocks = append(blocks, contentBlock{Type: "redacted_thinking", Data: b.Data})
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
}
|
||||
|
||||
var blocks []contentBlock
|
||||
if raw, ok := msg.ReasoningMetadata[MetadataRedactedThinking]; ok && len(raw) > 0 {
|
||||
var redacted []string
|
||||
if err := json.Unmarshal(raw, &redacted); err == nil {
|
||||
for _, data := range redacted {
|
||||
blocks = append(blocks, contentBlock{Type: "redacted_thinking", Data: data})
|
||||
}
|
||||
}
|
||||
}
|
||||
sig := api.SignatureFor(api.APIAnthropicMessages, msg.ReasoningSignature)
|
||||
if msg.ReasoningContent != "" && sig != "" {
|
||||
blocks = append(blocks, contentBlock{
|
||||
Type: "thinking", Thinking: msg.ReasoningContent, Signature: sig,
|
||||
})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func userBlocks(msg api.Message, content string) []contentBlock {
|
||||
var blocks []contentBlock
|
||||
addImage := func(ref string) {
|
||||
if src := imageSourceFor(ref); src != nil {
|
||||
blocks = append(blocks, contentBlock{Type: "image", Source: src})
|
||||
}
|
||||
}
|
||||
if len(msg.MultiContent) > 0 {
|
||||
for _, part := range msg.MultiContent {
|
||||
switch part.Type {
|
||||
case "text":
|
||||
if t := strings.TrimSpace(part.Text); t != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: t})
|
||||
}
|
||||
case "image_url":
|
||||
if part.ImageURL != nil {
|
||||
addImage(part.ImageURL.URL)
|
||||
}
|
||||
}
|
||||
}
|
||||
if content != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: content})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
for _, img := range msg.Images {
|
||||
addImage(img)
|
||||
}
|
||||
if content != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: content})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// imageSourceFor converts a data URI or URL into an image source block.
|
||||
func imageSourceFor(ref string) *imageSource {
|
||||
ref = api.ResolveImageURLForLLM(ref)
|
||||
if strings.HasPrefix(ref, "data:") {
|
||||
semi := strings.Index(ref, ";base64,")
|
||||
if semi < 0 {
|
||||
return nil
|
||||
}
|
||||
mediaType := strings.TrimPrefix(ref[:semi], "data:")
|
||||
data := ref[semi+len(";base64,"):]
|
||||
if _, err := base64.StdEncoding.DecodeString(data); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &imageSource{Type: "base64", MediaType: mediaType, Data: data}
|
||||
}
|
||||
if u, err := url.Parse(ref); err == nil && (u.Scheme == "http" || u.Scheme == "https") {
|
||||
return &imageSource{Type: "url", URL: ref}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func textFromMultiContent(parts []api.MessageContentPart) string {
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
textParts := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if part.Type == "text" && strings.TrimSpace(part.Text) != "" {
|
||||
textParts = append(textParts, strings.TrimSpace(part.Text))
|
||||
}
|
||||
}
|
||||
return strings.Join(textParts, "\n")
|
||||
}
|
||||
|
||||
// mapStopReason converts Anthropic stop reasons to the shared vocabulary.
|
||||
func mapStopReason(reason string, toolCalls int, incomplete bool) string {
|
||||
switch {
|
||||
case incomplete, reason == "":
|
||||
return types.FinishReasonIncomplete
|
||||
case reason == "max_tokens":
|
||||
return "length"
|
||||
case reason == "tool_use" || (toolCalls > 0 && reason == "end_turn"):
|
||||
return "tool_calls"
|
||||
case reason == "refusal":
|
||||
return "content_filter"
|
||||
}
|
||||
return reason
|
||||
}
|
||||
|
|
@ -0,0 +1,158 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// AuthFunc stamps credentials onto an outbound request. body is the exact
|
||||
// bytes being sent so signing vendors can hash them.
|
||||
type AuthFunc func(req *http.Request, body []byte)
|
||||
|
||||
// BearerAuth is the default: Authorization: Bearer <key>.
|
||||
func BearerAuth(apiKey string) AuthFunc {
|
||||
return func(req *http.Request, _ []byte) {
|
||||
if apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HeaderAuth writes the key under an arbitrary header (api-key for Azure,
|
||||
// x-api-key for Anthropic, x-goog-api-key for Gemini).
|
||||
func HeaderAuth(header, apiKey string) AuthFunc {
|
||||
return func(req *http.Request, _ []byte) {
|
||||
if apiKey != "" {
|
||||
req.Header.Set(header, apiKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NoAuth sends no credentials at all (local deployments).
|
||||
func NoAuth() AuthFunc { return func(*http.Request, []byte) {} }
|
||||
|
||||
// Endpoint is everything a protocol client needs to reach one model.
|
||||
type Endpoint struct {
|
||||
// BaseURL is the vendor root without a trailing slash.
|
||||
BaseURL string
|
||||
// URL, when set, is the complete request URL and overrides the protocol
|
||||
// default of BaseURL + protocol path. Vendors with non-standard paths
|
||||
// (Azure deployments, WeKnora Cloud) set it.
|
||||
URL string
|
||||
// Query is appended to the final URL (Azure api-version).
|
||||
Query map[string]string
|
||||
// Model is the name sent on the wire; ModelID is WeKnora's own identifier.
|
||||
Model string
|
||||
ModelID string
|
||||
// Auth stamps credentials; Headers are static extra headers (vendor
|
||||
// betas, user-configured custom headers). User headers never override
|
||||
// the protocol's own reserved headers.
|
||||
Auth AuthFunc
|
||||
Headers map[string]string
|
||||
// Client is the HTTP client; nil uses the shared SSRF-safe client.
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
// Resolve builds the request URL from the endpoint description.
|
||||
func (e Endpoint) Resolve(defaultPath string) string {
|
||||
target := e.URL
|
||||
if target == "" {
|
||||
target = strings.TrimRight(e.BaseURL, "/") + defaultPath
|
||||
}
|
||||
if len(e.Query) == 0 {
|
||||
return target
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString(target)
|
||||
sep := "?"
|
||||
if strings.Contains(target, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
for k, v := range e.Query {
|
||||
b.WriteString(sep)
|
||||
b.WriteString(k)
|
||||
b.WriteString("=")
|
||||
b.WriteString(v)
|
||||
sep = "&"
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (e Endpoint) httpClient() *http.Client {
|
||||
if e.Client != nil {
|
||||
return e.Client
|
||||
}
|
||||
return HTTPClient
|
||||
}
|
||||
|
||||
// NewRequest prepares an authenticated JSON POST. The body is marshalled
|
||||
// once so signing vendors see exactly what is sent.
|
||||
func (e Endpoint) NewRequest(ctx context.Context, url string, body any, stream bool) (*http.Request, []byte, error) {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
if err := secutils.ValidateURLForSSRF(url); err != nil {
|
||||
return nil, nil, fmt.Errorf("endpoint SSRF check failed: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if stream {
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
}
|
||||
if e.Auth != nil {
|
||||
e.Auth(req, data)
|
||||
}
|
||||
// User headers are applied last but the helper skips reserved names so
|
||||
// they cannot clobber auth or content negotiation.
|
||||
secutils.ApplyCustomHeaders(req, e.Headers)
|
||||
return req, data, nil
|
||||
}
|
||||
|
||||
// Do sends the request and returns the response. Non-2xx responses are
|
||||
// turned into an error carrying the body so callers surface vendor messages.
|
||||
func (e Endpoint) Do(req *http.Request) (*http.Response, error) {
|
||||
resp, err := e.httpClient().Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("send request: %w", err)
|
||||
}
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
_ = resp.Body.Close()
|
||||
return nil, &HTTPError{StatusCode: resp.StatusCode, Body: string(body)}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// HTTPError is a non-2xx vendor reply.
|
||||
type HTTPError struct {
|
||||
StatusCode int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *HTTPError) Error() string {
|
||||
return fmt.Sprintf("API request failed with status %d: %s", e.StatusCode, e.Body)
|
||||
}
|
||||
|
||||
// LogRequest emits the standard request log line with image payloads
|
||||
// compacted so data URIs do not flood the log.
|
||||
func LogRequest(ctx context.Context, url, model string, body []byte, stream bool) {
|
||||
pretty := body
|
||||
var buf bytes.Buffer
|
||||
if err := json.Indent(&buf, body, "", " "); err == nil {
|
||||
pretty = buf.Bytes()
|
||||
}
|
||||
logger.Infof(ctx, "[LLM Request] endpoint=%s, model=%s, stream=%v, request:\n%s",
|
||||
url, model, stream, secutils.CompactImageDataURLForLog(string(pretty)))
|
||||
}
|
||||
|
|
@ -0,0 +1,429 @@
|
|||
package googlegenai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
methodGenerate = "generateContent"
|
||||
methodStreamGenerate = "streamGenerateContent"
|
||||
)
|
||||
|
||||
// Client talks generateContent to one endpoint.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
}
|
||||
|
||||
// New creates a client. The endpoint must already carry auth and headers.
|
||||
func New(cfg Config) *Client {
|
||||
if cfg.ThinkingLevels == nil {
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
}
|
||||
return &Client{cfg: cfg}
|
||||
}
|
||||
|
||||
// GetModelName returns the wire model name.
|
||||
func (c *Client) GetModelName() string { return c.cfg.Endpoint.Model }
|
||||
|
||||
// GetModelID returns WeKnora's model identifier.
|
||||
func (c *Client) GetModelID() string { return c.cfg.Endpoint.ModelID }
|
||||
|
||||
// requestURL builds {base}/models/{model}:generateContent or
|
||||
// {base}/models/{model}:streamGenerateContent?alt=sse. A bare host base URL
|
||||
// gets Settings.APIVersionPrefix appended; an already versioned base is used
|
||||
// as-is. An explicit Endpoint.URL overrides the path entirely.
|
||||
func (c *Client) requestURL(stream bool) string {
|
||||
ep := c.cfg.Endpoint
|
||||
if ep.URL == "" {
|
||||
base := strings.TrimRight(ep.BaseURL, "/")
|
||||
if prefix := strings.Trim(c.cfg.Settings.APIVersionPrefix, "/"); prefix != "" && isBareHost(base) {
|
||||
base += "/" + prefix
|
||||
}
|
||||
method := methodGenerate
|
||||
if stream {
|
||||
method = methodStreamGenerate
|
||||
}
|
||||
ep.URL = fmt.Sprintf("%s/models/%s:%s", base, ep.Model, method)
|
||||
} else if stream && strings.HasSuffix(ep.URL, ":"+methodGenerate) {
|
||||
// A vendor-supplied full URL names the non-streaming method; adding
|
||||
// alt=sse to it would still return one buffered JSON document.
|
||||
ep.URL = strings.TrimSuffix(ep.URL, ":"+methodGenerate) + ":" + methodStreamGenerate
|
||||
}
|
||||
if stream {
|
||||
query := make(map[string]string, len(ep.Query)+1)
|
||||
for k, v := range ep.Query {
|
||||
query[k] = v
|
||||
}
|
||||
query["alt"] = "sse"
|
||||
ep.Query = query
|
||||
}
|
||||
return ep.Resolve("")
|
||||
}
|
||||
|
||||
func isBareHost(base string) bool {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return !strings.Contains(strings.TrimPrefix(strings.TrimPrefix(base, "https://"), "http://"), "/")
|
||||
}
|
||||
return u.Path == "" || u.Path == "/"
|
||||
}
|
||||
|
||||
func (c *Client) send(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
|
||||
) (*http.Response, []byte, error) {
|
||||
body, err := c.BuildRequestBody(messages, opts, stream)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
target := c.requestURL(stream)
|
||||
req, data, err := c.cfg.Endpoint.NewRequest(ctx, target, body, stream)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
api.LogRequest(ctx, target, c.cfg.Endpoint.Model, data, stream)
|
||||
resp, err := c.cfg.Endpoint.Do(req)
|
||||
if err != nil {
|
||||
return nil, data, err
|
||||
}
|
||||
return resp, data, nil
|
||||
}
|
||||
|
||||
// Chat performs a non-streaming generation.
|
||||
func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Options) (*types.ChatResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultChatTimeout)
|
||||
defer cancel()
|
||||
|
||||
resp, _, err := c.send(ctx, messages, opts, false)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, _, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, false)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create chat completion: %w", err)
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
result, err := c.parseResponse(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api.LogUsage(ctx, c.cfg.Endpoint.Model, &result.Usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ChatStream performs a streaming generation over SSE.
|
||||
func (c *Client) ChatStream(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultStreamTimeout)
|
||||
|
||||
resp, data, err := c.send(ctx, messages, opts, true)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, fmt.Errorf("create chat completion stream: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ch := make(chan types.StreamResponse)
|
||||
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
|
||||
if dumper != nil {
|
||||
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
|
||||
}
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer close(ch)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if dumper != nil {
|
||||
defer dumper.Close()
|
||||
}
|
||||
c.processStream(ctx, resp.Body, ch, dumper)
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// --- response decoding ---
|
||||
|
||||
type rawFunctionCall struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Args json.RawMessage `json:"args,omitempty"`
|
||||
}
|
||||
|
||||
type rawPart struct {
|
||||
Text string `json:"text,omitempty"`
|
||||
Thought bool `json:"thought,omitempty"`
|
||||
ThoughtSignature string `json:"thoughtSignature,omitempty"`
|
||||
FunctionCall *rawFunctionCall `json:"functionCall,omitempty"`
|
||||
}
|
||||
|
||||
type rawCandidate struct {
|
||||
Content struct {
|
||||
Role string `json:"role,omitempty"`
|
||||
Parts []rawPart `json:"parts,omitempty"`
|
||||
} `json:"content"`
|
||||
FinishReason string `json:"finishReason,omitempty"`
|
||||
}
|
||||
|
||||
type rawUsage struct {
|
||||
PromptTokenCount int `json:"promptTokenCount"`
|
||||
CandidatesTokenCount int `json:"candidatesTokenCount"`
|
||||
ThoughtsTokenCount int `json:"thoughtsTokenCount"`
|
||||
TotalTokenCount int `json:"totalTokenCount"`
|
||||
CachedContentTokenCount *int `json:"cachedContentTokenCount"`
|
||||
}
|
||||
|
||||
type rawResponse struct {
|
||||
Candidates []rawCandidate `json:"candidates,omitempty"`
|
||||
PromptFeedback *struct {
|
||||
BlockReason string `json:"blockReason,omitempty"`
|
||||
} `json:"promptFeedback,omitempty"`
|
||||
UsageMetadata *rawUsage `json:"usageMetadata,omitempty"`
|
||||
Error *struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Status string `json:"status"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) usage(u rawUsage) types.TokenUsage {
|
||||
out := types.TokenUsage{
|
||||
PromptTokens: u.PromptTokenCount,
|
||||
CompletionTokens: u.CandidatesTokenCount + u.ThoughtsTokenCount,
|
||||
TotalTokens: u.TotalTokenCount,
|
||||
}
|
||||
if out.TotalTokens == 0 {
|
||||
out.TotalTokens = out.PromptTokens + out.CompletionTokens
|
||||
}
|
||||
switch {
|
||||
case u.CachedContentTokenCount != nil:
|
||||
cached := *u.CachedContentTokenCount
|
||||
out.SetPromptCacheUsage(cached, 0, max(0, u.PromptTokenCount-cached), true)
|
||||
case c.cfg.Settings.PromptCacheAcct:
|
||||
out.SetPromptCacheUsage(0, 0, 0, false)
|
||||
default:
|
||||
out.MarkPromptCacheUnsupported()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// toolCall lifts a functionCall part into the neutral tool call, minting an
|
||||
// id when the vendor sent none and keeping the thought signature as
|
||||
// provider metadata so it can be replayed verbatim.
|
||||
func (c *Client) toolCall(p rawPart) types.LLMToolCall {
|
||||
fc := p.FunctionCall
|
||||
id := fc.ID
|
||||
if id == "" {
|
||||
id = newCallID()
|
||||
}
|
||||
args := "{}"
|
||||
if len(fc.Args) > 0 && string(fc.Args) != "null" {
|
||||
args = string(fc.Args)
|
||||
}
|
||||
call := types.LLMToolCall{
|
||||
ID: id,
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: fc.Name, Arguments: args},
|
||||
}
|
||||
if p.ThoughtSignature != "" {
|
||||
sig, _ := json.Marshal(p.ThoughtSignature)
|
||||
call.ProviderMetadata = types.ToolCallMetadata{metadataThoughtSignature: sig}
|
||||
}
|
||||
return call
|
||||
}
|
||||
|
||||
func newCallID() string {
|
||||
var b [6]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "call_000000000000"
|
||||
}
|
||||
return "call_" + hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// mapFinishReason maps Gemini finish reasons onto the OpenAI vocabulary the
|
||||
// rest of the system understands.
|
||||
func mapFinishReason(reason string, hasToolCalls bool) string {
|
||||
switch reason {
|
||||
case "":
|
||||
return ""
|
||||
case "STOP":
|
||||
if hasToolCalls {
|
||||
return "tool_calls"
|
||||
}
|
||||
return "stop"
|
||||
case "MAX_TOKENS":
|
||||
return "length"
|
||||
case "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT":
|
||||
return "content_filter"
|
||||
default:
|
||||
return strings.ToLower(reason)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
|
||||
var env rawResponse
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
if env.Error != nil && env.Error.Message != "" {
|
||||
return nil, fmt.Errorf("API error: %s", env.Error.Message)
|
||||
}
|
||||
if len(env.Candidates) == 0 {
|
||||
if env.PromptFeedback != nil && env.PromptFeedback.BlockReason != "" {
|
||||
return nil, fmt.Errorf("blocked: %s", env.PromptFeedback.BlockReason)
|
||||
}
|
||||
return nil, fmt.Errorf("no response from API")
|
||||
}
|
||||
cand := env.Candidates[0]
|
||||
result := &types.ChatResponse{}
|
||||
var content, reasoning strings.Builder
|
||||
for _, p := range cand.Content.Parts {
|
||||
if p.ThoughtSignature != "" {
|
||||
result.ReasoningSignature = api.TagSignature(api.APIGoogleGenerativeAI, p.ThoughtSignature)
|
||||
}
|
||||
switch {
|
||||
case p.FunctionCall != nil:
|
||||
result.ToolCalls = append(result.ToolCalls, c.toolCall(p))
|
||||
case p.Thought:
|
||||
reasoning.WriteString(p.Text)
|
||||
default:
|
||||
content.WriteString(p.Text)
|
||||
}
|
||||
}
|
||||
result.Content = content.String()
|
||||
result.ReasoningContent = reasoning.String()
|
||||
result.FinishReason = mapFinishReason(cand.FinishReason, len(result.ToolCalls) > 0)
|
||||
// Classify the cache status even without usageMetadata: an empty
|
||||
// CacheStatus is indistinguishable from a miss downstream.
|
||||
usage := rawUsage{}
|
||||
if env.UsageMetadata != nil {
|
||||
usage = *env.UsageMetadata
|
||||
}
|
||||
result.Usage = c.usage(usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// processStream decodes the alt=sse stream: every data line carries a full
|
||||
// GenerateContentResponse chunk. Function calls arrive complete in one part;
|
||||
// they are fed to the assembler as a name delta followed by an arguments
|
||||
// delta so the early ResponseTypeToolCall notification fires as it does for
|
||||
// the fragment-based protocols.
|
||||
func (c *Client) processStream(
|
||||
ctx context.Context, body io.Reader, ch chan<- types.StreamResponse, dumper *api.StreamPacketDumper,
|
||||
) {
|
||||
assembler := api.NewStreamAssembler(ctx, c.cfg.Endpoint.Model)
|
||||
reader := api.NewSSEReader(body)
|
||||
toolIndex := 0
|
||||
|
||||
for {
|
||||
// The consumer went away (client disconnect, aborted agent turn): stop
|
||||
// decoding a stream nobody will read instead of spinning to EOF.
|
||||
if assembler.Aborted() {
|
||||
return
|
||||
}
|
||||
event, err := reader.ReadEvent()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
assembler.End(ch)
|
||||
} else {
|
||||
assembler.Fail(ch, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if event == nil {
|
||||
continue
|
||||
}
|
||||
if event.Done {
|
||||
assembler.End(ch)
|
||||
return
|
||||
}
|
||||
if len(event.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
if dumper != nil {
|
||||
raw := make([]byte, len(event.Data))
|
||||
copy(raw, event.Data)
|
||||
dumper.WritePacketRaw(raw)
|
||||
}
|
||||
|
||||
var env rawResponse
|
||||
if err := json.Unmarshal(event.Data, &env); err != nil {
|
||||
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
|
||||
return
|
||||
}
|
||||
if env.Error != nil && env.Error.Message != "" {
|
||||
assembler.Fail(ch, fmt.Errorf("API stream error: %s", env.Error.Message))
|
||||
return
|
||||
}
|
||||
if env.UsageMetadata != nil {
|
||||
assembler.SetUsage(c.usage(*env.UsageMetadata))
|
||||
}
|
||||
if len(env.Candidates) == 0 {
|
||||
if env.PromptFeedback != nil && env.PromptFeedback.BlockReason != "" {
|
||||
assembler.Fail(ch, fmt.Errorf("blocked: %s", env.PromptFeedback.BlockReason))
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
cand := env.Candidates[0]
|
||||
var delta api.Delta
|
||||
var calls []rawPart
|
||||
for _, p := range cand.Content.Parts {
|
||||
if p.ThoughtSignature != "" {
|
||||
assembler.ReasoningSignature = api.TagSignature(api.APIGoogleGenerativeAI, p.ThoughtSignature)
|
||||
}
|
||||
switch {
|
||||
case p.FunctionCall != nil:
|
||||
calls = append(calls, p)
|
||||
case p.Thought:
|
||||
delta.Reasoning += p.Text
|
||||
default:
|
||||
delta.Content += p.Text
|
||||
}
|
||||
}
|
||||
if delta.Reasoning != "" || delta.Content != "" {
|
||||
assembler.Process(ch, delta)
|
||||
}
|
||||
for _, p := range calls {
|
||||
call := c.toolCall(p)
|
||||
idx := toolIndex
|
||||
toolIndex++
|
||||
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
|
||||
Index: idx, ID: call.ID, Type: call.Type, Name: call.Function.Name,
|
||||
}}})
|
||||
if len(call.ProviderMetadata) > 0 {
|
||||
assembler.SetToolCallMetadata(idx, call.ProviderMetadata)
|
||||
}
|
||||
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
|
||||
Index: idx, Arguments: call.Function.Arguments,
|
||||
}}})
|
||||
}
|
||||
if cand.FinishReason != "" {
|
||||
assembler.Process(ch, api.Delta{FinishReason: mapFinishReason(cand.FinishReason, toolIndex > 0)})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,700 @@
|
|||
package googlegenai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func newTestClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {
|
||||
t.Helper()
|
||||
cfg := Config{
|
||||
Endpoint: api.Endpoint{
|
||||
BaseURL: baseURL,
|
||||
Model: "gemini-2.5-pro",
|
||||
ModelID: "model-123",
|
||||
Auth: api.HeaderAuth("x-goog-api-key", "test-key"),
|
||||
},
|
||||
Settings: catalog.DefaultGoogleGenerativeAI(),
|
||||
Reasoning: true,
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&cfg)
|
||||
}
|
||||
return New(cfg)
|
||||
}
|
||||
|
||||
// normalize round-trips a body through JSON so typed slices and ints compare
|
||||
// equal to a parsed expectation.
|
||||
func normalize(t *testing.T, v any) any {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var out any
|
||||
if err := json.Unmarshal(data, &out); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func parseJSON(t *testing.T, s string) any {
|
||||
t.Helper()
|
||||
var out any
|
||||
if err := json.Unmarshal([]byte(s), &out); err != nil {
|
||||
t.Fatalf("parse expected json: %v", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func goldenMessages() []api.Message {
|
||||
return []api.Message{
|
||||
{Role: "system", Content: "You are helpful."},
|
||||
{Role: "user", MultiContent: []api.MessageContentPart{
|
||||
{Type: "image_url", ImageURL: &api.ImageURL{URL: "data:image/png;base64,AAAA"}},
|
||||
{Type: "text", Text: "What is this?"},
|
||||
}},
|
||||
{Role: "assistant", ReasoningContent: "never replayed", ToolCalls: []api.ToolCall{
|
||||
{
|
||||
ID: "call_1",
|
||||
Type: "function",
|
||||
Function: api.FunctionCall{
|
||||
Name: "get_weather",
|
||||
Arguments: `{"city":"Paris"}`,
|
||||
},
|
||||
ProviderMetadata: types.ToolCallMetadata{"thought_signature": json.RawMessage(`"sig-1"`)},
|
||||
},
|
||||
{ID: "call_2", Type: "function", Function: api.FunctionCall{Name: "get_time", Arguments: ""}},
|
||||
}},
|
||||
{Role: "tool", ToolCallID: "call_1", Content: `{"temp": 20}`},
|
||||
{Role: "tool", ToolCallID: "call_2", Name: "get_time", Content: "noon"},
|
||||
}
|
||||
}
|
||||
|
||||
func goldenOptions() *api.Options {
|
||||
return &api.Options{
|
||||
Temperature: 0.7,
|
||||
MaxTokens: 1024,
|
||||
ReasoningEffort: api.ReasoningHigh,
|
||||
ToolChoice: "auto",
|
||||
Tools: []api.Tool{
|
||||
{Type: "function", Function: api.FunctionDef{
|
||||
Name: "get_weather",
|
||||
Description: "Weather",
|
||||
Parameters: json.RawMessage(`{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"title": "Weather",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"city": {"type": "string", "default": "Paris", "examples": ["Paris"]},
|
||||
"title": {"type": "string", "description": "a property named title"}
|
||||
},
|
||||
"required": ["city"]
|
||||
}`),
|
||||
}},
|
||||
{Type: "function", Function: api.FunctionDef{Name: "get_time", Description: "Time"}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const goldenBase = `{
|
||||
"systemInstruction": {"parts": [{"text": "You are helpful."}]},
|
||||
"contents": [
|
||||
{"role": "user", "parts": [
|
||||
{"inlineData": {"mimeType": "image/png", "data": "AAAA"}},
|
||||
{"text": "What is this?"}
|
||||
]},
|
||||
{"role": "model", "parts": [
|
||||
{"functionCall": {"id": "call_1", "name": "get_weather", "args": {"city": "Paris"}}, "thoughtSignature": "sig-1"},
|
||||
{"functionCall": {"id": "call_2", "name": "get_time", "args": {}}}
|
||||
]},
|
||||
{"role": "user", "parts": [
|
||||
{"functionResponse": {"id": "call_1", "name": "get_weather", "response": {"result": {"temp": 20}}}},
|
||||
{"functionResponse": {"id": "call_2", "name": "get_time", "response": {"result": "noon"}}}
|
||||
]}
|
||||
],
|
||||
"tools": [{"functionDeclarations": [
|
||||
{"name": "get_weather", "description": "Weather", "parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string"},
|
||||
"title": {"type": "string", "description": "a property named title"}
|
||||
},
|
||||
"required": ["city"]
|
||||
}},
|
||||
{"name": "get_time", "description": "Time"}
|
||||
]}],
|
||||
"toolConfig": {"functionCallingConfig": {"mode": "AUTO"}},
|
||||
"generationConfig": {
|
||||
"temperature": 0.7,
|
||||
"maxOutputTokens": 1024,
|
||||
"thinkingConfig": THINKING
|
||||
}
|
||||
}`
|
||||
|
||||
// TestThinkingConfigOmittedForNonReasoningModels guards models the catalog
|
||||
// does not mark as reasoning (gemini-2.0-flash, Gemma): they may reject any
|
||||
// thinkingConfig, including the thinkingBudget 0 an agent's default "off" maps to.
|
||||
func TestThinkingConfigOmittedForNonReasoningModels(t *testing.T) {
|
||||
client := newTestClient(t, "https://generativelanguage.googleapis.com",
|
||||
func(c *Config) { c.Reasoning = false })
|
||||
off := false
|
||||
body, err := client.BuildRequestBody(
|
||||
[]api.Message{{Role: "user", Content: "hi"}}, &api.Options{Thinking: &off}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gc, ok := body["generationConfig"].(map[string]any); ok {
|
||||
if _, has := gc["thinkingConfig"]; has {
|
||||
t.Fatalf("thinkingConfig sent for a non-reasoning model: %v", gc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestForeignSignatureNotReplayed guards cross-provider replay: a signature
|
||||
// issued by another protocol must never reach Gemini as thoughtSignature.
|
||||
func TestForeignSignatureNotReplayed(t *testing.T) {
|
||||
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
|
||||
body, err := client.BuildRequestBody([]api.Message{
|
||||
{Role: "user", Content: "hi"},
|
||||
{
|
||||
Role: "assistant", Content: "ok",
|
||||
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "claude-sig"),
|
||||
},
|
||||
{Role: "user", Content: "again"},
|
||||
}, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := json.Marshal(body)
|
||||
if strings.Contains(string(data), "claude-sig") {
|
||||
t.Fatalf("foreign signature replayed: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestBodyGolden(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Config)
|
||||
thinking string
|
||||
}{
|
||||
{
|
||||
name: "budget mode",
|
||||
thinking: `{"thinkingBudget": 24576, "includeThoughts": true}`,
|
||||
},
|
||||
{
|
||||
name: "level mode",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingMode = catalog.GoogleThinkingLevel
|
||||
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningHigh: api.StringPtr("high")}
|
||||
},
|
||||
thinking: `{"thinkingLevel": "high", "includeThoughts": true}`,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client := newTestClient(t, "https://generativelanguage.googleapis.com", tc.mutate)
|
||||
body, err := client.BuildRequestBody(goldenMessages(), goldenOptions(), false)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
expected := parseJSON(t, replaceThinking(goldenBase, tc.thinking))
|
||||
got := normalize(t, body)
|
||||
if !reflect.DeepEqual(got, expected) {
|
||||
gotJSON, _ := json.MarshalIndent(got, "", " ")
|
||||
wantJSON, _ := json.MarshalIndent(expected, "", " ")
|
||||
t.Fatalf("body mismatch\n got: %s\nwant: %s", gotJSON, wantJSON)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func replaceThinking(tmpl, thinking string) string {
|
||||
return strings.Replace(tmpl, "THINKING", thinking, 1)
|
||||
}
|
||||
|
||||
func TestThinkingConfigVariants(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Config)
|
||||
opts *api.Options
|
||||
want string // "" means no thinkingConfig
|
||||
}{
|
||||
{name: "not requested", opts: &api.Options{}, want: ""},
|
||||
{
|
||||
name: "budget off supported", opts: &api.Options{ReasoningEffort: api.ReasoningOff},
|
||||
want: `{"thinkingBudget": 0}`,
|
||||
},
|
||||
{
|
||||
name: "budget off unsupported",
|
||||
mutate: func(c *Config) { c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: nil} },
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningOff},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "budget auto", opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
|
||||
want: `{"thinkingBudget": -1, "includeThoughts": true}`,
|
||||
},
|
||||
{
|
||||
name: "budget explicit tokens",
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningLow, ThinkingBudgetTokens: 512},
|
||||
want: `{"thinkingBudget": 512, "includeThoughts": true}`,
|
||||
},
|
||||
{
|
||||
name: "mode none",
|
||||
mutate: func(c *Config) { c.Settings.ThinkingMode = catalog.GoogleThinkingNone },
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningHigh},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "level off unmapped",
|
||||
mutate: func(c *Config) { c.Settings.ThinkingMode = catalog.GoogleThinkingLevel },
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningOff},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "level auto",
|
||||
mutate: func(c *Config) { c.Settings.ThinkingMode = catalog.GoogleThinkingLevel },
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
|
||||
want: `{"includeThoughts": true}`,
|
||||
},
|
||||
{
|
||||
name: "level clamps unsupported rung",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingMode = catalog.GoogleThinkingLevel
|
||||
c.ThinkingLevels = api.ThinkingLevelMap{
|
||||
api.ReasoningMedium: nil,
|
||||
api.ReasoningHigh: api.StringPtr("high"),
|
||||
}
|
||||
},
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningMedium},
|
||||
want: `{"thinkingLevel": "high", "includeThoughts": true}`,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client := newTestClient(t, "https://generativelanguage.googleapis.com", tc.mutate)
|
||||
body, err := client.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, tc.opts, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got any
|
||||
if gen, ok := body["generationConfig"].(map[string]any); ok {
|
||||
if tcfg, ok := gen["thinkingConfig"]; ok {
|
||||
got = normalize(t, tcfg)
|
||||
}
|
||||
}
|
||||
var want any
|
||||
if tc.want != "" {
|
||||
want = parseJSON(t, tc.want)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("thinkingConfig = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolChoiceAndFormat(t *testing.T) {
|
||||
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
|
||||
opts := &api.Options{
|
||||
ToolChoice: "get_weather",
|
||||
Tools: []api.Tool{{Function: api.FunctionDef{Name: "get_weather"}}},
|
||||
Format: json.RawMessage(`{"type":"object"}`),
|
||||
}
|
||||
body, err := client.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, opts, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := normalize(t, body["toolConfig"])
|
||||
want := parseJSON(t, `{"functionCallingConfig": {"mode": "ANY", "allowedFunctionNames": ["get_weather"]}}`)
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("toolConfig = %v, want %v", got, want)
|
||||
}
|
||||
gen := body["generationConfig"].(map[string]any)
|
||||
if gen["responseMimeType"] != "application/json" {
|
||||
t.Fatalf("responseMimeType = %v", gen["responseMimeType"])
|
||||
}
|
||||
contents := body["contents"].([]map[string]any)
|
||||
text := contents[0]["parts"].([]part)[0]["text"].(string)
|
||||
if text != "hi\nUse this JSON schema: {\"type\":\"object\"}" {
|
||||
t.Fatalf("schema hint not appended: %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestURL(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
base string
|
||||
stream bool
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"bare host non-stream", "https://generativelanguage.googleapis.com", false,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
},
|
||||
{
|
||||
"bare host trailing slash stream", "https://generativelanguage.googleapis.com/", true,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
|
||||
},
|
||||
{
|
||||
"versioned base non-stream", "https://proxy.example.com/gemini/v1beta", false,
|
||||
"https://proxy.example.com/gemini/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
},
|
||||
{
|
||||
"versioned base stream", "https://proxy.example.com/v1beta/", true,
|
||||
"https://proxy.example.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client := newTestClient(t, tc.base, nil)
|
||||
if got := client.requestURL(tc.stream); got != tc.want {
|
||||
t.Fatalf("requestURL = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("explicit URL override", func(t *testing.T) {
|
||||
client := newTestClient(t, "https://ignored.example.com", func(c *Config) {
|
||||
c.Endpoint.URL = "https://custom.example.com/route:generateContent"
|
||||
})
|
||||
if got := client.requestURL(false); got != "https://custom.example.com/route:generateContent" {
|
||||
t.Fatalf("requestURL = %q", got)
|
||||
}
|
||||
// A streaming call must name the streaming method: ":generateContent"
|
||||
// answers with one buffered JSON document even with alt=sse, which the
|
||||
// SSE reader would see as an empty stream.
|
||||
want := "https://custom.example.com/route:streamGenerateContent?alt=sse"
|
||||
if got := client.requestURL(true); got != want {
|
||||
t.Fatalf("requestURL = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit URL override without a known method is left alone", func(t *testing.T) {
|
||||
client := newTestClient(t, "https://ignored.example.com", func(c *Config) {
|
||||
c.Endpoint.URL = "https://custom.example.com/route"
|
||||
})
|
||||
if got := client.requestURL(true); got != "https://custom.example.com/route?alt=sse" {
|
||||
t.Fatalf("requestURL = %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestChatDecodesResponse(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var gotPath, gotQuery, gotKey string
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
gotQuery = r.URL.RawQuery
|
||||
gotKey = r.Header.Get("x-goog-api-key")
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &gotBody)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"candidates": [{
|
||||
"content": {"role": "model", "parts": [
|
||||
{"text": "Thinking about Paris.", "thought": true, "thoughtSignature": "sig-thought"},
|
||||
{"text": "Let me check."},
|
||||
{"functionCall": {"id": "fc-1", "name": "get_weather", "args": {"city": "Paris"}},
|
||||
"thoughtSignature": "sig-fc"}
|
||||
]},
|
||||
"finishReason": "STOP"
|
||||
}],
|
||||
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "thoughtsTokenCount": 3,
|
||||
"totalTokenCount": 18, "cachedContentTokenCount": 4}
|
||||
}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := newTestClient(t, srv.URL, nil)
|
||||
resp, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "weather?"}}, &api.Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("Chat: %v", err)
|
||||
}
|
||||
if gotPath != "/v1beta/models/gemini-2.5-pro:generateContent" || gotQuery != "" {
|
||||
t.Fatalf("request path = %q query = %q", gotPath, gotQuery)
|
||||
}
|
||||
if gotKey != "test-key" {
|
||||
t.Fatalf("x-goog-api-key = %q", gotKey)
|
||||
}
|
||||
if _, ok := gotBody["contents"]; !ok {
|
||||
t.Fatalf("request body missing contents: %v", gotBody)
|
||||
}
|
||||
if resp.Content != "Let me check." {
|
||||
t.Fatalf("Content = %q", resp.Content)
|
||||
}
|
||||
if resp.ReasoningContent != "Thinking about Paris." {
|
||||
t.Fatalf("ReasoningContent = %q", resp.ReasoningContent)
|
||||
}
|
||||
if resp.ReasoningSignature != "google-generative-ai:sig-fc" {
|
||||
t.Fatalf("ReasoningSignature = %q", resp.ReasoningSignature)
|
||||
}
|
||||
if resp.FinishReason != "tool_calls" {
|
||||
t.Fatalf("FinishReason = %q", resp.FinishReason)
|
||||
}
|
||||
if len(resp.ToolCalls) != 1 {
|
||||
t.Fatalf("ToolCalls = %+v", resp.ToolCalls)
|
||||
}
|
||||
tc := resp.ToolCalls[0]
|
||||
if tc.ID != "fc-1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
|
||||
tc.Function.Arguments != `{"city": "Paris"}` {
|
||||
t.Fatalf("tool call = %+v", tc)
|
||||
}
|
||||
if string(tc.ProviderMetadata["thought_signature"]) != `"sig-fc"` {
|
||||
t.Fatalf("thought_signature = %s", tc.ProviderMetadata["thought_signature"])
|
||||
}
|
||||
u := resp.Usage
|
||||
if u.PromptTokens != 10 || u.CompletionTokens != 8 || u.TotalTokens != 18 {
|
||||
t.Fatalf("usage = %+v", u)
|
||||
}
|
||||
if u.CacheReadTokens != 4 || u.CacheMissTokens != 6 || !u.CacheReported ||
|
||||
u.CacheStatus != types.PromptCacheStatusHit {
|
||||
t.Fatalf("cache usage = %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatErrors(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"error payload", `{"error": {"code": 400, "message": "bad request", "status": "INVALID_ARGUMENT"}}`,
|
||||
"API error: bad request",
|
||||
},
|
||||
{"blocked prompt", `{"promptFeedback": {"blockReason": "SAFETY"}}`, "blocked: SAFETY"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
client := newTestClient(t, srv.URL, nil)
|
||||
_, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err == nil || err.Error() != tc.want {
|
||||
t.Fatalf("err = %v, want %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStreamDecodesSSE(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var gotPath, gotQuery string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
gotQuery = r.URL.RawQuery
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
chunks := []string{
|
||||
`{"candidates":[{"content":{"role":"model","parts":[{"text":"Let me think.","thought":true}]}}]}`,
|
||||
`{"candidates":[{"content":{"role":"model","parts":[{"text":"Checking "}]}}]}`,
|
||||
`{"candidates":[{"content":{"role":"model","parts":[{"text":"weather."}]}}]}`,
|
||||
`{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"get_weather",` +
|
||||
`"args":{"city":"Paris"}},"thoughtSignature":"sig-stream"}]},"finishReason":"STOP"}],` +
|
||||
`"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"thoughtsTokenCount":3,` +
|
||||
`"totalTokenCount":18}}`,
|
||||
}
|
||||
for _, c := range chunks {
|
||||
_, _ = w.Write([]byte("data: " + c + "\n\n"))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := newTestClient(t, srv.URL, nil)
|
||||
ch, err := client.ChatStream(context.Background(),
|
||||
[]api.Message{{Role: "user", Content: "weather?"}}, &api.Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var events []types.StreamResponse
|
||||
for ev := range ch {
|
||||
events = append(events, ev)
|
||||
}
|
||||
if gotPath != "/v1beta/models/gemini-2.5-pro:streamGenerateContent" || gotQuery != "alt=sse" {
|
||||
t.Fatalf("request path = %q query = %q", gotPath, gotQuery)
|
||||
}
|
||||
if len(events) == 0 {
|
||||
t.Fatal("no events")
|
||||
}
|
||||
|
||||
firstThinking, firstAnswer, toolCallEvent := -1, -1, -1
|
||||
var thinking, answer string
|
||||
for i, ev := range events {
|
||||
switch ev.ResponseType {
|
||||
case types.ResponseTypeThinking:
|
||||
if !ev.Done {
|
||||
if firstThinking < 0 {
|
||||
firstThinking = i
|
||||
}
|
||||
thinking += ev.Content
|
||||
}
|
||||
case types.ResponseTypeAnswer:
|
||||
if ev.Content != "" {
|
||||
if firstAnswer < 0 {
|
||||
firstAnswer = i
|
||||
}
|
||||
answer += ev.Content
|
||||
}
|
||||
case types.ResponseTypeToolCall:
|
||||
if toolCallEvent < 0 {
|
||||
toolCallEvent = i
|
||||
}
|
||||
if ev.Data["tool_name"] != "get_weather" || ev.Data["tool_call_id"] == "" {
|
||||
t.Fatalf("tool_call event data = %v", ev.Data)
|
||||
}
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("stream error: %s", ev.Content)
|
||||
}
|
||||
}
|
||||
if firstThinking < 0 || firstAnswer < 0 || firstThinking > firstAnswer {
|
||||
t.Fatalf("thinking (%d) must precede answer (%d)", firstThinking, firstAnswer)
|
||||
}
|
||||
if thinking != "Let me think." || answer != "Checking weather." {
|
||||
t.Fatalf("thinking = %q answer = %q", thinking, answer)
|
||||
}
|
||||
if toolCallEvent < 0 {
|
||||
t.Fatal("no ResponseTypeToolCall event")
|
||||
}
|
||||
|
||||
final := events[len(events)-1]
|
||||
if final.ResponseType != types.ResponseTypeAnswer || !final.Done {
|
||||
t.Fatalf("final event = %+v", final)
|
||||
}
|
||||
if final.FinishReason != "tool_calls" {
|
||||
t.Fatalf("final FinishReason = %q", final.FinishReason)
|
||||
}
|
||||
if final.Usage == nil || final.Usage.PromptTokens != 10 || final.Usage.CompletionTokens != 8 ||
|
||||
final.Usage.TotalTokens != 18 {
|
||||
t.Fatalf("final usage = %+v", final.Usage)
|
||||
}
|
||||
if final.Usage.CacheStatus != types.PromptCacheStatusUnreported || final.Usage.CacheReported {
|
||||
t.Fatalf("cache status = %+v", final.Usage)
|
||||
}
|
||||
if len(final.ToolCalls) != 1 {
|
||||
t.Fatalf("final tool calls = %+v", final.ToolCalls)
|
||||
}
|
||||
tc := final.ToolCalls[0]
|
||||
if tc.Function.Name != "get_weather" || tc.Function.Arguments != `{"city":"Paris"}` || tc.Type != "function" {
|
||||
t.Fatalf("tool call = %+v", tc)
|
||||
}
|
||||
if len(tc.ID) != len("call_")+12 || tc.ID[:5] != "call_" {
|
||||
t.Fatalf("generated tool call id = %q", tc.ID)
|
||||
}
|
||||
if string(tc.ProviderMetadata["thought_signature"]) != `"sig-stream"` {
|
||||
t.Fatalf("thought_signature = %s", tc.ProviderMetadata["thought_signature"])
|
||||
}
|
||||
if final.Data["reasoning_signature"] != "google-generative-ai:sig-stream" {
|
||||
t.Fatalf("Data = %v", final.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStreamErrorPayload(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte("data: {\"error\": {\"code\": 429, \"message\": \"quota exceeded\"}}\n\n"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := newTestClient(t, srv.URL, nil)
|
||||
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var last types.StreamResponse
|
||||
for ev := range ch {
|
||||
last = ev
|
||||
}
|
||||
if last.ResponseType != types.ResponseTypeError || last.Content != "API stream error: quota exceeded" {
|
||||
t.Fatalf("last event = %+v", last)
|
||||
}
|
||||
}
|
||||
|
||||
// "contents" is required and must be an array. A request that produced no
|
||||
// turns (only system prompts) used to marshal a nil slice as null, which
|
||||
// generateContent rejects with 400.
|
||||
func TestBuildRequestBodyContentsNeverNull(t *testing.T) {
|
||||
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
|
||||
for _, msgs := range [][]api.Message{nil, {{Role: "system", Content: "be brief"}}} {
|
||||
body, err := client.BuildRequestBody(msgs, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if strings.Contains(string(data), `"contents":null`) {
|
||||
t.Fatalf("contents marshalled as null: %s", data)
|
||||
}
|
||||
if !strings.Contains(string(data), `"contents":[]`) {
|
||||
t.Fatalf("contents not an empty array: %s", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without usageMetadata the cache status must still be classified, otherwise
|
||||
// "the vendor reported nothing" is indistinguishable from a real miss on the
|
||||
// usage dashboards.
|
||||
func TestChatClassifiesCacheStatusWithoutUsageMetadata(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},` +
|
||||
`"finishReason":"STOP"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := newTestClient(t, srv.URL, nil)
|
||||
resp, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Chat: %v", err)
|
||||
}
|
||||
if resp.Usage.CacheStatus == "" {
|
||||
t.Fatal("CacheStatus is empty; the usage block must still be classified")
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk that blocks the prompt mid-stream must surface as an error rather
|
||||
// than being skipped as "no candidates".
|
||||
func TestChatStreamSurfacesPromptFeedbackBlock(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"promptFeedback\":{\"blockReason\":\"SAFETY\"}}\n\n"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := newTestClient(t, srv.URL, nil)
|
||||
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var sawError bool
|
||||
for chunk := range ch {
|
||||
if chunk.ResponseType == types.ResponseTypeError {
|
||||
sawError = true
|
||||
if !strings.Contains(chunk.Content, "SAFETY") {
|
||||
t.Fatalf("error chunk = %q, want the block reason", chunk.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sawError {
|
||||
t.Fatal("blocked prompt did not produce an error chunk")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,524 @@
|
|||
// Package googlegenai implements the native Google Gemini generateContent
|
||||
// wire protocol (https://ai.google.dev/api/generate-content). Every
|
||||
// model-specific deviation is driven by catalog.GoogleGenerativeAISettings;
|
||||
// this package contains no vendor names beyond the protocol itself.
|
||||
package googlegenai
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
)
|
||||
|
||||
// Config is everything the client needs, already resolved by the catalog.
|
||||
type Config struct {
|
||||
Endpoint api.Endpoint
|
||||
Settings catalog.GoogleGenerativeAISettings
|
||||
// ThinkingLevels maps neutral levels to the vendor vocabulary
|
||||
// (thinkingLevel values for Gemini 3, "off" support for budget models).
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
// Reasoning marks a reasoning model. The Gemini protocol has no
|
||||
// role selection to gate on it; the field is informational and mirrors
|
||||
// the other protocol configs.
|
||||
Reasoning bool
|
||||
}
|
||||
|
||||
const (
|
||||
roleUser = "user"
|
||||
roleModel = "model"
|
||||
|
||||
// metadataThoughtSignature is the ToolCallMetadata key under which a
|
||||
// function call's thoughtSignature round-trips. Gemini 3 rejects a
|
||||
// replayed function call whose signature is missing or altered.
|
||||
metadataThoughtSignature = "thought_signature"
|
||||
|
||||
defaultImageMIME = "image/jpeg"
|
||||
)
|
||||
|
||||
type part = map[string]any
|
||||
|
||||
// convertMessages splits neutral messages into the system instruction text
|
||||
// and the Gemini contents array. Consecutive tool results are merged into one
|
||||
// user content carrying several functionResponse parts, as Gemini requires
|
||||
// every functionCall of a model turn to be answered in the next content.
|
||||
func (c *Client) convertMessages(messages []api.Message) (system []string, contents []map[string]any) {
|
||||
toolNames := map[string]string{}
|
||||
openToolBatch := -1 // index in contents of the functionResponse content being filled
|
||||
for _, msg := range messages {
|
||||
msg = api.NeutralizeMessageSpecialTokens(msg)
|
||||
switch msg.Role {
|
||||
case "system":
|
||||
if text := systemText(msg); text != "" {
|
||||
system = append(system, text)
|
||||
}
|
||||
case "assistant":
|
||||
for _, tc := range msg.ToolCalls {
|
||||
if tc.ID != "" {
|
||||
toolNames[tc.ID] = tc.Function.Name
|
||||
}
|
||||
}
|
||||
contents = append(contents, map[string]any{"role": roleModel, "parts": assistantParts(msg)})
|
||||
case "tool":
|
||||
p := toolResultPart(msg, toolNames)
|
||||
if openToolBatch >= 0 && openToolBatch == len(contents)-1 {
|
||||
batch := contents[openToolBatch]
|
||||
batch["parts"] = append(batch["parts"].([]part), p)
|
||||
continue
|
||||
}
|
||||
contents = append(contents, map[string]any{"role": roleUser, "parts": []part{p}})
|
||||
openToolBatch = len(contents) - 1
|
||||
default:
|
||||
contents = append(contents, map[string]any{"role": roleUser, "parts": userParts(msg)})
|
||||
}
|
||||
}
|
||||
return system, contents
|
||||
}
|
||||
|
||||
func systemText(msg api.Message) string {
|
||||
if len(msg.MultiContent) == 0 {
|
||||
return msg.Content
|
||||
}
|
||||
var texts []string
|
||||
for _, p := range msg.MultiContent {
|
||||
if p.Type == "text" && p.Text != "" {
|
||||
texts = append(texts, p.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(texts, "\n")
|
||||
}
|
||||
|
||||
// userParts renders a user turn. Legacy Message.Images are emitted before the
|
||||
// text part, matching the Chat Completions package.
|
||||
func userParts(msg api.Message) []part {
|
||||
var parts []part
|
||||
switch {
|
||||
case len(msg.MultiContent) > 0:
|
||||
for _, p := range msg.MultiContent {
|
||||
switch p.Type {
|
||||
case "text":
|
||||
if p.Text != "" {
|
||||
parts = append(parts, part{"text": p.Text})
|
||||
}
|
||||
case "image_url":
|
||||
if p.ImageURL != nil {
|
||||
if ip := imagePart(p.ImageURL.URL); ip != nil {
|
||||
parts = append(parts, ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case len(msg.Images) > 0:
|
||||
for _, img := range msg.Images {
|
||||
if ip := imagePart(img); ip != nil {
|
||||
parts = append(parts, ip)
|
||||
}
|
||||
}
|
||||
parts = append(parts, part{"text": msg.Content})
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
parts = append(parts, part{"text": msg.Content})
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
// assistantParts renders a model turn: the answer text (carrying the thought
|
||||
// signature when the turn had no function calls) followed by one functionCall
|
||||
// part per tool call, each replaying its own thought signature. Reasoning
|
||||
// text is never replayed as a thought part: Gemini only needs signatures.
|
||||
func assistantParts(msg api.Message) []part {
|
||||
var parts []part
|
||||
if msg.Content != "" || len(msg.ToolCalls) == 0 {
|
||||
p := part{"text": msg.Content}
|
||||
sig := api.SignatureFor(api.APIGoogleGenerativeAI, msg.ReasoningSignature)
|
||||
if sig != "" && len(msg.ToolCalls) == 0 {
|
||||
p["thoughtSignature"] = sig
|
||||
}
|
||||
parts = append(parts, p)
|
||||
}
|
||||
for _, tc := range msg.ToolCalls {
|
||||
fc := map[string]any{
|
||||
"name": tc.Function.Name,
|
||||
"args": parseArgs(tc.Function.Arguments),
|
||||
}
|
||||
if tc.ID != "" {
|
||||
fc["id"] = tc.ID
|
||||
}
|
||||
p := part{"functionCall": fc}
|
||||
if sig := thoughtSignatureFromMetadata(tc.ProviderMetadata); sig != "" {
|
||||
p["thoughtSignature"] = sig
|
||||
}
|
||||
parts = append(parts, p)
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
// toolResultPart renders a tool result as a functionResponse part. The tool
|
||||
// name comes from the message or, failing that, from the assistant turn that
|
||||
// issued the call.
|
||||
func toolResultPart(msg api.Message, toolNames map[string]string) part {
|
||||
name := msg.Name
|
||||
if name == "" {
|
||||
name = toolNames[msg.ToolCallID]
|
||||
}
|
||||
fr := map[string]any{
|
||||
"name": name,
|
||||
"response": map[string]any{"result": decodeToolResult(msg.Content)},
|
||||
}
|
||||
if msg.ToolCallID != "" {
|
||||
fr["id"] = msg.ToolCallID
|
||||
}
|
||||
return part{"functionResponse": fr}
|
||||
}
|
||||
|
||||
// decodeToolResult returns the tool output as a JSON value when it is a JSON
|
||||
// object or array, otherwise the raw string.
|
||||
func decodeToolResult(content string) any {
|
||||
trimmed := strings.TrimSpace(content)
|
||||
if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") {
|
||||
var v any
|
||||
if err := json.Unmarshal([]byte(trimmed), &v); err == nil {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
// parseArgs decodes a tool call's JSON arguments into the object Gemini
|
||||
// expects; anything that is not a JSON object becomes an empty object.
|
||||
func parseArgs(arguments string) map[string]any {
|
||||
args := map[string]any{}
|
||||
if strings.TrimSpace(arguments) == "" {
|
||||
return args
|
||||
}
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil || args == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func thoughtSignatureFromMetadata(md map[string]json.RawMessage) string {
|
||||
raw, ok := md[metadataThoughtSignature]
|
||||
if !ok || len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
var sig string
|
||||
if err := json.Unmarshal(raw, &sig); err != nil {
|
||||
return ""
|
||||
}
|
||||
return sig
|
||||
}
|
||||
|
||||
// imagePart renders an image reference. Stored images are resolved to data
|
||||
// URIs first; data URIs become inlineData, everything else is passed as
|
||||
// fileData with a MIME type guessed from the extension.
|
||||
func imagePart(ref string) part {
|
||||
resolved := api.ResolveImageURLForLLM(ref)
|
||||
if strings.HasPrefix(resolved, "data:") {
|
||||
mimeType, data, ok := parseDataURI(resolved)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return part{"inlineData": map[string]any{"mimeType": mimeType, "data": data}}
|
||||
}
|
||||
return part{"fileData": map[string]any{"mimeType": guessImageMIME(resolved), "fileUri": resolved}}
|
||||
}
|
||||
|
||||
// parseDataURI splits "data:<mime>[;base64],<payload>" into the MIME type and
|
||||
// the base64 payload Gemini wants. Non-base64 payloads are re-encoded.
|
||||
func parseDataURI(uri string) (mimeType, data string, ok bool) {
|
||||
comma := strings.Index(uri, ",")
|
||||
if comma < 0 {
|
||||
return "", "", false
|
||||
}
|
||||
header := uri[len("data:"):comma]
|
||||
payload := uri[comma+1:]
|
||||
isBase64 := false
|
||||
if strings.HasSuffix(header, ";base64") {
|
||||
header = strings.TrimSuffix(header, ";base64")
|
||||
isBase64 = true
|
||||
}
|
||||
mimeType = header
|
||||
if idx := strings.Index(mimeType, ";"); idx >= 0 {
|
||||
mimeType = mimeType[:idx]
|
||||
}
|
||||
if mimeType == "" {
|
||||
mimeType = defaultImageMIME
|
||||
}
|
||||
if isBase64 {
|
||||
return mimeType, payload, true
|
||||
}
|
||||
decoded, err := url.PathUnescape(payload)
|
||||
if err != nil {
|
||||
decoded = payload
|
||||
}
|
||||
return mimeType, base64.StdEncoding.EncodeToString([]byte(decoded)), true
|
||||
}
|
||||
|
||||
func guessImageMIME(ref string) string {
|
||||
ext := path.Ext(ref)
|
||||
if u, err := url.Parse(ref); err == nil && u.Path != "" {
|
||||
ext = path.Ext(u.Path)
|
||||
}
|
||||
if ext != "" {
|
||||
if mt := mime.TypeByExtension(strings.ToLower(ext)); strings.HasPrefix(mt, "image/") {
|
||||
return mt
|
||||
}
|
||||
}
|
||||
return defaultImageMIME
|
||||
}
|
||||
|
||||
// buildBody assembles the generateContent request body. The body is the
|
||||
// same for streaming and non-streaming calls; streaming is selected by the
|
||||
// URL. It returns nested maps so golden tests can inspect it.
|
||||
func (c *Client) buildBody(messages []api.Message, opts *api.Options) (map[string]any, error) {
|
||||
s := c.cfg.Settings
|
||||
system, contents := c.convertMessages(messages)
|
||||
if contents == nil {
|
||||
// "contents" is required and must be an array: a nil slice marshals to
|
||||
// null and generateContent answers 400. A request carrying only system
|
||||
// messages legitimately produces no turns.
|
||||
contents = []map[string]any{}
|
||||
}
|
||||
body := map[string]any{"contents": contents}
|
||||
if len(system) > 0 {
|
||||
body["systemInstruction"] = map[string]any{
|
||||
"parts": []part{{"text": strings.Join(system, "\n\n")}},
|
||||
}
|
||||
}
|
||||
|
||||
gen := map[string]any{}
|
||||
if opts != nil {
|
||||
c.applySampling(gen, opts)
|
||||
if budget := opts.CompletionBudget(); budget > 0 {
|
||||
gen["maxOutputTokens"] = budget
|
||||
}
|
||||
c.applyTools(body, opts)
|
||||
if len(opts.Format) > 0 {
|
||||
gen["responseMimeType"] = "application/json"
|
||||
appendSchemaHint(contents, opts.Format)
|
||||
}
|
||||
if tc := c.thinkingConfig(opts); tc != nil {
|
||||
gen["thinkingConfig"] = tc
|
||||
}
|
||||
}
|
||||
for k, v := range s.ExtraGeneration {
|
||||
if _, exists := gen[k]; !exists {
|
||||
gen[k] = v
|
||||
}
|
||||
}
|
||||
if len(gen) > 0 {
|
||||
body["generationConfig"] = gen
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (c *Client) applySampling(gen map[string]any, opts *api.Options) {
|
||||
s := c.cfg.Settings
|
||||
if opts.Temperature > 0 {
|
||||
gen["temperature"] = opts.Temperature
|
||||
}
|
||||
if opts.TopP > 0 {
|
||||
gen["topP"] = opts.TopP
|
||||
}
|
||||
if opts.Seed > 0 && s.SupportsSeed {
|
||||
gen["seed"] = opts.Seed
|
||||
}
|
||||
if s.SupportsPenalty {
|
||||
if opts.FrequencyPenalty > 0 {
|
||||
gen["frequencyPenalty"] = opts.FrequencyPenalty
|
||||
}
|
||||
if opts.PresencePenalty > 0 {
|
||||
gen["presencePenalty"] = opts.PresencePenalty
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
|
||||
if len(opts.Tools) == 0 {
|
||||
return
|
||||
}
|
||||
decls := make([]map[string]any, 0, len(opts.Tools))
|
||||
for _, tool := range opts.Tools {
|
||||
decl := map[string]any{
|
||||
"name": tool.Function.Name,
|
||||
"description": tool.Function.Description,
|
||||
}
|
||||
if schema := sanitizeParameters(tool.Function.Parameters); schema != nil {
|
||||
decl["parameters"] = schema
|
||||
}
|
||||
decls = append(decls, decl)
|
||||
}
|
||||
body["tools"] = []map[string]any{{"functionDeclarations": decls}}
|
||||
|
||||
if opts.ToolChoice == "" {
|
||||
return
|
||||
}
|
||||
cfg := map[string]any{}
|
||||
switch opts.ToolChoice {
|
||||
case "auto":
|
||||
cfg["mode"] = "AUTO"
|
||||
case "required":
|
||||
cfg["mode"] = "ANY"
|
||||
case "none":
|
||||
cfg["mode"] = "NONE"
|
||||
default:
|
||||
cfg["mode"] = "ANY"
|
||||
cfg["allowedFunctionNames"] = []string{opts.ToolChoice}
|
||||
}
|
||||
body["toolConfig"] = map[string]any{"functionCallingConfig": cfg}
|
||||
}
|
||||
|
||||
// unsupportedSchemaKeys are JSON Schema members the Gemini Schema type
|
||||
// rejects. They are stripped recursively; property names are never touched.
|
||||
var unsupportedSchemaKeys = map[string]bool{
|
||||
"$schema": true,
|
||||
"$id": true,
|
||||
"$ref": true,
|
||||
"$defs": true,
|
||||
"definitions": true,
|
||||
"additionalProperties": true,
|
||||
"default": true,
|
||||
"examples": true,
|
||||
"title": true,
|
||||
}
|
||||
|
||||
// sanitizeParameters decodes a tool's JSON schema and strips the members
|
||||
// Gemini does not accept. Empty or undecodable schemas yield nil.
|
||||
func sanitizeParameters(raw json.RawMessage) any {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
var schema any
|
||||
if err := json.Unmarshal(raw, &schema); err != nil {
|
||||
return nil
|
||||
}
|
||||
if _, ok := schema.(map[string]any); !ok {
|
||||
return nil
|
||||
}
|
||||
return sanitizeSchema(schema)
|
||||
}
|
||||
|
||||
func sanitizeSchema(v any) any {
|
||||
switch t := v.(type) {
|
||||
case map[string]any:
|
||||
out := make(map[string]any, len(t))
|
||||
for k, val := range t {
|
||||
if unsupportedSchemaKeys[k] {
|
||||
continue
|
||||
}
|
||||
if k == "properties" {
|
||||
if props, ok := val.(map[string]any); ok {
|
||||
cleaned := make(map[string]any, len(props))
|
||||
for name, sub := range props {
|
||||
cleaned[name] = sanitizeSchema(sub)
|
||||
}
|
||||
out[k] = cleaned
|
||||
continue
|
||||
}
|
||||
}
|
||||
out[k] = sanitizeSchema(val)
|
||||
}
|
||||
return out
|
||||
case []any:
|
||||
for i := range t {
|
||||
t[i] = sanitizeSchema(t[i])
|
||||
}
|
||||
return t
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// appendSchemaHint appends the JSON schema instruction to the last user text
|
||||
// part, mirroring the Chat Completions package.
|
||||
func appendSchemaHint(contents []map[string]any, format json.RawMessage) {
|
||||
hint := fmt.Sprintf("\nUse this JSON schema: %s", format)
|
||||
for i := len(contents) - 1; i >= 0; i-- {
|
||||
if contents[i]["role"] != roleUser {
|
||||
continue
|
||||
}
|
||||
parts, _ := contents[i]["parts"].([]part)
|
||||
for j := len(parts) - 1; j >= 0; j-- {
|
||||
if text, ok := parts[j]["text"].(string); ok {
|
||||
parts[j]["text"] = text + hint
|
||||
return
|
||||
}
|
||||
}
|
||||
contents[i]["parts"] = append(parts, part{"text": strings.TrimPrefix(hint, "\n")})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// thinkingConfig encodes the requested reasoning level in the shape the
|
||||
// model generation supports: thinkingBudget (Gemini 2.5) or thinkingLevel
|
||||
// (Gemini 3). nil means "send no thinkingConfig".
|
||||
func (c *Client) thinkingConfig(opts *api.Options) map[string]any {
|
||||
s := c.cfg.Settings
|
||||
levels := c.cfg.ThinkingLevels
|
||||
level, requested := opts.Reasoning()
|
||||
// Models the catalog does not mark as reasoning (gemini-2.0-flash, Gemma,
|
||||
// unknown ids) may reject thinkingConfig outright, so send none.
|
||||
if !requested || !c.cfg.Reasoning {
|
||||
return nil
|
||||
}
|
||||
mode := s.ThinkingMode
|
||||
if mode == "" {
|
||||
mode = catalog.GoogleThinkingBudget
|
||||
}
|
||||
switch mode {
|
||||
case catalog.GoogleThinkingBudget:
|
||||
switch level {
|
||||
case api.ReasoningOff:
|
||||
if levels.Supports(api.ReasoningOff) {
|
||||
return map[string]any{"thinkingBudget": 0}
|
||||
}
|
||||
return nil
|
||||
case api.ReasoningAuto:
|
||||
return map[string]any{"thinkingBudget": -1, "includeThoughts": s.IncludeThoughts}
|
||||
default:
|
||||
level = levels.Clamp(level)
|
||||
budget := opts.ThinkingBudgetTokens
|
||||
if budget <= 0 {
|
||||
if b, ok := s.ThinkingBudgets[level]; ok && level.Graded() {
|
||||
budget = b
|
||||
} else {
|
||||
budget = -1
|
||||
}
|
||||
}
|
||||
return map[string]any{"thinkingBudget": budget, "includeThoughts": s.IncludeThoughts}
|
||||
}
|
||||
case catalog.GoogleThinkingLevel:
|
||||
switch level {
|
||||
case api.ReasoningOff:
|
||||
// Gemini 3 cannot switch thinking off; only send a level when the
|
||||
// vendor explicitly mapped "off" to a wire value.
|
||||
if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
|
||||
return map[string]any{"thinkingLevel": *v}
|
||||
}
|
||||
return nil
|
||||
case api.ReasoningAuto:
|
||||
return map[string]any{"includeThoughts": s.IncludeThoughts}
|
||||
default:
|
||||
level = levels.Clamp(level)
|
||||
if !level.Graded() {
|
||||
return map[string]any{"includeThoughts": s.IncludeThoughts}
|
||||
}
|
||||
return map[string]any{"thinkingLevel": levels.Value(level), "includeThoughts": s.IncludeThoughts}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// BuildRequestBody is the golden-test entry point: it returns the exact
|
||||
// JSON object that would be sent for the given inputs. The stream flag is
|
||||
// accepted for interface parity; Gemini selects streaming through the URL.
|
||||
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
_ = stream
|
||||
return c.buildBody(messages, opts)
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ResolveImageURLForLLM converts stored image paths to a format that LLM APIs can consume.
|
||||
// - data: URIs and http(s):// URLs are returned as-is.
|
||||
// - resource:// and provider-backed local paths are read through the
|
||||
// application resolver and converted to base64 data URIs.
|
||||
func ResolveImageURLForLLM(imageURL string) string {
|
||||
if strings.HasPrefix(imageURL, "data:") ||
|
||||
strings.HasPrefix(imageURL, "http://") ||
|
||||
strings.HasPrefix(imageURL, "https://") {
|
||||
return imageURL
|
||||
}
|
||||
if isApplicationStoredImage(imageURL) {
|
||||
data := readLocalStorageBytes(imageURL)
|
||||
if data != nil {
|
||||
mime := http.DetectContentType(data)
|
||||
return fmt.Sprintf("data:%s;base64,%s", mime, base64.StdEncoding.EncodeToString(data))
|
||||
}
|
||||
}
|
||||
return imageURL
|
||||
}
|
||||
|
||||
// ResolveImageURLForOllama converts stored image paths to raw bytes for the Ollama API.
|
||||
func ResolveImageURLForOllama(imageURL string) []byte {
|
||||
if strings.HasPrefix(imageURL, "data:") {
|
||||
idx := strings.Index(imageURL, ";base64,")
|
||||
if idx < 0 {
|
||||
return nil
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(imageURL[idx+8:])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
if isApplicationStoredImage(imageURL) {
|
||||
return readLocalStorageBytes(imageURL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isApplicationStoredImage(imageURL string) bool {
|
||||
return strings.HasPrefix(imageURL, "resource://") ||
|
||||
strings.HasPrefix(imageURL, "local://") ||
|
||||
strings.HasPrefix(imageURL, "storage://")
|
||||
}
|
||||
|
||||
// LocalImageResolver resolves a resource:// or provider storage URL to bytes
|
||||
// using the owning tenant's storage config. The application layer sets it at
|
||||
// startup.
|
||||
// Stored local:// URLs are relative to the storage base dir and do NOT encode
|
||||
// the tenant's configured PathPrefix, so a plain env-based join would miss the
|
||||
// prefix. When nil (e.g. in tests), callers fall back to the env-based
|
||||
// LOCAL_STORAGE_BASE_DIR resolution below.
|
||||
var LocalImageResolver func(storageURL string) ([]byte, bool)
|
||||
|
||||
// readLocalStorageBytes resolves a local:// storage path to disk bytes.
|
||||
func readLocalStorageBytes(storagePath string) []byte {
|
||||
if LocalImageResolver != nil {
|
||||
if data, ok := LocalImageResolver(storagePath); ok {
|
||||
return data
|
||||
}
|
||||
}
|
||||
relPath := strings.TrimPrefix(storagePath, "local://")
|
||||
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
|
||||
if baseDir == "" {
|
||||
baseDir = "/data/files"
|
||||
}
|
||||
localPath := filepath.Join(baseDir, filepath.FromSlash(relPath))
|
||||
data, err := os.ReadFile(localPath)
|
||||
if err != nil {
|
||||
log.Printf("[image-resolve] failed to read local file %s: %v", localPath, err)
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// IsMultimodalNotSupportedError checks if an error indicates the model does not
|
||||
// support multimodal/image input.
|
||||
//
|
||||
// The status is read off the error, never matched as text: HTTPError.Error()
|
||||
// prints "status 400" for every 400, and vendor bodies carry "400" inside
|
||||
// unrelated numbers ("max 4000 px"), so a substring test turned any failure
|
||||
// that merely mentions an image into a "model is not multimodal" verdict and
|
||||
// silently retried it stripped.
|
||||
func IsMultimodalNotSupportedError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
mentionsImages := strings.Contains(msg, "multimodal") ||
|
||||
strings.Contains(msg, "image") ||
|
||||
strings.Contains(msg, "vision")
|
||||
if !mentionsImages {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(msg, "not support") || strings.Contains(msg, "unsupported") {
|
||||
return true
|
||||
}
|
||||
// No explicit wording: only a genuine 400 (the status vendors use to reject
|
||||
// an input their model cannot read) is worth a stripped retry.
|
||||
var httpErr *HTTPError
|
||||
return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusBadRequest
|
||||
}
|
||||
|
||||
// StripImagesFromMessages returns a copy of messages with all image data removed.
|
||||
//
|
||||
// Images travel in two shapes: the Images list (chat history, Ollama) and
|
||||
// image_url parts inside MultiContent, which is what the remote VLM path and
|
||||
// every assembled multimodal turn actually send. Clearing only the first left
|
||||
// the retry sending the identical request, so the "retry without images"
|
||||
// fallback never recovered anything on those paths.
|
||||
func StripImagesFromMessages(messages []Message) []Message {
|
||||
cleaned := make([]Message, len(messages))
|
||||
for i, msg := range messages {
|
||||
cleaned[i] = msg
|
||||
cleaned[i].Images = nil
|
||||
cleaned[i].MultiContent = stripImageParts(msg.MultiContent)
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
// stripImageParts drops image parts from one MultiContent list, copying it
|
||||
// only when there is something to drop so the caller's slice is never mutated.
|
||||
// A list that was nothing but images becomes nil: the protocol packages then
|
||||
// fall back to the message's plain Content instead of sending an empty parts
|
||||
// array, which some vendors reject.
|
||||
func stripImageParts(parts []MessageContentPart) []MessageContentPart {
|
||||
if len(parts) == 0 {
|
||||
return parts
|
||||
}
|
||||
kept := make([]MessageContentPart, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if part.Type == "image_url" || part.ImageURL != nil {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, part)
|
||||
}
|
||||
if len(kept) == len(parts) {
|
||||
return parts
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
return nil
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The remote VLM path sends its pictures as image_url parts in MultiContent,
|
||||
// not in Images, so a strip that only cleared Images re-sent the identical
|
||||
// request and the "retry without images" fallback could never succeed.
|
||||
func TestStripImagesFromMessages_RemovesMultiContentImageParts(t *testing.T) {
|
||||
messages := []Message{{
|
||||
Role: "user",
|
||||
Images: []string{"data:image/png;base64,AAA"},
|
||||
MultiContent: []MessageContentPart{
|
||||
{Type: "text", Text: "describe this"},
|
||||
{Type: "image_url", ImageURL: &ImageURL{URL: "data:image/png;base64,AAA"}},
|
||||
},
|
||||
}}
|
||||
|
||||
cleaned := StripImagesFromMessages(messages)
|
||||
|
||||
if cleaned[0].Images != nil {
|
||||
t.Errorf("Images = %v, want nil", cleaned[0].Images)
|
||||
}
|
||||
if len(cleaned[0].MultiContent) != 1 || cleaned[0].MultiContent[0].Type != "text" {
|
||||
t.Fatalf("MultiContent = %#v, want the text part only", cleaned[0].MultiContent)
|
||||
}
|
||||
// The caller's slice must survive: the retry is built from the same
|
||||
// messages the first attempt used.
|
||||
if len(messages[0].MultiContent) != 2 || len(messages[0].Images) != 1 {
|
||||
t.Fatalf("input mutated: %#v", messages[0])
|
||||
}
|
||||
}
|
||||
|
||||
// An images-only turn loses MultiContent entirely rather than going out as an
|
||||
// empty parts array, which some vendors reject.
|
||||
func TestStripImagesFromMessages_DropsEmptiedMultiContent(t *testing.T) {
|
||||
cleaned := StripImagesFromMessages([]Message{{
|
||||
Role: "user",
|
||||
Content: "what is this",
|
||||
MultiContent: []MessageContentPart{
|
||||
{Type: "image_url", ImageURL: &ImageURL{URL: "https://example.com/a.png"}},
|
||||
},
|
||||
}})
|
||||
if cleaned[0].MultiContent != nil {
|
||||
t.Fatalf("MultiContent = %#v, want nil", cleaned[0].MultiContent)
|
||||
}
|
||||
if cleaned[0].Content != "what is this" {
|
||||
t.Fatalf("Content = %q, want it untouched", cleaned[0].Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsMultimodalNotSupportedError(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "explicit wording, no status",
|
||||
err: fmt.Errorf("this model does not support image input"),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "400 rejecting the image",
|
||||
err: &HTTPError{StatusCode: 400, Body: `{"error":"invalid content type image_url"}`},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "wrapped 400 still matches",
|
||||
err: fmt.Errorf("create chat completion: %w",
|
||||
&HTTPError{StatusCode: 400, Body: "image input rejected"}),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
// The old substring test fired here: HTTPError.Error() prints the
|
||||
// status, so every 5xx mentioning an image looked like "model is
|
||||
// not multimodal" and was retried stripped.
|
||||
name: "server error mentioning an image is not a capability verdict",
|
||||
err: &HTTPError{StatusCode: 500, Body: "image upload backend unavailable"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
// "400" also hides inside ordinary numbers in vendor bodies.
|
||||
name: "429 whose body merely contains 400",
|
||||
err: &HTTPError{StatusCode: 429, Body: "image exceeds 4000 px, slow down"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "unrelated failure",
|
||||
err: fmt.Errorf("context deadline exceeded"),
|
||||
want: false,
|
||||
},
|
||||
{name: "nil", err: nil, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := IsMultimodalNotSupportedError(tc.err); got != tc.want {
|
||||
t.Errorf("IsMultimodalNotSupportedError(%v) = %v, want %v", tc.err, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,16 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// jsonFieldExtractor extracts a specific string field value from streaming JSON fragments.
|
||||
// JSONFieldExtractor extracts a specific string field value from streaming JSON fragments.
|
||||
// It processes incremental JSON argument chunks from LLM tool calls.
|
||||
//
|
||||
// Example: for fieldName="answer", expected JSON format: {"answer":"...content..."}
|
||||
// The extractor uses a simple state machine to skip the JSON prefix and extract the string value.
|
||||
type jsonFieldExtractor struct {
|
||||
type JSONFieldExtractor struct {
|
||||
fieldName string // the JSON field name to extract (e.g. "answer", "thought")
|
||||
buffer string // accumulated full arguments string
|
||||
valueStart int // byte offset where the field value starts (-1 if not found yet)
|
||||
|
|
@ -18,9 +18,9 @@ type jsonFieldExtractor struct {
|
|||
done bool // whether we've seen the closing quote
|
||||
}
|
||||
|
||||
// newJSONFieldExtractor creates a new extractor instance for the given field name
|
||||
func newJSONFieldExtractor(fieldName string) *jsonFieldExtractor {
|
||||
return &jsonFieldExtractor{
|
||||
// NewJSONFieldExtractor creates a new extractor instance for the given field name
|
||||
func NewJSONFieldExtractor(fieldName string) *JSONFieldExtractor {
|
||||
return &JSONFieldExtractor{
|
||||
fieldName: fieldName,
|
||||
valueStart: -1,
|
||||
lastEmit: 0,
|
||||
|
|
@ -29,7 +29,7 @@ func newJSONFieldExtractor(fieldName string) *jsonFieldExtractor {
|
|||
|
||||
// Feed processes a new argument delta and returns any new content to emit.
|
||||
// Returns empty string if no new content is available yet.
|
||||
func (e *jsonFieldExtractor) Feed(argsDelta string) string {
|
||||
func (e *JSONFieldExtractor) Feed(argsDelta string) string {
|
||||
if e.done {
|
||||
return ""
|
||||
}
|
||||
|
|
@ -72,7 +72,7 @@ func (e *jsonFieldExtractor) Feed(argsDelta string) string {
|
|||
}
|
||||
|
||||
// IsDone returns whether the extractor has finished (closing quote found)
|
||||
func (e *jsonFieldExtractor) IsDone() bool {
|
||||
func (e *JSONFieldExtractor) IsDone() bool {
|
||||
return e.done
|
||||
}
|
||||
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestJSONFieldExtractor_Basic(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
// Simulate streaming JSON: {"answer":"Hello world"}
|
||||
got := ""
|
||||
|
|
@ -23,7 +23,7 @@ func TestJSONFieldExtractor_Basic(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_WithEscapes(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
// Simulate: {"answer":"line1\nline2 and \"quoted\""}
|
||||
got := ""
|
||||
|
|
@ -38,7 +38,7 @@ func TestJSONFieldExtractor_WithEscapes(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_OneChunk(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
got := e.Feed(`{"answer":"complete answer here"}`)
|
||||
|
||||
|
|
@ -51,7 +51,7 @@ func TestJSONFieldExtractor_OneChunk(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_SmallChunks(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
// Very small chunks
|
||||
got := ""
|
||||
|
|
@ -66,7 +66,7 @@ func TestJSONFieldExtractor_SmallChunks(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_Markdown(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
got := ""
|
||||
got += e.Feed(`{"answer":"# Title\n\n`)
|
||||
|
|
@ -82,7 +82,7 @@ func TestJSONFieldExtractor_Markdown(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_UnicodeEscape(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
got := ""
|
||||
got += e.Feed(`{"answer":"Hello \u4e16\u754c`)
|
||||
|
|
@ -95,7 +95,7 @@ func TestJSONFieldExtractor_UnicodeEscape(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_IncompleteEscapeAtBoundary(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
// Escape sequence split across chunks
|
||||
got := ""
|
||||
|
|
@ -109,7 +109,7 @@ func TestJSONFieldExtractor_IncompleteEscapeAtBoundary(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_WhitespaceInJSON(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
// Whitespace around colon
|
||||
got := e.Feed(`{ "answer" : "content here" }`)
|
||||
|
|
@ -120,7 +120,7 @@ func TestJSONFieldExtractor_WhitespaceInJSON(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_EmptyAnswer(t *testing.T) {
|
||||
e := newJSONFieldExtractor("answer")
|
||||
e := NewJSONFieldExtractor("answer")
|
||||
|
||||
got := e.Feed(`{"answer":""}`)
|
||||
|
||||
|
|
@ -134,7 +134,7 @@ func TestJSONFieldExtractor_EmptyAnswer(t *testing.T) {
|
|||
|
||||
// Test extracting "thought" field (for thinking tool)
|
||||
func TestJSONFieldExtractor_ThoughtField(t *testing.T) {
|
||||
e := newJSONFieldExtractor("thought")
|
||||
e := NewJSONFieldExtractor("thought")
|
||||
|
||||
got := ""
|
||||
got += e.Feed(`{"thought":"Let me analyze`)
|
||||
|
|
@ -151,7 +151,7 @@ func TestJSONFieldExtractor_ThoughtField(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestJSONFieldExtractor_ThoughtFieldWithEscapes(t *testing.T) {
|
||||
e := newJSONFieldExtractor("thought")
|
||||
e := NewJSONFieldExtractor("thought")
|
||||
|
||||
got := ""
|
||||
got += e.Feed(`{"thought":"Step 1:\n- Analyze the query\n- `)
|
||||
|
|
@ -0,0 +1,398 @@
|
|||
package openaicompletions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const defaultPath = "/chat/completions"
|
||||
|
||||
// Client talks Chat Completions to one endpoint.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
}
|
||||
|
||||
// New creates a client. The endpoint must already carry auth and headers.
|
||||
func New(cfg Config) *Client {
|
||||
if cfg.ThinkingLevels == nil {
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
}
|
||||
return &Client{cfg: cfg}
|
||||
}
|
||||
|
||||
// GetModelName returns the wire model name.
|
||||
func (c *Client) GetModelName() string { return c.cfg.Endpoint.Model }
|
||||
|
||||
// GetModelID returns WeKnora's model identifier.
|
||||
func (c *Client) GetModelID() string { return c.cfg.Endpoint.ModelID }
|
||||
|
||||
// Settings exposes the resolved settings (diagnostics, tests).
|
||||
func (c *Client) Settings() Config { return c.cfg }
|
||||
|
||||
func (c *Client) url() string { return c.cfg.Endpoint.Resolve(defaultPath) }
|
||||
|
||||
func (c *Client) send(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
|
||||
) (*http.Response, []byte, error) {
|
||||
opts = api.WithSessionCacheKey(ctx, opts)
|
||||
body, err := c.BuildRequestBody(messages, opts, stream)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
url := c.url()
|
||||
req, data, err := c.cfg.Endpoint.NewRequest(ctx, url, body, stream)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if c.cfg.Settings.PromptCacheKey {
|
||||
key := c.cfg.SessionID
|
||||
if opts != nil && opts.PromptCacheKey != "" {
|
||||
key = opts.PromptCacheKey
|
||||
}
|
||||
api.AttachSessionAffinityHeaders(req, api.ClampPromptCacheKey(key))
|
||||
}
|
||||
api.LogRequest(ctx, url, c.cfg.Endpoint.Model, data, stream)
|
||||
resp, err := c.cfg.Endpoint.Do(req)
|
||||
if err != nil {
|
||||
return nil, data, err
|
||||
}
|
||||
return resp, data, nil
|
||||
}
|
||||
|
||||
// Chat performs a non-streaming completion.
|
||||
func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Options) (*types.ChatResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultChatTimeout)
|
||||
defer cancel()
|
||||
|
||||
resp, _, err := c.send(ctx, messages, opts, false)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, _, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, false)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create chat completion: %w", err)
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
result, err := c.parseResponse(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api.LogUsage(ctx, c.cfg.Endpoint.Model, &result.Usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ChatStream performs a streaming completion.
|
||||
func (c *Client) ChatStream(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultStreamTimeout)
|
||||
|
||||
resp, data, err := c.send(ctx, messages, opts, true)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, fmt.Errorf("create chat completion stream: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ch := make(chan types.StreamResponse)
|
||||
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
|
||||
if dumper != nil {
|
||||
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
|
||||
}
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer close(ch)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if dumper != nil {
|
||||
defer dumper.Close()
|
||||
}
|
||||
c.processStream(ctx, resp.Body, ch, dumper)
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// --- response decoding ---
|
||||
|
||||
type rawToolCall struct {
|
||||
Index *int `json:"index,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Function struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Arguments string `json:"arguments,omitempty"`
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
type rawMessage struct {
|
||||
Role string `json:"role,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
ReasoningContent string `json:"reasoning_content,omitempty"`
|
||||
Reasoning string `json:"reasoning,omitempty"`
|
||||
ReasoningText string `json:"reasoning_text,omitempty"`
|
||||
ReasoningDetails json.RawMessage `json:"reasoning_details,omitempty"`
|
||||
ToolCalls []json.RawMessage `json:"tool_calls,omitempty"`
|
||||
}
|
||||
|
||||
type rawChoice struct {
|
||||
Index int `json:"index"`
|
||||
Message rawMessage `json:"message"`
|
||||
Delta rawMessage `json:"delta"`
|
||||
FinishReason string `json:"finish_reason,omitempty"`
|
||||
}
|
||||
|
||||
type rawEnvelope struct {
|
||||
Choices []rawChoice `json:"choices"`
|
||||
Usage *api.OpenAIUsage `json:"usage,omitempty"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
Code any `json:"code"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) reasoningText(m rawMessage) string {
|
||||
for _, field := range c.cfg.Settings.ReasoningFields {
|
||||
switch field {
|
||||
case "reasoning_content":
|
||||
if m.ReasoningContent != "" {
|
||||
return m.ReasoningContent
|
||||
}
|
||||
case "reasoning":
|
||||
if m.Reasoning != "" {
|
||||
return m.Reasoning
|
||||
}
|
||||
case "reasoning_text":
|
||||
if m.ReasoningText != "" {
|
||||
return m.ReasoningText
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c *Client) decodeToolCalls(raws []json.RawMessage) ([]types.LLMToolCall, []api.ToolCallDelta, error) {
|
||||
calls := make([]types.LLMToolCall, 0, len(raws))
|
||||
deltas := make([]api.ToolCallDelta, 0, len(raws))
|
||||
for i, raw := range raws {
|
||||
var tc rawToolCall
|
||||
if err := json.Unmarshal(raw, &tc); err != nil {
|
||||
// Dropping the entry turns a round that wanted to call a tool into
|
||||
// a plain answer, and the agent has no way to notice the action it
|
||||
// was told to take went missing. Surface it instead.
|
||||
return nil, nil, fmt.Errorf("decode tool call %d: %w", i, err)
|
||||
}
|
||||
idx := i
|
||||
if tc.Index != nil {
|
||||
idx = *tc.Index
|
||||
}
|
||||
call := types.LLMToolCall{
|
||||
ID: tc.ID,
|
||||
Type: orDefault(tc.Type, "function"),
|
||||
Function: types.FunctionCall{Name: tc.Function.Name, Arguments: tc.Function.Arguments},
|
||||
}
|
||||
call.ProviderMetadata = c.extractToolCallMetadata(raw)
|
||||
calls = append(calls, call)
|
||||
deltas = append(deltas, api.ToolCallDelta{
|
||||
Index: idx, ID: tc.ID, Type: tc.Type, Name: tc.Function.Name, Arguments: tc.Function.Arguments,
|
||||
})
|
||||
}
|
||||
return calls, deltas, nil
|
||||
}
|
||||
|
||||
func (c *Client) extractToolCallMetadata(raw json.RawMessage) types.ToolCallMetadata {
|
||||
if len(c.cfg.Settings.ToolCallExtraFields) == 0 {
|
||||
return nil
|
||||
}
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &obj); err != nil {
|
||||
return nil
|
||||
}
|
||||
var md types.ToolCallMetadata
|
||||
for _, key := range c.cfg.Settings.ToolCallExtraFields {
|
||||
if v, ok := obj[key]; ok && len(v) > 0 && string(v) != "null" {
|
||||
if md == nil {
|
||||
md = types.ToolCallMetadata{}
|
||||
}
|
||||
md[key] = v
|
||||
}
|
||||
}
|
||||
return md
|
||||
}
|
||||
|
||||
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
|
||||
var env rawEnvelope
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
if env.Error != nil && env.Error.Message != "" {
|
||||
return nil, fmt.Errorf("API error: %s", env.Error.Message)
|
||||
}
|
||||
if len(env.Choices) == 0 {
|
||||
return nil, fmt.Errorf("no response from API")
|
||||
}
|
||||
choice := env.Choices[0]
|
||||
content, inlineReasoning := splitThinkTags(choice.Message.Content)
|
||||
result := &types.ChatResponse{
|
||||
Content: content,
|
||||
ReasoningContent: c.reasoningText(choice.Message),
|
||||
FinishReason: choice.FinishReason,
|
||||
}
|
||||
if result.ReasoningContent == "" {
|
||||
result.ReasoningContent = inlineReasoning
|
||||
}
|
||||
if len(choice.Message.ReasoningDetails) > 0 {
|
||||
result.ReasoningMetadata = types.ProviderMetadata{metadataReasoningDetails: choice.Message.ReasoningDetails}
|
||||
}
|
||||
if len(choice.Message.ToolCalls) > 0 {
|
||||
calls, _, err := c.decodeToolCalls(choice.Message.ToolCalls)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.ToolCalls = calls
|
||||
}
|
||||
// Classify the cache status even when the vendor omitted the usage block,
|
||||
// so "no counters at all" is still distinguishable from a real miss on the
|
||||
// usage dashboards instead of landing as an empty CacheStatus.
|
||||
usage := api.OpenAIUsage{}
|
||||
if env.Usage != nil {
|
||||
usage = *env.Usage
|
||||
}
|
||||
result.Usage = usage.ToTokenUsage(c.cfg.Settings.PromptCacheAccounting)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// splitThinkTags handles models that inline their chain of thought as a
|
||||
// leading <think>...</think> block instead of a reasoning field.
|
||||
func splitThinkTags(content string) (answer, reasoning string) {
|
||||
const start, end = "<think>", "</think>"
|
||||
trimmed := strings.TrimSpace(content)
|
||||
if !strings.HasPrefix(trimmed, start) {
|
||||
return content, ""
|
||||
}
|
||||
idx := strings.LastIndex(trimmed, end)
|
||||
if idx < 0 {
|
||||
// Unterminated: the whole output is (truncated) reasoning.
|
||||
return "", strings.TrimSpace(trimmed[len(start):])
|
||||
}
|
||||
return strings.TrimSpace(trimmed[idx+len(end):]), strings.TrimSpace(trimmed[len(start):idx])
|
||||
}
|
||||
|
||||
func (c *Client) processStream(
|
||||
ctx context.Context, body io.Reader, ch chan<- types.StreamResponse, dumper *api.StreamPacketDumper,
|
||||
) {
|
||||
assembler := api.NewStreamAssembler(ctx, c.cfg.Endpoint.Model)
|
||||
reader := api.NewSSEReader(body)
|
||||
var reasoningDetails []json.RawMessage
|
||||
|
||||
finish := func() {
|
||||
if len(reasoningDetails) > 0 {
|
||||
merged, _ := json.Marshal(reasoningDetails)
|
||||
assembler.ReasoningMetadata = types.ProviderMetadata{metadataReasoningDetails: merged}
|
||||
}
|
||||
assembler.End(ch)
|
||||
}
|
||||
|
||||
for {
|
||||
// The consumer went away (client disconnect, aborted agent turn): stop
|
||||
// decoding a stream nobody will read instead of spinning to EOF.
|
||||
if assembler.Aborted() {
|
||||
return
|
||||
}
|
||||
event, err := reader.ReadEvent()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
finish()
|
||||
} else {
|
||||
assembler.Fail(ch, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if event == nil {
|
||||
continue
|
||||
}
|
||||
if event.Done {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if len(event.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
if dumper != nil {
|
||||
raw := make([]byte, len(event.Data))
|
||||
copy(raw, event.Data)
|
||||
dumper.WritePacketRaw(raw)
|
||||
}
|
||||
|
||||
var env rawEnvelope
|
||||
if err := json.Unmarshal(event.Data, &env); err != nil {
|
||||
// Fail rather than skip, as the Anthropic and Gemini loops do. A
|
||||
// chunk we cannot decode is a hole in the answer: skipping it ends
|
||||
// the stream on EOF, which reaches the caller as a *successful*
|
||||
// truncated reply and gets persisted as the model's answer. An
|
||||
// error at least surfaces the proxy that corrupted the stream.
|
||||
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
|
||||
return
|
||||
}
|
||||
if env.Error != nil && env.Error.Message != "" {
|
||||
assembler.Fail(ch, fmt.Errorf("API stream error: %s", env.Error.Message))
|
||||
return
|
||||
}
|
||||
if env.Usage != nil {
|
||||
assembler.SetUsage(env.Usage.ToTokenUsage(c.cfg.Settings.PromptCacheAccounting))
|
||||
}
|
||||
if len(env.Choices) == 0 {
|
||||
continue
|
||||
}
|
||||
choice := env.Choices[0]
|
||||
delta := api.Delta{
|
||||
Reasoning: c.reasoningText(choice.Delta),
|
||||
Content: choice.Delta.Content,
|
||||
FinishReason: choice.FinishReason,
|
||||
}
|
||||
if len(choice.Delta.ReasoningDetails) > 0 {
|
||||
var items []json.RawMessage
|
||||
if err := json.Unmarshal(choice.Delta.ReasoningDetails, &items); err == nil {
|
||||
reasoningDetails = append(reasoningDetails, items...)
|
||||
}
|
||||
}
|
||||
if len(choice.Delta.ToolCalls) > 0 {
|
||||
_, deltas, err := c.decodeToolCalls(choice.Delta.ToolCalls)
|
||||
if err != nil {
|
||||
assembler.Fail(ch, err)
|
||||
return
|
||||
}
|
||||
delta.ToolCalls = deltas
|
||||
for i, raw := range choice.Delta.ToolCalls {
|
||||
if md := c.extractToolCallMetadata(raw); len(md) > 0 {
|
||||
idx := i
|
||||
if i < len(deltas) {
|
||||
idx = deltas[i].Index
|
||||
}
|
||||
assembler.SetToolCallMetadata(idx, md)
|
||||
}
|
||||
}
|
||||
}
|
||||
assembler.Process(ch, delta)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,632 @@
|
|||
package openaicompletions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newClient(t *testing.T, mutate func(*Config)) *Client {
|
||||
t.Helper()
|
||||
cfg := Config{
|
||||
Endpoint: api.Endpoint{
|
||||
BaseURL: "https://example.com/v1", Model: "m", ModelID: "id", Auth: api.BearerAuth("k"),
|
||||
},
|
||||
Settings: catalog.DefaultOpenAICompletions(),
|
||||
ThinkingLevels: api.ThinkingLevelMap{},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&cfg)
|
||||
}
|
||||
return New(cfg)
|
||||
}
|
||||
|
||||
func bodyJSON(t *testing.T, c *Client, msgs []api.Message, opts *api.Options, stream bool) map[string]any {
|
||||
t.Helper()
|
||||
body, err := c.BuildRequestBody(msgs, opts, stream)
|
||||
require.NoError(t, err)
|
||||
data, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &out))
|
||||
return out
|
||||
}
|
||||
|
||||
func ptrBool(b bool) *bool { return &b }
|
||||
|
||||
var conversation = []api.Message{
|
||||
{Role: "system", Content: "You are helpful."},
|
||||
{Role: "user", Content: "hi"},
|
||||
{Role: "assistant", ReasoningContent: "thinking...", ToolCalls: []api.ToolCall{{
|
||||
ID: "call_1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"x"}`},
|
||||
}}},
|
||||
{Role: "tool", ToolCallID: "call_1", Name: "search", Content: "result"},
|
||||
}
|
||||
|
||||
var toolOpts = &api.Options{
|
||||
Temperature: 0.7, MaxTokens: 1000,
|
||||
Tools: []api.Tool{{Type: "function", Function: api.FunctionDef{
|
||||
Name: "search", Description: "d", Parameters: json.RawMessage(`{"type":"object","properties":{}}`),
|
||||
}}},
|
||||
ToolChoice: "required", ParallelToolCalls: ptrBool(true),
|
||||
}
|
||||
|
||||
// TestGolden pins the exact wire body per vendor dialect. Each case is one
|
||||
// row of the vendor fact table; changing a vendor's behaviour means changing
|
||||
// the expectation here on purpose.
|
||||
func TestGolden(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Config)
|
||||
opts *api.Options
|
||||
stream bool
|
||||
want map[string]any // keys asserted; value nil means "must be absent"
|
||||
}{
|
||||
{
|
||||
name: "openai baseline: max_completion_tokens, store, developer role off for non-reasoning",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.SupportsStore = true
|
||||
c.Settings.SupportsDeveloperRole = true
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatOpenAI
|
||||
c.Settings.SupportsReasoningEffort = true
|
||||
},
|
||||
opts: toolOpts,
|
||||
stream: true,
|
||||
want: map[string]any{
|
||||
"max_completion_tokens": float64(1000), "max_tokens": nil,
|
||||
"store": false, "stream": true, "stream_options": map[string]any{"include_usage": true},
|
||||
"temperature": 0.7, "tool_choice": "required", "parallel_tool_calls": true,
|
||||
"reasoning_effort": nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "openai reasoning model: developer role, no sampling, effort medium",
|
||||
mutate: func(c *Config) {
|
||||
c.Reasoning = true
|
||||
c.Settings.SupportsDeveloperRole = true
|
||||
c.Settings.SupportsTemperature = false
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatOpenAI
|
||||
c.Settings.SupportsReasoningEffort = true
|
||||
},
|
||||
opts: &api.Options{Temperature: 0.7, MaxTokens: 10, ReasoningEffort: api.ReasoningMedium},
|
||||
want: map[string]any{
|
||||
"temperature": nil, "reasoning_effort": "medium", "max_completion_tokens": float64(10),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "openai gpt-5.1 off maps to reasoning_effort none",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatOpenAI
|
||||
c.Settings.SupportsReasoningEffort = true
|
||||
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: api.StringPtr("none")}
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(false)},
|
||||
want: map[string]any{"reasoning_effort": "none"},
|
||||
},
|
||||
{
|
||||
name: "deepseek: max_tokens, thinking.type + effort clamp, tool_choice required dropped",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.MaxTokensField = "max_tokens"
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatThinkingType
|
||||
c.Settings.SupportsReasoningEffort = true
|
||||
c.Settings.ToolChoiceModes = []string{"none", "auto"}
|
||||
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningMedium: api.StringPtr("high")}
|
||||
},
|
||||
opts: func() *api.Options { o := *toolOpts; o.ReasoningEffort = api.ReasoningMedium; return &o }(),
|
||||
want: map[string]any{
|
||||
"max_tokens": float64(1000), "max_completion_tokens": nil,
|
||||
"thinking": map[string]any{"type": "enabled"}, "reasoning_effort": "high",
|
||||
"tool_choice": nil, "parallel_tool_calls": true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "deepseek reasoner: always-on, off request sends nothing",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatThinkingType
|
||||
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: nil}
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(false)},
|
||||
want: map[string]any{"thinking": nil},
|
||||
},
|
||||
{
|
||||
name: "zhipu: thinking disabled explicitly",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatThinkingType
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(false)},
|
||||
want: map[string]any{"thinking": map[string]any{"type": "disabled"}},
|
||||
},
|
||||
{
|
||||
name: "minimax m3: adaptive thinking value",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatThinkingType
|
||||
c.Settings.ThinkingEnabledValue = "adaptive"
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(true)},
|
||||
want: map[string]any{"thinking": map[string]any{"type": "adaptive"}, "reasoning_effort": nil},
|
||||
},
|
||||
{
|
||||
name: "dashscope hybrid: enable_thinking always sent, budget, non-stream forces off",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.MaxTokensField = "max_tokens"
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatEnableThinking
|
||||
c.Settings.ThinkingBudgetField = "thinking_budget"
|
||||
c.Settings.ThinkingAlwaysSend = true
|
||||
c.Settings.ThinkingDisableOnNonStream = true
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(true), ThinkingBudgetTokens: 4096},
|
||||
stream: false,
|
||||
want: map[string]any{"enable_thinking": false, "thinking_budget": nil},
|
||||
},
|
||||
{
|
||||
name: "dashscope hybrid streaming: enable_thinking true with budget",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatEnableThinking
|
||||
c.Settings.ThinkingBudgetField = "thinking_budget"
|
||||
c.Settings.ThinkingAlwaysSend = true
|
||||
c.Settings.ThinkingDisableOnNonStream = true
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(true), ThinkingBudgetTokens: 4096},
|
||||
stream: true,
|
||||
want: map[string]any{"enable_thinking": true, "thinking_budget": float64(4096)},
|
||||
},
|
||||
{
|
||||
name: "dashscope: no preference still pins enable_thinking false",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatEnableThinking
|
||||
c.Settings.ThinkingAlwaysSend = true
|
||||
},
|
||||
opts: &api.Options{Temperature: 0.1},
|
||||
want: map[string]any{"enable_thinking": false},
|
||||
},
|
||||
{
|
||||
name: "vllm: chat_template_kwargs",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatChatTemplateKwargs
|
||||
},
|
||||
opts: &api.Options{Thinking: ptrBool(true)},
|
||||
want: map[string]any{"chat_template_kwargs": map[string]any{"enable_thinking": true}},
|
||||
},
|
||||
{
|
||||
name: "openrouter: reasoning effort object and enabled=false",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatOpenRouter
|
||||
c.Settings.SupportsReasoningEffort = true
|
||||
},
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningHigh},
|
||||
want: map[string]any{"reasoning": map[string]any{"effort": "high"}},
|
||||
},
|
||||
{
|
||||
name: "openrouter: auto enables without effort",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatOpenRouter
|
||||
c.Settings.SupportsReasoningEffort = true
|
||||
},
|
||||
opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
|
||||
want: map[string]any{"reasoning": map[string]any{"enabled": true}},
|
||||
},
|
||||
{
|
||||
name: "moonshot v1: fixed temperature, other sampling dropped",
|
||||
mutate: func(c *Config) {
|
||||
one := 1.0
|
||||
c.Settings.FixedTemperature = &one
|
||||
},
|
||||
opts: &api.Options{Temperature: 0.2, TopP: 0.9},
|
||||
want: map[string]any{"temperature": 1.0, "top_p": nil},
|
||||
},
|
||||
{
|
||||
name: "no thinking preference on a plain vendor sends no thinking fields",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ThinkingFormat = catalog.ThinkingFormatThinkingType
|
||||
},
|
||||
opts: &api.Options{Temperature: 0.2},
|
||||
want: map[string]any{"thinking": nil, "reasoning_effort": nil, "enable_thinking": nil},
|
||||
},
|
||||
{
|
||||
name: "prompt cache key and long retention",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.PromptCacheKey = true
|
||||
},
|
||||
opts: &api.Options{PromptCacheKey: "sess-1", CacheRetention: api.CacheRetentionLong},
|
||||
want: map[string]any{"prompt_cache_key": "sess-1", "prompt_cache_retention": "24h"},
|
||||
},
|
||||
{
|
||||
name: "extra_body merges vendor knobs without overriding caller fields",
|
||||
mutate: func(c *Config) {
|
||||
c.Settings.ExtraBody = map[string]any{"enable_search": true, "temperature": 0.9}
|
||||
},
|
||||
opts: &api.Options{Temperature: 0.2},
|
||||
want: map[string]any{"enable_search": true, "temperature": 0.2},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := newClient(t, tc.mutate)
|
||||
got := bodyJSON(t, c, conversation, tc.opts, tc.stream)
|
||||
for key, want := range tc.want {
|
||||
if want == nil {
|
||||
_, present := got[key]
|
||||
assert.False(t, present, "field %q must be absent, got %v", key, got[key])
|
||||
continue
|
||||
}
|
||||
assert.Equal(t, want, got[key], "field %q", key)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessages_RolesToolsAndReasoningReplay(t *testing.T) {
|
||||
c := newClient(t, func(c *Config) {
|
||||
c.Reasoning = true
|
||||
c.Settings.SupportsDeveloperRole = true
|
||||
})
|
||||
got := bodyJSON(t, c, conversation, nil, false)
|
||||
msgs := got["messages"].([]any)
|
||||
require.Len(t, msgs, 4)
|
||||
assert.Equal(t, "developer", msgs[0].(map[string]any)["role"])
|
||||
assistant := msgs[2].(map[string]any)
|
||||
assert.Equal(t, "thinking...", assistant["reasoning_content"])
|
||||
_, hasContent := assistant["content"]
|
||||
assert.False(t, hasContent, "empty content omitted next to tool_calls")
|
||||
tc := assistant["tool_calls"].([]any)[0].(map[string]any)
|
||||
assert.Equal(t, "call_1", tc["id"])
|
||||
assert.Equal(t, `{"q":"x"}`, tc["function"].(map[string]any)["arguments"])
|
||||
tool := msgs[3].(map[string]any)
|
||||
assert.Equal(t, "call_1", tool["tool_call_id"])
|
||||
assert.Equal(t, "search", tool["name"])
|
||||
|
||||
plain := newClient(t, func(c *Config) { c.Settings.ReplayReasoningContent = false })
|
||||
got = bodyJSON(t, plain, conversation, nil, false)
|
||||
assistant = got["messages"].([]any)[2].(map[string]any)
|
||||
_, has := assistant["reasoning_content"]
|
||||
assert.False(t, has)
|
||||
assert.Equal(t, "system", got["messages"].([]any)[0].(map[string]any)["role"])
|
||||
}
|
||||
|
||||
func TestMessages_ImagesAndMultiContentDowngrade(t *testing.T) {
|
||||
msgs := []api.Message{{Role: "user", Content: "look", Images: []string{"https://img/x.png"}}}
|
||||
c := newClient(t, nil)
|
||||
got := bodyJSON(t, c, msgs, nil, false)
|
||||
parts := got["messages"].([]any)[0].(map[string]any)["content"].([]any)
|
||||
require.Len(t, parts, 2)
|
||||
assert.Equal(t, "image_url", parts[0].(map[string]any)["type"])
|
||||
assert.Equal(t, "look", parts[1].(map[string]any)["text"])
|
||||
|
||||
flat := newClient(t, func(c *Config) { c.Settings.SupportsMultiContent = false })
|
||||
got = bodyJSON(t, flat, msgs, nil, false)
|
||||
assert.Equal(t, "look", got["messages"].([]any)[0].(map[string]any)["content"])
|
||||
}
|
||||
|
||||
func TestToolCallExtraFieldsRoundTrip(t *testing.T) {
|
||||
c := newClient(t, func(c *Config) { c.Settings.ToolCallExtraFields = []string{"extra_content"} })
|
||||
md := c.extractToolCallMetadata(json.RawMessage(`{"id":"call_1","type":"function",` +
|
||||
`"function":{"name":"f","arguments":"{}"},"extra_content":{"google":{"thought_signature":"abc"}}}`))
|
||||
require.NotNil(t, md)
|
||||
assert.JSONEq(t, `{"google":{"thought_signature":"abc"}}`, string(md["extra_content"]))
|
||||
|
||||
msgs := []api.Message{{Role: "assistant", ToolCalls: []api.ToolCall{{
|
||||
ID: "call_1", Type: "function", Function: api.FunctionCall{Name: "f", Arguments: "{}"}, ProviderMetadata: md,
|
||||
}}}}
|
||||
got := bodyJSON(t, c, msgs, nil, false)
|
||||
tc := got["messages"].([]any)[0].(map[string]any)["tool_calls"].([]any)[0].(map[string]any)
|
||||
assert.Equal(t, map[string]any{"google": map[string]any{"thought_signature": "abc"}}, tc["extra_content"])
|
||||
}
|
||||
|
||||
func TestCacheControlBreakpoints(t *testing.T) {
|
||||
c := newClient(t, func(c *Config) { c.Settings.CacheControlFormat = "anthropic" })
|
||||
got := bodyJSON(t, c, conversation, toolOpts, false)
|
||||
data, _ := json.Marshal(got)
|
||||
assert.Equal(t, 3, strings.Count(string(data), `"cache_control"`))
|
||||
|
||||
none := bodyJSON(t, c, conversation, &api.Options{CacheRetention: api.CacheRetentionNone}, false)
|
||||
data, _ = json.Marshal(none)
|
||||
assert.NotContains(t, string(data), "cache_control")
|
||||
}
|
||||
|
||||
func TestChat_NonStreamDecoding(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var captured http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
captured = r.Header.Clone()
|
||||
assert.Equal(t, "/v1/chat/completions", r.URL.Path)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"choices":[{"index":0,"message":{"role":"assistant",` +
|
||||
`"content":"<think>deep</think>answer",` +
|
||||
`"tool_calls":[{"id":"c1","type":"function","function":{"name":"f","arguments":"{\"a\":1}"}}]},` +
|
||||
`"finish_reason":"tool_calls"}],` +
|
||||
`"usage":{"prompt_tokens":30,"completion_tokens":5,` +
|
||||
`"prompt_cache_hit_tokens":20,"prompt_cache_miss_tokens":10}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{
|
||||
BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk"),
|
||||
Headers: map[string]string{"X-Custom": "1", "Authorization": "Bearer evil"},
|
||||
},
|
||||
Settings: func() catalog.OpenAICompletionsSettings {
|
||||
s := catalog.DefaultOpenAICompletions()
|
||||
s.PromptCacheAccounting = true
|
||||
return s
|
||||
}(),
|
||||
})
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Bearer sk", captured.Get("Authorization"), "user headers cannot override auth")
|
||||
assert.Equal(t, "1", captured.Get("X-Custom"))
|
||||
assert.Equal(t, "answer", resp.Content)
|
||||
assert.Equal(t, "deep", resp.ReasoningContent)
|
||||
assert.Equal(t, "tool_calls", resp.FinishReason)
|
||||
require.Len(t, resp.ToolCalls, 1)
|
||||
assert.Equal(t, 20, resp.Usage.CacheReadTokens)
|
||||
assert.Equal(t, 10, resp.Usage.CacheMissTokens)
|
||||
}
|
||||
|
||||
func TestChat_HTTPErrorSurfacesBody(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":{"message":"max_tokens is not supported"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL, Model: "m"}, Settings: catalog.DefaultOpenAICompletions(),
|
||||
})
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "status 400")
|
||||
assert.Contains(t, err.Error(), "max_tokens is not supported")
|
||||
}
|
||||
|
||||
const streamFixture = `data: {"choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"thi"}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{"reasoning_content":"nk"}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{"content":"Hel"}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{"content":"lo"}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function",` +
|
||||
`"function":{"name":"search"}}]}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"q\":"}}]}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"x\"}"}}]}}]}
|
||||
|
||||
data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}
|
||||
|
||||
data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":7,"prompt_tokens_details":{"cached_tokens":4}}}
|
||||
|
||||
data: [DONE]
|
||||
`
|
||||
|
||||
func TestChatStream_Sequence(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
|
||||
assert.Equal(t, true, body["stream"])
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(streamFixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL, Model: "m"}, Settings: catalog.DefaultOpenAICompletions(),
|
||||
})
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var thinking, answer strings.Builder
|
||||
var seenTypes []types.ResponseType
|
||||
var last types.StreamResponse
|
||||
thinkingDone := false
|
||||
for chunk := range ch {
|
||||
seenTypes = append(seenTypes, chunk.ResponseType)
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeThinking:
|
||||
if chunk.Done {
|
||||
thinkingDone = true
|
||||
}
|
||||
thinking.WriteString(chunk.Content)
|
||||
case types.ResponseTypeAnswer:
|
||||
answer.WriteString(chunk.Content)
|
||||
if chunk.Done {
|
||||
last = chunk
|
||||
}
|
||||
case types.ResponseTypeToolCall:
|
||||
assert.Equal(t, "search", chunk.Data["tool_name"])
|
||||
assert.Equal(t, "c1", chunk.Data["tool_call_id"])
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("unexpected error: %s", chunk.Content)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "think", thinking.String())
|
||||
assert.True(t, thinkingDone, "thinking done marker emitted before the answer")
|
||||
assert.Equal(t, "Hello", answer.String())
|
||||
assert.Contains(t, seenTypes, types.ResponseTypeToolCall)
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, `{"q":"x"}`, last.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, "tool_calls", last.FinishReason)
|
||||
require.NotNil(t, last.Usage)
|
||||
assert.Equal(t, 12, last.Usage.PromptTokens)
|
||||
assert.Equal(t, 4, last.Usage.CacheReadTokens)
|
||||
}
|
||||
|
||||
func TestSplitThinkTags(t *testing.T) {
|
||||
answer, reasoning := splitThinkTags("<think>a</think>b")
|
||||
assert.Equal(t, "b", answer)
|
||||
assert.Equal(t, "a", reasoning)
|
||||
answer, reasoning = splitThinkTags("<think>truncated")
|
||||
assert.Equal(t, "", answer)
|
||||
assert.Equal(t, "truncated", reasoning)
|
||||
answer, reasoning = splitThinkTags("plain")
|
||||
assert.Equal(t, "plain", answer)
|
||||
assert.Equal(t, "", reasoning)
|
||||
}
|
||||
|
||||
// A response without a usage block must still classify the cache status:
|
||||
// leaving it empty makes "the vendor reported nothing" look like a real miss
|
||||
// on the usage dashboards. The pre-split implementation always classified.
|
||||
func TestChat_ClassifiesCacheStatusWithoutUsageBlock(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"choices":[{"index":0,"message":{"role":"assistant","content":"hi"},` +
|
||||
`"finish_reason":"stop"}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
accounting bool
|
||||
want types.PromptCacheStatus
|
||||
}{
|
||||
{"vendor documents cache accounting", true, types.PromptCacheStatusUnreported},
|
||||
{"vendor has no cache accounting", false, types.PromptCacheStatusUnsupported},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
|
||||
Settings: func() catalog.OpenAICompletionsSettings {
|
||||
s := catalog.DefaultOpenAICompletions()
|
||||
s.PromptCacheAccounting = tc.accounting
|
||||
return s
|
||||
}(),
|
||||
})
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.want, resp.Usage.CacheStatus)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A stream that ends on the [DONE] sentinel without a space after the colon
|
||||
// must still terminate cleanly rather than logging a JSON parse failure.
|
||||
func TestChatStream_TolerantDoneSentinel(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hi\"},\"finish_reason\":\"stop\"}]}\n\n" +
|
||||
"data:[DONE]\n\n"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
|
||||
Settings: catalog.DefaultOpenAICompletions(),
|
||||
})
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
var answer strings.Builder
|
||||
for chunk := range ch {
|
||||
if chunk.ResponseType == types.ResponseTypeError {
|
||||
t.Fatalf("unexpected error chunk: %s", chunk.Content)
|
||||
}
|
||||
answer.WriteString(chunk.Content)
|
||||
}
|
||||
assert.Equal(t, "hi", answer.String())
|
||||
}
|
||||
|
||||
// A chunk that will not decode is a hole in the answer. Skipping it (the old
|
||||
// behaviour) ended the stream on EOF, so a proxy that corrupted one packet
|
||||
// produced a truncated reply that every caller recorded as a successful one.
|
||||
// The Anthropic and Gemini loops fail in this situation; so does this one.
|
||||
func TestChatStream_UndecodableChunkFailsTheStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n" +
|
||||
"data: <html>502 Bad Gateway</html>\n\n" +
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"},\"finish_reason\":\"stop\"}]}\n\n" +
|
||||
"data: [DONE]\n\n"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
|
||||
Settings: catalog.DefaultOpenAICompletions(),
|
||||
})
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var sawError bool
|
||||
var answer strings.Builder
|
||||
for chunk := range ch {
|
||||
if chunk.ResponseType == types.ResponseTypeError {
|
||||
sawError = true
|
||||
assert.Contains(t, chunk.Content, "decode stream chunk")
|
||||
continue
|
||||
}
|
||||
answer.WriteString(chunk.Content)
|
||||
}
|
||||
assert.True(t, sawError, "a truncated stream must surface as an error, not as a short answer")
|
||||
assert.Equal(t, "Hel", answer.String(), "decoding stops at the bad chunk")
|
||||
}
|
||||
|
||||
// A tool_calls entry we cannot decode used to be skipped, so a round that
|
||||
// wanted to call a tool arrived at the agent as a plain answer with nothing
|
||||
// to act on. Losing the action is worse than failing the round.
|
||||
func TestChat_MalformedToolCallIsAnError(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"choices":[{"index":0,"message":{"role":"assistant","content":"",` +
|
||||
`"tool_calls":["not-an-object"]},"finish_reason":"tool_calls"}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
|
||||
Settings: catalog.DefaultOpenAICompletions(),
|
||||
})
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.Error(t, err, "a tool call that will not decode must not pass as a plain answer")
|
||||
assert.Contains(t, err.Error(), "decode tool call")
|
||||
}
|
||||
|
||||
// The streaming counterpart: the round must end as an error rather than as a
|
||||
// short answer whose tool call quietly vanished.
|
||||
func TestChatStream_MalformedToolCallFailsTheStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"}}]}\n\n" +
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[42]}}]}\n\n" +
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n" +
|
||||
"data: [DONE]\n\n"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := New(Config{
|
||||
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
|
||||
Settings: catalog.DefaultOpenAICompletions(),
|
||||
})
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var sawError bool
|
||||
var answer strings.Builder
|
||||
for chunk := range ch {
|
||||
if chunk.ResponseType == types.ResponseTypeError {
|
||||
sawError = true
|
||||
assert.Contains(t, chunk.Content, "decode tool call")
|
||||
continue
|
||||
}
|
||||
answer.WriteString(chunk.Content)
|
||||
}
|
||||
assert.True(t, sawError, "a dropped tool call must surface as an error")
|
||||
assert.Equal(t, "ok", answer.String(), "decoding stops at the bad chunk")
|
||||
}
|
||||
|
|
@ -0,0 +1,427 @@
|
|||
// Package openaicompletions implements the OpenAI Chat Completions wire
|
||||
// protocol. Every vendor-specific deviation is driven by
|
||||
// catalog.OpenAICompletionsSettings; this package contains no vendor names.
|
||||
package openaicompletions
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
)
|
||||
|
||||
// Config is everything the client needs, already resolved by the catalog.
|
||||
type Config struct {
|
||||
Endpoint api.Endpoint
|
||||
Settings catalog.OpenAICompletionsSettings
|
||||
// ThinkingLevels maps neutral levels to the vendor vocabulary.
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
// Reasoning marks a reasoning model (developer role, no sampling params
|
||||
// are decided by Settings, this only gates role selection).
|
||||
Reasoning bool
|
||||
// SessionID feeds prompt_cache_key when the caller sets none.
|
||||
SessionID string
|
||||
}
|
||||
|
||||
type wireToolCall struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Function wireFunctionCall `json:"function"`
|
||||
extra map[string]json.RawMessage
|
||||
}
|
||||
|
||||
type wireFunctionCall struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
}
|
||||
|
||||
// MarshalJSON appends opaque vendor fields (Gemini extra_content) next to
|
||||
// the standard members.
|
||||
func (t wireToolCall) MarshalJSON() ([]byte, error) {
|
||||
type plain wireToolCall
|
||||
data, err := json.Marshal(plain(t))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(t.extra) == 0 {
|
||||
return data, nil
|
||||
}
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &obj); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range t.extra {
|
||||
obj[k] = v
|
||||
}
|
||||
return json.Marshal(obj)
|
||||
}
|
||||
|
||||
type wireMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
ToolCalls []wireToolCall `json:"tool_calls,omitempty"`
|
||||
ReasoningContent *string `json:"reasoning_content,omitempty"`
|
||||
ReasoningDetails json.RawMessage `json:"reasoning_details,omitempty"`
|
||||
}
|
||||
|
||||
type wirePart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL *wireImageURL `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
type wireImageURL struct {
|
||||
URL string `json:"url"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// convertMessages maps neutral messages onto Chat Completions messages.
|
||||
func (c *Client) convertMessages(messages []api.Message) []wireMessage {
|
||||
s := c.cfg.Settings
|
||||
instructionRole := "system"
|
||||
if c.cfg.Reasoning && s.SupportsDeveloperRole {
|
||||
instructionRole = "developer"
|
||||
}
|
||||
out := make([]wireMessage, 0, len(messages))
|
||||
for _, msg := range messages {
|
||||
msg = api.NeutralizeMessageSpecialTokens(msg)
|
||||
wm := wireMessage{Role: msg.Role}
|
||||
if msg.Role == "system" {
|
||||
wm.Role = instructionRole
|
||||
}
|
||||
|
||||
switch {
|
||||
case len(msg.MultiContent) > 0:
|
||||
parts := make([]wirePart, 0, len(msg.MultiContent))
|
||||
for _, part := range msg.MultiContent {
|
||||
switch part.Type {
|
||||
case "text":
|
||||
parts = append(parts, wirePart{Type: "text", Text: part.Text})
|
||||
case "image_url":
|
||||
if part.ImageURL != nil {
|
||||
parts = append(parts, wirePart{Type: "image_url", ImageURL: &wireImageURL{
|
||||
URL: api.ResolveImageURLForLLM(part.ImageURL.URL), Detail: part.ImageURL.Detail,
|
||||
}})
|
||||
}
|
||||
}
|
||||
}
|
||||
wm.Content = c.contentParts(parts)
|
||||
case len(msg.Images) > 0 && msg.Role == "user":
|
||||
parts := make([]wirePart, 0, len(msg.Images)+1)
|
||||
for _, img := range msg.Images {
|
||||
parts = append(parts, wirePart{Type: "image_url", ImageURL: &wireImageURL{
|
||||
URL: api.ResolveImageURLForLLM(img), Detail: "auto",
|
||||
}})
|
||||
}
|
||||
parts = append(parts, wirePart{Type: "text", Text: msg.Content})
|
||||
wm.Content = c.contentParts(parts)
|
||||
default:
|
||||
if msg.Content != "" || len(msg.ToolCalls) == 0 {
|
||||
wm.Content = msg.Content
|
||||
}
|
||||
}
|
||||
|
||||
if len(msg.ToolCalls) > 0 {
|
||||
wm.ToolCalls = make([]wireToolCall, 0, len(msg.ToolCalls))
|
||||
for _, tc := range msg.ToolCalls {
|
||||
wtc := wireToolCall{
|
||||
ID: tc.ID,
|
||||
Type: orDefault(tc.Type, "function"),
|
||||
Function: wireFunctionCall{Name: tc.Function.Name, Arguments: tc.Function.Arguments},
|
||||
}
|
||||
for _, key := range s.ToolCallExtraFields {
|
||||
if raw, ok := tc.ProviderMetadata[key]; ok && len(raw) > 0 {
|
||||
if wtc.extra == nil {
|
||||
wtc.extra = map[string]json.RawMessage{}
|
||||
}
|
||||
wtc.extra[key] = raw
|
||||
}
|
||||
}
|
||||
wm.ToolCalls = append(wm.ToolCalls, wtc)
|
||||
}
|
||||
}
|
||||
|
||||
if msg.Role == "tool" {
|
||||
wm.ToolCallID = msg.ToolCallID
|
||||
wm.Name = msg.Name
|
||||
}
|
||||
|
||||
if msg.Role == "assistant" {
|
||||
if s.ReplayReasoningContent && msg.ReasoningContent != "" {
|
||||
rc := msg.ReasoningContent
|
||||
wm.ReasoningContent = &rc
|
||||
}
|
||||
// reasoning_details is OpenRouter's format; other vendors reject it.
|
||||
raw, ok := msg.ReasoningMetadata[metadataReasoningDetails]
|
||||
if ok && len(raw) > 0 && s.ThinkingFormat == catalog.ThinkingFormatOpenRouter {
|
||||
wm.ReasoningDetails = raw
|
||||
}
|
||||
}
|
||||
out = append(out, wm)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// contentParts flattens rich content to plain text for vendors that only
|
||||
// accept strings (WeKnora Cloud), otherwise returns the parts as-is.
|
||||
func (c *Client) contentParts(parts []wirePart) any {
|
||||
if c.cfg.Settings.SupportsMultiContent {
|
||||
return parts
|
||||
}
|
||||
var texts []string
|
||||
for _, p := range parts {
|
||||
if p.Type == "text" && p.Text != "" {
|
||||
texts = append(texts, p.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(texts, "\n")
|
||||
}
|
||||
|
||||
const metadataReasoningDetails = "reasoning_details"
|
||||
|
||||
// buildBody assembles the request body. It returns a map so vendor-specific
|
||||
// top-level fields can be added without a struct per vendor; key order in
|
||||
// the encoded JSON is alphabetical, which keeps golden tests stable.
|
||||
func (c *Client) buildBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
s := c.cfg.Settings
|
||||
body := map[string]any{
|
||||
"model": c.cfg.Endpoint.Model,
|
||||
"messages": c.convertMessages(messages),
|
||||
}
|
||||
if stream {
|
||||
body["stream"] = true
|
||||
if s.SupportsUsageInStreaming {
|
||||
body["stream_options"] = map[string]any{"include_usage": true}
|
||||
}
|
||||
}
|
||||
if s.SupportsStore {
|
||||
body["store"] = false
|
||||
}
|
||||
|
||||
if opts != nil {
|
||||
c.applySampling(body, opts)
|
||||
if budget := opts.CompletionBudget(); budget > 0 {
|
||||
field := s.MaxTokensField
|
||||
if field == "" {
|
||||
field = "max_completion_tokens"
|
||||
}
|
||||
body[field] = budget
|
||||
}
|
||||
c.applyTools(body, opts)
|
||||
if len(opts.Format) > 0 && s.SupportsResponseFormat {
|
||||
body["response_format"] = map[string]any{"type": "json_object"}
|
||||
msgs := body["messages"].([]wireMessage)
|
||||
if len(msgs) > 0 {
|
||||
last := &msgs[len(msgs)-1]
|
||||
if text, ok := last.Content.(string); ok {
|
||||
last.Content = text + fmt.Sprintf("\nUse this JSON schema: %s", opts.Format)
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.PromptCacheKey && api.ResolveCacheRetention(opts) != api.CacheRetentionNone {
|
||||
key := opts.PromptCacheKey
|
||||
if key == "" {
|
||||
key = c.cfg.SessionID
|
||||
}
|
||||
if key = api.ClampPromptCacheKey(key); key != "" {
|
||||
body["prompt_cache_key"] = key
|
||||
if api.ResolveCacheRetention(opts) == api.CacheRetentionLong {
|
||||
body["prompt_cache_retention"] = "24h"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c.applyThinking(body, opts, stream)
|
||||
|
||||
for k, v := range s.ExtraBody {
|
||||
if _, exists := body[k]; !exists {
|
||||
body[k] = v
|
||||
}
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (c *Client) applySampling(body map[string]any, opts *api.Options) {
|
||||
s := c.cfg.Settings
|
||||
if !s.SupportsTemperature {
|
||||
return
|
||||
}
|
||||
if s.FixedTemperature != nil {
|
||||
body["temperature"] = *s.FixedTemperature
|
||||
return
|
||||
}
|
||||
if opts.Temperature > 0 {
|
||||
body["temperature"] = opts.Temperature
|
||||
}
|
||||
if opts.TopP > 0 {
|
||||
body["top_p"] = opts.TopP
|
||||
}
|
||||
if opts.FrequencyPenalty > 0 {
|
||||
body["frequency_penalty"] = opts.FrequencyPenalty
|
||||
}
|
||||
if opts.PresencePenalty > 0 {
|
||||
body["presence_penalty"] = opts.PresencePenalty
|
||||
}
|
||||
if opts.Seed > 0 && s.SupportsSeed {
|
||||
body["seed"] = opts.Seed
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
|
||||
s := c.cfg.Settings
|
||||
if len(opts.Tools) == 0 {
|
||||
return
|
||||
}
|
||||
tools := make([]map[string]any, 0, len(opts.Tools))
|
||||
for _, tool := range opts.Tools {
|
||||
fn := map[string]any{
|
||||
"name": tool.Function.Name,
|
||||
"description": tool.Function.Description,
|
||||
}
|
||||
if len(tool.Function.Parameters) > 0 {
|
||||
fn["parameters"] = tool.Function.Parameters
|
||||
}
|
||||
tools = append(tools, map[string]any{"type": orDefault(tool.Type, "function"), "function": fn})
|
||||
}
|
||||
body["tools"] = tools
|
||||
if opts.ParallelToolCalls != nil && s.SupportsParallelToolCalls {
|
||||
body["parallel_tool_calls"] = *opts.ParallelToolCalls
|
||||
}
|
||||
if opts.ToolChoice == "" {
|
||||
return
|
||||
}
|
||||
switch opts.ToolChoice {
|
||||
case "none", "required", "auto":
|
||||
if s.AllowsToolChoice(opts.ToolChoice) {
|
||||
body["tool_choice"] = opts.ToolChoice
|
||||
}
|
||||
default:
|
||||
if s.AllowsToolChoice("function") {
|
||||
body["tool_choice"] = map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{"name": opts.ToolChoice},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// applyThinking encodes the requested reasoning level in the vendor's
|
||||
// dialect. See catalog.ThinkingFormat for the dialects.
|
||||
func (c *Client) applyThinking(body map[string]any, opts *api.Options, stream bool) {
|
||||
s := c.cfg.Settings
|
||||
if s.ThinkingFormat == catalog.ThinkingFormatNone || s.ThinkingFormat == "" {
|
||||
return
|
||||
}
|
||||
levels := c.cfg.ThinkingLevels
|
||||
level, requested := opts.Reasoning()
|
||||
if !requested {
|
||||
if !s.ThinkingAlwaysSend {
|
||||
return
|
||||
}
|
||||
level = api.ReasoningOff
|
||||
}
|
||||
if level.Graded() {
|
||||
level = levels.Clamp(level)
|
||||
}
|
||||
enabled := level.Enabled()
|
||||
if enabled && s.ThinkingDisableOnNonStream && !stream {
|
||||
enabled = false
|
||||
}
|
||||
if !enabled && !levels.Supports(api.ReasoningOff) {
|
||||
// Always-on reasoning model: there is nothing to switch off and the
|
||||
// vendor rejects the attempt.
|
||||
return
|
||||
}
|
||||
|
||||
effort := ""
|
||||
if enabled && level.Graded() && s.SupportsReasoningEffort {
|
||||
effort = levels.Value(level)
|
||||
}
|
||||
effortField := orDefault(s.ReasoningEffortField, "reasoning_effort")
|
||||
if enabled && opts != nil && opts.ThinkingBudgetTokens > 0 && s.ThinkingBudgetField != "" {
|
||||
body[s.ThinkingBudgetField] = opts.ThinkingBudgetTokens
|
||||
}
|
||||
|
||||
switch s.ThinkingFormat {
|
||||
case catalog.ThinkingFormatOpenAI:
|
||||
if enabled {
|
||||
if effort != "" {
|
||||
body[effortField] = effort
|
||||
}
|
||||
} else if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
|
||||
body[effortField] = *v
|
||||
}
|
||||
case catalog.ThinkingFormatThinkingType:
|
||||
if enabled {
|
||||
body["thinking"] = map[string]any{"type": orDefault(s.ThinkingEnabledValue, "enabled")}
|
||||
if effort != "" {
|
||||
body[effortField] = effort
|
||||
}
|
||||
} else {
|
||||
body["thinking"] = map[string]any{"type": "disabled"}
|
||||
}
|
||||
case catalog.ThinkingFormatEnableThinking:
|
||||
body["enable_thinking"] = enabled
|
||||
if effort != "" {
|
||||
body[effortField] = effort
|
||||
}
|
||||
case catalog.ThinkingFormatChatTemplateKwargs:
|
||||
body["chat_template_kwargs"] = map[string]any{"enable_thinking": enabled}
|
||||
case catalog.ThinkingFormatOpenRouter:
|
||||
if enabled {
|
||||
reasoning := map[string]any{}
|
||||
if effort != "" {
|
||||
reasoning["effort"] = effort
|
||||
} else {
|
||||
reasoning["enabled"] = true
|
||||
}
|
||||
body["reasoning"] = reasoning
|
||||
} else {
|
||||
body["reasoning"] = map[string]any{"enabled": false}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// finalizeBody applies transformations that need the JSON object form
|
||||
// (cache_control breakpoints) and returns the bytes to send.
|
||||
func (c *Client) finalizeBody(body map[string]any, opts *api.Options) (map[string]any, error) {
|
||||
s := c.cfg.Settings
|
||||
if s.CacheControlFormat != "anthropic" {
|
||||
return body, nil
|
||||
}
|
||||
marker := api.CacheControlFor(api.ResolveCacheRetention(opts), "1h")
|
||||
if marker == nil {
|
||||
return body, nil
|
||||
}
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api.ApplyCacheControlBreakpoints(payload, marker)
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
// BuildRequestBody is the golden-test entry point: it returns the exact
|
||||
// JSON object that would be sent for the given inputs.
|
||||
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
body, err := c.buildBody(messages, opts, stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.finalizeBody(body, opts)
|
||||
}
|
||||
|
||||
func orDefault(v, def string) string {
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
|
@ -0,0 +1,552 @@
|
|||
package openairesponses
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const defaultPath = "/responses"
|
||||
|
||||
// Client talks the Responses protocol to one endpoint.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
}
|
||||
|
||||
// New creates a client. The endpoint must already carry auth and headers.
|
||||
func New(cfg Config) *Client {
|
||||
if cfg.ThinkingLevels == nil {
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
}
|
||||
return &Client{cfg: cfg}
|
||||
}
|
||||
|
||||
// GetModelName returns the wire model name.
|
||||
func (c *Client) GetModelName() string { return c.cfg.Endpoint.Model }
|
||||
|
||||
// GetModelID returns WeKnora's model identifier.
|
||||
func (c *Client) GetModelID() string { return c.cfg.Endpoint.ModelID }
|
||||
|
||||
// Settings exposes the resolved settings (diagnostics, tests).
|
||||
func (c *Client) Settings() Config { return c.cfg }
|
||||
|
||||
func (c *Client) url() string { return c.cfg.Endpoint.Resolve(defaultPath) }
|
||||
|
||||
func (c *Client) send(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
|
||||
) (*http.Response, []byte, error) {
|
||||
opts = api.WithSessionCacheKey(ctx, opts)
|
||||
body, err := c.BuildRequestBody(messages, opts, stream)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
url := c.url()
|
||||
req, data, err := c.cfg.Endpoint.NewRequest(ctx, url, body, stream)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if c.cfg.Settings.PromptCacheKey {
|
||||
key := c.cfg.SessionID
|
||||
if opts != nil && opts.PromptCacheKey != "" {
|
||||
key = opts.PromptCacheKey
|
||||
}
|
||||
api.AttachSessionAffinityHeaders(req, api.ClampPromptCacheKey(key))
|
||||
}
|
||||
api.LogRequest(ctx, url, c.cfg.Endpoint.Model, data, stream)
|
||||
resp, err := c.cfg.Endpoint.Do(req)
|
||||
if err != nil {
|
||||
return nil, data, err
|
||||
}
|
||||
return resp, data, nil
|
||||
}
|
||||
|
||||
// Chat performs a non-streaming response creation.
|
||||
func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Options) (*types.ChatResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultChatTimeout)
|
||||
defer cancel()
|
||||
|
||||
resp, _, err := c.send(ctx, messages, opts, false)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, _, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, false)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create response: %w", err)
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
result, err := c.parseResponse(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api.LogUsage(ctx, c.cfg.Endpoint.Model, &result.Usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ChatStream performs a streaming response creation.
|
||||
func (c *Client) ChatStream(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultStreamTimeout)
|
||||
|
||||
resp, data, err := c.send(ctx, messages, opts, true)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, fmt.Errorf("create response stream: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ch := make(chan types.StreamResponse)
|
||||
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
|
||||
if dumper != nil {
|
||||
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
|
||||
}
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer close(ch)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if dumper != nil {
|
||||
defer dumper.Close()
|
||||
}
|
||||
c.processStream(ctx, resp.Body, ch, dumper)
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// --- response decoding ---
|
||||
|
||||
type rawContentPart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// rawOutputItem is the union of the output item shapes this package reads:
|
||||
// message, function_call and reasoning.
|
||||
type rawOutputItem struct {
|
||||
Type string `json:"type"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
Content []rawContentPart `json:"content,omitempty"`
|
||||
CallID string `json:"call_id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Arguments string `json:"arguments,omitempty"`
|
||||
Summary []rawContentPart `json:"summary,omitempty"`
|
||||
}
|
||||
|
||||
type rawUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
InputTokensDetails *struct {
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
} `json:"input_tokens_details,omitempty"`
|
||||
}
|
||||
|
||||
func (u rawUsage) toTokenUsage() types.TokenUsage {
|
||||
out := types.TokenUsage{
|
||||
PromptTokens: u.InputTokens,
|
||||
CompletionTokens: u.OutputTokens,
|
||||
TotalTokens: u.TotalTokens,
|
||||
}
|
||||
if out.TotalTokens == 0 {
|
||||
out.TotalTokens = out.PromptTokens + out.CompletionTokens
|
||||
}
|
||||
if u.InputTokensDetails != nil {
|
||||
cached := u.InputTokensDetails.CachedTokens
|
||||
out.SetPromptCacheUsage(cached, 0, max(0, u.InputTokens-cached), true)
|
||||
} else {
|
||||
out.SetPromptCacheUsage(0, 0, 0, false)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type rawError struct {
|
||||
Code any `json:"code,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type rawResponse struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
IncompleteDetails *struct {
|
||||
Reason string `json:"reason"`
|
||||
} `json:"incomplete_details,omitempty"`
|
||||
Output []json.RawMessage `json:"output,omitempty"`
|
||||
Usage *rawUsage `json:"usage,omitempty"`
|
||||
Error *rawError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// finishReason maps the response status onto the Chat Completions
|
||||
// vocabulary the rest of the engine understands.
|
||||
func (r *rawResponse) finishReason(hasToolCalls bool) string {
|
||||
if hasToolCalls {
|
||||
return "tool_calls"
|
||||
}
|
||||
if r != nil && r.Status == "incomplete" && r.IncompleteDetails != nil {
|
||||
switch r.IncompleteDetails.Reason {
|
||||
case "max_output_tokens":
|
||||
return "length"
|
||||
case "content_filter":
|
||||
return "content_filter"
|
||||
}
|
||||
}
|
||||
return "stop"
|
||||
}
|
||||
|
||||
func decodeItem(raw json.RawMessage) (rawOutputItem, error) {
|
||||
var item rawOutputItem
|
||||
if err := json.Unmarshal(raw, &item); err != nil {
|
||||
return rawOutputItem{}, fmt.Errorf("decode output item: %w", err)
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// streamItem decodes the item carried by an output_item event. An event that
|
||||
// carries no item at all is simply nothing to decode, but an item we cannot
|
||||
// read is lost output, possibly a whole function_call, so the caller must
|
||||
// surface it instead of moving on.
|
||||
func streamItem(raw json.RawMessage) (rawOutputItem, bool, error) {
|
||||
if len(raw) == 0 {
|
||||
return rawOutputItem{}, false, nil
|
||||
}
|
||||
item, err := decodeItem(raw)
|
||||
if err != nil {
|
||||
return rawOutputItem{}, false, err
|
||||
}
|
||||
return item, true, nil
|
||||
}
|
||||
|
||||
func itemText(item rawOutputItem) string {
|
||||
var b strings.Builder
|
||||
for _, part := range item.Content {
|
||||
if part.Type == "output_text" {
|
||||
b.WriteString(part.Text)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func itemSummary(item rawOutputItem) string {
|
||||
texts := make([]string, 0, len(item.Summary))
|
||||
for _, part := range item.Summary {
|
||||
if part.Text != "" {
|
||||
texts = append(texts, part.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(texts, "\n")
|
||||
}
|
||||
|
||||
func toolCallMetadata(item rawOutputItem) types.ToolCallMetadata {
|
||||
if len(item.ID) == 0 || string(item.ID) == "null" {
|
||||
return nil
|
||||
}
|
||||
return types.ToolCallMetadata{metadataToolCallItemID: item.ID}
|
||||
}
|
||||
|
||||
func reasoningMetadata(items []json.RawMessage) types.ProviderMetadata {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
merged, err := json.Marshal(items)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return types.ProviderMetadata{metadataReasoningItems: merged}
|
||||
}
|
||||
|
||||
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
|
||||
var env rawResponse
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
if env.Error != nil && env.Error.Message != "" {
|
||||
return nil, fmt.Errorf("API error: %s", env.Error.Message)
|
||||
}
|
||||
if env.Status == "failed" {
|
||||
return nil, fmt.Errorf("API error: response failed")
|
||||
}
|
||||
|
||||
result := &types.ChatResponse{}
|
||||
var content, reasoning []string
|
||||
var reasoningItems []json.RawMessage
|
||||
for _, rawItem := range env.Output {
|
||||
// An output item we cannot read may be the round's tool call. Dropping
|
||||
// it hands the agent what looks like a plain answer, so fail instead.
|
||||
item, err := decodeItem(rawItem)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch item.Type {
|
||||
case "message":
|
||||
content = append(content, itemText(item))
|
||||
case "function_call":
|
||||
result.ToolCalls = append(result.ToolCalls, types.LLMToolCall{
|
||||
ID: item.CallID,
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: item.Name, Arguments: item.Arguments},
|
||||
ProviderMetadata: toolCallMetadata(item),
|
||||
})
|
||||
case "reasoning":
|
||||
if summary := itemSummary(item); summary != "" {
|
||||
reasoning = append(reasoning, summary)
|
||||
}
|
||||
reasoningItems = append(reasoningItems, rawItem)
|
||||
}
|
||||
}
|
||||
result.Content = strings.Join(content, "")
|
||||
result.ReasoningContent = strings.Join(reasoning, "\n")
|
||||
result.ReasoningMetadata = reasoningMetadata(reasoningItems)
|
||||
result.FinishReason = env.finishReason(len(result.ToolCalls) > 0)
|
||||
// Classify the cache status even without a usage block, so an empty
|
||||
// CacheStatus never reaches the usage dashboards as a silent miss.
|
||||
usage := rawUsage{}
|
||||
if env.Usage != nil {
|
||||
usage = *env.Usage
|
||||
}
|
||||
result.Usage = usage.toTokenUsage()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// --- streaming ---
|
||||
|
||||
// rawStreamEvent is the union of the fields this package reads from the
|
||||
// Responses SSE events. Every event carries "type".
|
||||
type rawStreamEvent struct {
|
||||
Type string `json:"type"`
|
||||
Delta string `json:"delta,omitempty"`
|
||||
ItemID string `json:"item_id,omitempty"`
|
||||
OutputIndex int `json:"output_index,omitempty"`
|
||||
SummaryIndex int `json:"summary_index,omitempty"`
|
||||
Item json.RawMessage `json:"item,omitempty"`
|
||||
Response *rawResponse `json:"response,omitempty"`
|
||||
// Message/Code are set on the top-level "error" event.
|
||||
Message string `json:"message,omitempty"`
|
||||
Code any `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// streamState tracks the function_call items seen so far so argument deltas
|
||||
// can be routed to the assembler index that announced the call.
|
||||
type streamState struct {
|
||||
toolIndex map[string]int // item id -> assembler index
|
||||
argsSeen map[string]bool
|
||||
nextToolIndex int
|
||||
reasoningItems []json.RawMessage
|
||||
}
|
||||
|
||||
func (st *streamState) indexFor(itemID string) int {
|
||||
if idx, ok := st.toolIndex[itemID]; ok {
|
||||
return idx
|
||||
}
|
||||
idx := st.nextToolIndex
|
||||
st.nextToolIndex++
|
||||
st.toolIndex[itemID] = idx
|
||||
return idx
|
||||
}
|
||||
|
||||
func (c *Client) processStream(
|
||||
ctx context.Context, body io.Reader, ch chan<- types.StreamResponse, dumper *api.StreamPacketDumper,
|
||||
) {
|
||||
assembler := api.NewStreamAssembler(ctx, c.cfg.Endpoint.Model)
|
||||
reader := api.NewSSEReader(body)
|
||||
st := &streamState{toolIndex: map[string]int{}, argsSeen: map[string]bool{}}
|
||||
|
||||
finish := func() {
|
||||
assembler.ReasoningMetadata = reasoningMetadata(st.reasoningItems)
|
||||
assembler.End(ch)
|
||||
}
|
||||
|
||||
for {
|
||||
// The consumer went away (client disconnect, aborted agent turn): stop
|
||||
// decoding a stream nobody will read instead of spinning to EOF.
|
||||
if assembler.Aborted() {
|
||||
return
|
||||
}
|
||||
event, err := reader.ReadEvent()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
finish()
|
||||
} else {
|
||||
assembler.Fail(ch, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if event == nil {
|
||||
continue
|
||||
}
|
||||
if event.Done {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if len(event.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
if dumper != nil {
|
||||
raw := make([]byte, len(event.Data))
|
||||
copy(raw, event.Data)
|
||||
dumper.WritePacketRaw(raw)
|
||||
}
|
||||
|
||||
var ev rawStreamEvent
|
||||
if err := json.Unmarshal(event.Data, &ev); err != nil {
|
||||
// An event whose *type* we do not know is routine and the switch
|
||||
// below already ignores it. A payload that is not JSON at all is
|
||||
// not: it is a truncated frame or a gateway error page, i.e. a
|
||||
// hole in the answer. Skipping it runs the loop to EOF, which the
|
||||
// caller cannot tell from a complete reply and then stores as the
|
||||
// model's answer. Fail, as the Completions loop does.
|
||||
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
switch ev.Type {
|
||||
case "response.output_text.delta":
|
||||
if ev.Delta != "" {
|
||||
assembler.Process(ch, api.Delta{Content: ev.Delta})
|
||||
}
|
||||
case "response.reasoning_summary_text.delta", "response.reasoning_text.delta":
|
||||
if ev.Delta != "" {
|
||||
assembler.Process(ch, api.Delta{Reasoning: ev.Delta})
|
||||
}
|
||||
case "response.reasoning_summary_part.added":
|
||||
// Mirror the non-stream join of summary parts with a newline.
|
||||
if ev.SummaryIndex > 0 {
|
||||
assembler.Process(ch, api.Delta{Reasoning: "\n"})
|
||||
}
|
||||
case "response.output_item.added":
|
||||
item, ok, err := streamItem(ev.Item)
|
||||
if err != nil {
|
||||
assembler.Fail(ch, err)
|
||||
return
|
||||
}
|
||||
if !ok || item.Type != "function_call" {
|
||||
continue
|
||||
}
|
||||
itemID := streamItemID(item, ev.OutputIndex)
|
||||
idx := st.indexFor(itemID)
|
||||
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
|
||||
Index: idx, ID: item.CallID, Type: "function", Name: item.Name,
|
||||
}}})
|
||||
assembler.SetToolCallMetadata(idx, toolCallMetadata(item))
|
||||
case "response.function_call_arguments.delta":
|
||||
if ev.Delta == "" {
|
||||
continue
|
||||
}
|
||||
// Correlate on the same key output_item.added registered. Vendors
|
||||
// that omit item ids would otherwise send every call's arguments
|
||||
// to the single index keyed by "", merging distinct tool calls.
|
||||
key := streamEventKey(ev.ItemID, ev.OutputIndex)
|
||||
st.argsSeen[key] = true
|
||||
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
|
||||
Index: st.indexFor(key), Arguments: ev.Delta,
|
||||
}}})
|
||||
case "response.output_item.done":
|
||||
item, ok, err := streamItem(ev.Item)
|
||||
if err != nil {
|
||||
assembler.Fail(ch, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch item.Type {
|
||||
case "reasoning":
|
||||
st.reasoningItems = append(st.reasoningItems, ev.Item)
|
||||
case "function_call":
|
||||
// Providers that never stream argument deltas deliver the
|
||||
// arguments only on the done item.
|
||||
itemID := streamItemID(item, ev.OutputIndex)
|
||||
if !st.argsSeen[itemID] && item.Arguments != "" {
|
||||
st.argsSeen[itemID] = true
|
||||
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
|
||||
Index: st.indexFor(itemID), ID: item.CallID, Type: "function",
|
||||
Name: item.Name, Arguments: item.Arguments,
|
||||
}}})
|
||||
assembler.SetToolCallMetadata(st.indexFor(itemID), toolCallMetadata(item))
|
||||
}
|
||||
}
|
||||
case "response.completed", "response.incomplete":
|
||||
c.completeStream(ch, assembler, st, ev.Response, ev.Type == "response.incomplete")
|
||||
return
|
||||
case "response.failed":
|
||||
msg := "response failed"
|
||||
if ev.Response != nil && ev.Response.Error != nil && ev.Response.Error.Message != "" {
|
||||
msg = ev.Response.Error.Message
|
||||
}
|
||||
assembler.Fail(ch, fmt.Errorf("API stream error: %s", msg))
|
||||
return
|
||||
case "error":
|
||||
assembler.Fail(ch, fmt.Errorf("API stream error: %s", orDefault(ev.Message, "unknown error")))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// streamItemID returns the item id used to correlate added/delta/done
|
||||
// events, falling back to the output index when the vendor omits ids.
|
||||
func streamItemID(item rawOutputItem, outputIndex int) string {
|
||||
var id string
|
||||
if len(item.ID) > 0 {
|
||||
_ = json.Unmarshal(item.ID, &id)
|
||||
}
|
||||
return streamEventKey(id, outputIndex)
|
||||
}
|
||||
|
||||
// streamEventKey is the correlation key for one output item: its id when the
|
||||
// vendor sends one, otherwise its position in the output list.
|
||||
func streamEventKey(itemID string, outputIndex int) string {
|
||||
if itemID != "" {
|
||||
return itemID
|
||||
}
|
||||
return fmt.Sprintf("output_index:%d", outputIndex)
|
||||
}
|
||||
|
||||
// completeStream handles the terminal response.completed / response.incomplete
|
||||
// event: usage, finish reason, reasoning artifacts and the closing chunks.
|
||||
func (c *Client) completeStream(
|
||||
ch chan<- types.StreamResponse, assembler *api.StreamAssembler, st *streamState, resp *rawResponse, incomplete bool,
|
||||
) {
|
||||
if resp != nil {
|
||||
if resp.Usage != nil {
|
||||
assembler.SetUsage(resp.Usage.toTokenUsage())
|
||||
}
|
||||
// Fall back to the final response body for reasoning items when the
|
||||
// vendor never emitted output_item.done for them.
|
||||
if len(st.reasoningItems) == 0 {
|
||||
for _, rawItem := range resp.Output {
|
||||
// Tolerated on purpose, unlike the item events above: the
|
||||
// deltas already carried the answer and its tool calls, so an
|
||||
// unreadable item here costs at most a reasoning artifact.
|
||||
if item, err := decodeItem(rawItem); err == nil && item.Type == "reasoning" {
|
||||
st.reasoningItems = append(st.reasoningItems, rawItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finishReason := resp.finishReason(assembler.ToolCallCount() > 0)
|
||||
if incomplete && finishReason == "stop" {
|
||||
finishReason = "length"
|
||||
}
|
||||
assembler.Process(ch, api.Delta{FinishReason: finishReason})
|
||||
assembler.ReasoningMetadata = reasoningMetadata(st.reasoningItems)
|
||||
assembler.End(ch)
|
||||
}
|
||||
|
|
@ -0,0 +1,677 @@
|
|||
package openairesponses
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func newTestClient(t *testing.T, server *httptest.Server, reasoning bool) *Client {
|
||||
t.Helper()
|
||||
ep := api.Endpoint{
|
||||
Model: "gpt-5",
|
||||
ModelID: "model-1",
|
||||
Auth: api.BearerAuth("sk-test"),
|
||||
}
|
||||
if server != nil {
|
||||
ep.BaseURL = server.URL
|
||||
ep.Client = server.Client()
|
||||
} else {
|
||||
ep.BaseURL = "https://api.openai.com/v1"
|
||||
}
|
||||
return New(Config{
|
||||
Endpoint: ep,
|
||||
Settings: catalog.DefaultOpenAIResponses(),
|
||||
Reasoning: reasoning,
|
||||
SessionID: "session-fallback",
|
||||
})
|
||||
}
|
||||
|
||||
// roundTrip marshals and re-decodes the body so struct-typed values compare
|
||||
// as plain JSON.
|
||||
func roundTrip(t *testing.T, body map[string]any) map[string]any {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal body: %v", err)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(data, &out); err != nil {
|
||||
t.Fatalf("unmarshal body: %v", err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func conversation() []api.Message {
|
||||
return []api.Message{
|
||||
{Role: "system", Content: "You are a weather assistant."},
|
||||
{Role: "user", Content: "What's the weather in Paris?"},
|
||||
{
|
||||
Role: "assistant",
|
||||
ToolCalls: []api.ToolCall{{
|
||||
ID: "call_1",
|
||||
Type: "function",
|
||||
Function: api.FunctionCall{
|
||||
Name: "get_weather",
|
||||
Arguments: `{"city":"Paris"}`,
|
||||
},
|
||||
ProviderMetadata: types.ToolCallMetadata{
|
||||
"openai_responses_item_id": json.RawMessage(`"fc_1"`),
|
||||
},
|
||||
}},
|
||||
ReasoningMetadata: types.ProviderMetadata{
|
||||
"openai_responses_reasoning": json.RawMessage(
|
||||
`[{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"enc-abc"}]`),
|
||||
},
|
||||
},
|
||||
{Role: "tool", ToolCallID: "call_1", Name: "get_weather", Content: "Sunny, 24C"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestBodyGolden(t *testing.T) {
|
||||
c := newTestClient(t, nil, true)
|
||||
opts := &api.Options{
|
||||
Temperature: 0.7,
|
||||
MaxCompletionTokens: 1000,
|
||||
ReasoningEffort: api.ReasoningHigh,
|
||||
PromptCacheKey: "cache-key-1",
|
||||
Tools: []api.Tool{{
|
||||
Type: "function",
|
||||
Function: api.FunctionDef{
|
||||
Name: "get_weather",
|
||||
Description: "Get weather",
|
||||
Parameters: json.RawMessage(`{"type":"object","properties":{"city":{"type":"string"}}}`),
|
||||
},
|
||||
}},
|
||||
ToolChoice: "auto",
|
||||
}
|
||||
body, err := c.BuildRequestBody(conversation(), opts, false)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
got := roundTrip(t, body)
|
||||
|
||||
want := map[string]any{
|
||||
"model": "gpt-5",
|
||||
"store": false,
|
||||
"instructions": "You are a weather assistant.",
|
||||
"input": []any{
|
||||
map[string]any{"type": "message", "role": "user", "content": "What's the weather in Paris?"},
|
||||
map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{}, "encrypted_content": "enc-abc"},
|
||||
map[string]any{
|
||||
"type": "function_call", "id": "fc_1", "call_id": "call_1",
|
||||
"name": "get_weather", "arguments": `{"city":"Paris"}`,
|
||||
},
|
||||
map[string]any{"type": "function_call_output", "call_id": "call_1", "output": "Sunny, 24C"},
|
||||
},
|
||||
"max_output_tokens": float64(1000),
|
||||
"tools": []any{
|
||||
map[string]any{
|
||||
"type": "function",
|
||||
"name": "get_weather",
|
||||
"description": "Get weather",
|
||||
"parameters": map[string]any{
|
||||
"type": "object", "properties": map[string]any{"city": map[string]any{"type": "string"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
"tool_choice": "auto",
|
||||
"reasoning": map[string]any{"effort": "high", "summary": "auto"},
|
||||
"include": []any{"reasoning.encrypted_content"},
|
||||
"prompt_cache_key": "cache-key-1",
|
||||
}
|
||||
wantJSON, _ := json.Marshal(want)
|
||||
gotJSON, _ := json.Marshal(got)
|
||||
if string(wantJSON) != string(gotJSON) {
|
||||
t.Fatalf("body mismatch\n got: %s\nwant: %s", gotJSON, wantJSON)
|
||||
}
|
||||
for _, absent := range []string{"temperature", "stream", "messages", "frequency_penalty", "presence_penalty"} {
|
||||
if _, ok := got[absent]; ok {
|
||||
t.Errorf("unexpected key %q in body", absent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestBodyNonReasoningStream(t *testing.T) {
|
||||
c := newTestClient(t, nil, false)
|
||||
c.cfg.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: api.StringPtr("none")}
|
||||
off := false
|
||||
opts := &api.Options{
|
||||
Temperature: 0.3,
|
||||
TopP: 0.9,
|
||||
Thinking: &off,
|
||||
CacheRetention: api.CacheRetentionLong,
|
||||
MaxTokens: 4,
|
||||
Format: json.RawMessage(`{"type":"object"}`),
|
||||
}
|
||||
body, err := c.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, opts, true)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
got := roundTrip(t, body)
|
||||
|
||||
if got["stream"] != true {
|
||||
t.Errorf("stream = %v, want true", got["stream"])
|
||||
}
|
||||
if got["temperature"] != 0.3 || got["top_p"] != 0.9 {
|
||||
t.Errorf("sampling = %v / %v", got["temperature"], got["top_p"])
|
||||
}
|
||||
if got["max_output_tokens"] != float64(16) {
|
||||
t.Errorf("max_output_tokens = %v, want 16 (minimum)", got["max_output_tokens"])
|
||||
}
|
||||
if got["prompt_cache_key"] != "session-fallback" {
|
||||
t.Errorf("prompt_cache_key = %v", got["prompt_cache_key"])
|
||||
}
|
||||
if got["prompt_cache_retention"] != "24h" {
|
||||
t.Errorf("prompt_cache_retention = %v", got["prompt_cache_retention"])
|
||||
}
|
||||
if _, ok := got["include"]; ok {
|
||||
t.Errorf("include must not be sent for non-reasoning models")
|
||||
}
|
||||
reasoning, _ := got["reasoning"].(map[string]any)
|
||||
if reasoning["effort"] != "none" {
|
||||
t.Errorf("reasoning = %v, want effort none", got["reasoning"])
|
||||
}
|
||||
text, _ := got["text"].(map[string]any)
|
||||
format, _ := text["format"].(map[string]any)
|
||||
if format["type"] != "json_object" {
|
||||
t.Errorf("text.format = %v", got["text"])
|
||||
}
|
||||
input, _ := got["input"].([]any)
|
||||
if len(input) != 1 {
|
||||
t.Fatalf("input = %v", got["input"])
|
||||
}
|
||||
msg := input[0].(map[string]any)
|
||||
if content, _ := msg["content"].(string); !strings.HasSuffix(content, `Use this JSON schema: {"type":"object"}`) {
|
||||
t.Errorf("schema hint not appended: %q", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestBodyOffWithoutMapping(t *testing.T) {
|
||||
c := newTestClient(t, nil, false)
|
||||
off := false
|
||||
body, err := c.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, &api.Options{Thinking: &off}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
if _, ok := body["reasoning"]; ok {
|
||||
t.Fatalf("reasoning must be omitted when off has no vendor value: %v", body["reasoning"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestBodyImagesAndAuto(t *testing.T) {
|
||||
c := newTestClient(t, nil, true)
|
||||
on := true
|
||||
msgs := []api.Message{{
|
||||
Role: "user",
|
||||
MultiContent: []api.MessageContentPart{
|
||||
{Type: "text", Text: "Describe"},
|
||||
{Type: "image_url", ImageURL: &api.ImageURL{URL: "https://example.com/a.png"}},
|
||||
},
|
||||
}}
|
||||
body, err := c.BuildRequestBody(msgs, &api.Options{Thinking: &on}, false)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
got := roundTrip(t, body)
|
||||
input := got["input"].([]any)
|
||||
parts := input[0].(map[string]any)["content"].([]any)
|
||||
if len(parts) != 2 {
|
||||
t.Fatalf("parts = %v", parts)
|
||||
}
|
||||
img := parts[1].(map[string]any)
|
||||
if img["type"] != "input_image" || img["image_url"] != "https://example.com/a.png" || img["detail"] != "auto" {
|
||||
t.Errorf("image part = %v", img)
|
||||
}
|
||||
reasoning := got["reasoning"].(map[string]any)
|
||||
if _, ok := reasoning["effort"]; ok {
|
||||
t.Errorf("auto must not send effort: %v", reasoning)
|
||||
}
|
||||
if reasoning["summary"] != "auto" {
|
||||
t.Errorf("reasoning summary = %v", reasoning)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatDecodesResponse(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var gotPath string
|
||||
var gotHeaders http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
gotHeaders = r.Header.Clone()
|
||||
_, _ = io.ReadAll(r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id": "resp_1",
|
||||
"status": "completed",
|
||||
"output": [
|
||||
{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"Think A"},
|
||||
{"type":"summary_text","text":"Think B"}],"encrypted_content":"enc"},
|
||||
{"type":"message","id":"msg_1","role":"assistant","status":"completed",
|
||||
"content":[{"type":"output_text","text":"Hello "},{"type":"output_text","text":"world"}]},
|
||||
{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather",
|
||||
"arguments":"{\"city\":\"Paris\"}","status":"completed"}
|
||||
],
|
||||
"usage": {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120,
|
||||
"input_tokens_details": {"cached_tokens": 60}}
|
||||
}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, true)
|
||||
resp, err := c.Chat(
|
||||
context.Background(),
|
||||
[]api.Message{{Role: "user", Content: "hi"}},
|
||||
&api.Options{PromptCacheKey: "k1"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Chat: %v", err)
|
||||
}
|
||||
if gotPath != "/responses" {
|
||||
t.Errorf("path = %q", gotPath)
|
||||
}
|
||||
if gotHeaders.Get("Authorization") != "Bearer sk-test" {
|
||||
t.Errorf("auth header = %q", gotHeaders.Get("Authorization"))
|
||||
}
|
||||
if gotHeaders.Get("x-session-affinity") != "k1" {
|
||||
t.Errorf("affinity header = %q", gotHeaders.Get("x-session-affinity"))
|
||||
}
|
||||
if resp.Content != "Hello world" {
|
||||
t.Errorf("content = %q", resp.Content)
|
||||
}
|
||||
if resp.ReasoningContent != "Think A\nThink B" {
|
||||
t.Errorf("reasoning = %q", resp.ReasoningContent)
|
||||
}
|
||||
if resp.FinishReason != "tool_calls" {
|
||||
t.Errorf("finish = %q", resp.FinishReason)
|
||||
}
|
||||
if len(resp.ToolCalls) != 1 {
|
||||
t.Fatalf("tool calls = %+v", resp.ToolCalls)
|
||||
}
|
||||
tc := resp.ToolCalls[0]
|
||||
if tc.ID != "call_1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
|
||||
tc.Function.Arguments != `{"city":"Paris"}` {
|
||||
t.Errorf("tool call = %+v", tc)
|
||||
}
|
||||
if string(tc.ProviderMetadata["openai_responses_item_id"]) != `"fc_1"` {
|
||||
t.Errorf("item id metadata = %s", tc.ProviderMetadata["openai_responses_item_id"])
|
||||
}
|
||||
var items []map[string]any
|
||||
if err := json.Unmarshal(resp.ReasoningMetadata["openai_responses_reasoning"], &items); err != nil {
|
||||
t.Fatalf("reasoning metadata: %v", err)
|
||||
}
|
||||
if len(items) != 1 || items[0]["id"] != "rs_1" || items[0]["encrypted_content"] != "enc" {
|
||||
t.Errorf("reasoning items = %v", items)
|
||||
}
|
||||
u := resp.Usage
|
||||
if u.PromptTokens != 100 || u.CompletionTokens != 20 || u.TotalTokens != 120 {
|
||||
t.Errorf("usage = %+v", u)
|
||||
}
|
||||
if u.CacheReadTokens != 60 || u.CacheMissTokens != 40 || !u.CacheReported ||
|
||||
u.CacheStatus != types.PromptCacheStatusHit {
|
||||
t.Errorf("cache usage = %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatIncompleteAndError(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
payload := `{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":` +
|
||||
`[{"type":"message","content":[{"type":"output_text","text":"partial"}]}],` +
|
||||
`"usage":{"input_tokens":1,"output_tokens":2}}`
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(payload))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, false)
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Chat: %v", err)
|
||||
}
|
||||
if resp.FinishReason != "length" || resp.Content != "partial" {
|
||||
t.Errorf("resp = %+v", resp)
|
||||
}
|
||||
if resp.Usage.TotalTokens != 3 || resp.Usage.CacheReported ||
|
||||
resp.Usage.CacheStatus != types.PromptCacheStatusUnreported {
|
||||
t.Errorf("usage = %+v", resp.Usage)
|
||||
}
|
||||
|
||||
payload = `{"error":{"type":"invalid_request_error","message":"bad model"}}`
|
||||
_, err = c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "bad model") {
|
||||
t.Fatalf("expected API error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func sseBody(events ...string) string {
|
||||
var b strings.Builder
|
||||
for _, ev := range events {
|
||||
var probe struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(ev), &probe)
|
||||
fmt.Fprintf(&b, "event: %s\ndata: %s\n\n", probe.Type, ev)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func TestChatStreamAssemblesToolCall(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
body := sseBody(
|
||||
`{"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
|
||||
`{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`,
|
||||
`{"type":"response.reasoning_summary_text.delta",`+
|
||||
`"item_id":"rs_1","output_index":0,"summary_index":0,"delta":"thinking..."}`,
|
||||
`{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning",`+
|
||||
`"id":"rs_1","summary":[{"type":"summary_text","text":"thinking..."}],"encrypted_content":"enc"}}`,
|
||||
`{"type":"response.output_item.added","output_index":1,`+
|
||||
`"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`,
|
||||
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":1,"delta":"Hello"}`,
|
||||
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":1,"delta":" world"}`,
|
||||
`{"type":"response.output_item.done","output_index":1,"item":{"type":"message",`+
|
||||
`"id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"Hello world"}]}}`,
|
||||
`{"type":"response.output_item.added","output_index":2,"item":{"type":"function_call",`+
|
||||
`"id":"fc_1","call_id":"call_1","name":"get_weather","arguments":""}}`,
|
||||
`{"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":2,"delta":"{\"city\":"}`,
|
||||
`{"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":2,"delta":"\"Paris\"}"}`,
|
||||
`{"type":"response.function_call_arguments.done",`+
|
||||
`"item_id":"fc_1","output_index":2,"arguments":"{\"city\":\"Paris\"}"}`,
|
||||
`{"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc_1","call_id":`+
|
||||
`"call_1","name":"get_weather","arguments":"{\"city\":\"Paris\"}","status":"completed"}}`,
|
||||
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_to`+
|
||||
`kens":50,"output_tokens":10,"total_tokens":60,"input_tokens_details":{"cached_tokens":0}}}}`,
|
||||
)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
var req map[string]any
|
||||
if err := json.Unmarshal(raw, &req); err != nil || req["stream"] != true {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, true)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var events []types.StreamResponse
|
||||
for ev := range ch {
|
||||
events = append(events, ev)
|
||||
}
|
||||
if len(events) == 0 {
|
||||
t.Fatal("no events")
|
||||
}
|
||||
|
||||
var thinking, answer string
|
||||
var sawToolCallEvent, sawThinkingDone bool
|
||||
for _, ev := range events {
|
||||
switch ev.ResponseType {
|
||||
case types.ResponseTypeThinking:
|
||||
if ev.Done {
|
||||
sawThinkingDone = true
|
||||
} else {
|
||||
thinking += ev.Content
|
||||
}
|
||||
case types.ResponseTypeAnswer:
|
||||
answer += ev.Content
|
||||
case types.ResponseTypeToolCall:
|
||||
sawToolCallEvent = true
|
||||
if ev.Data["tool_name"] != "get_weather" || ev.Data["tool_call_id"] != "call_1" {
|
||||
t.Errorf("tool call event data = %v", ev.Data)
|
||||
}
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("unexpected error event: %s", ev.Content)
|
||||
}
|
||||
}
|
||||
if thinking != "thinking..." || !sawThinkingDone {
|
||||
t.Errorf("thinking = %q done=%t", thinking, sawThinkingDone)
|
||||
}
|
||||
if answer != "Hello world" {
|
||||
t.Errorf("answer = %q", answer)
|
||||
}
|
||||
if !sawToolCallEvent {
|
||||
t.Error("missing ResponseTypeToolCall event")
|
||||
}
|
||||
|
||||
final := events[len(events)-1]
|
||||
if final.ResponseType != types.ResponseTypeAnswer || !final.Done {
|
||||
t.Fatalf("final event = %+v", final)
|
||||
}
|
||||
if final.Usage == nil || final.Usage.PromptTokens != 50 || final.Usage.CompletionTokens != 10 ||
|
||||
final.Usage.TotalTokens != 60 || !final.Usage.CacheReported {
|
||||
t.Errorf("final usage = %+v", final.Usage)
|
||||
}
|
||||
if final.FinishReason != "tool_calls" {
|
||||
t.Errorf("final finish = %q", final.FinishReason)
|
||||
}
|
||||
if len(final.ToolCalls) != 1 {
|
||||
t.Fatalf("final tool calls = %+v", final.ToolCalls)
|
||||
}
|
||||
tc := final.ToolCalls[0]
|
||||
if tc.ID != "call_1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
|
||||
tc.Function.Arguments != `{"city":"Paris"}` {
|
||||
t.Errorf("assembled tool call = %+v", tc)
|
||||
}
|
||||
if string(tc.ProviderMetadata["openai_responses_item_id"]) != `"fc_1"` {
|
||||
t.Errorf("item id metadata = %s", tc.ProviderMetadata["openai_responses_item_id"])
|
||||
}
|
||||
md, _ := final.Data["reasoning_metadata"].(types.ProviderMetadata)
|
||||
var items []map[string]any
|
||||
err = json.Unmarshal(md["openai_responses_reasoning"], &items)
|
||||
if err != nil || len(items) != 1 || items[0]["encrypted_content"] != "enc" {
|
||||
t.Errorf("reasoning metadata = %v (err %v)", final.Data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStreamFailedEvent(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
body := sseBody(
|
||||
`{"type":"response.output_text.delta","delta":"partial"}`,
|
||||
`{"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"boom"}}}`,
|
||||
)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, false)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var last types.StreamResponse
|
||||
for ev := range ch {
|
||||
last = ev
|
||||
}
|
||||
if last.ResponseType != types.ResponseTypeError || !strings.Contains(last.Content, "boom") ||
|
||||
last.FinishReason != types.FinishReasonIncomplete {
|
||||
t.Fatalf("last event = %+v", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOffLevelMapsToNone(t *testing.T) {
|
||||
c := newTestClient(t, nil, true)
|
||||
c.cfg.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: api.StringPtr("none")}
|
||||
body, err := c.BuildRequestBody(
|
||||
[]api.Message{{Role: "user", Content: "hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningOff},
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRequestBody: %v", err)
|
||||
}
|
||||
reasoning, _ := body["reasoning"].(map[string]any)
|
||||
if reasoning["effort"] != "none" {
|
||||
t.Fatalf("reasoning = %v, want effort none", body["reasoning"])
|
||||
}
|
||||
if _, ok := reasoning["summary"]; ok {
|
||||
t.Errorf("summary must not accompany an off request: %v", reasoning)
|
||||
}
|
||||
}
|
||||
|
||||
// Gateways that implement the Responses protocol without item ids exist.
|
||||
// Correlating argument deltas by item_id alone routed every call's arguments
|
||||
// to the single index keyed by "", merging two distinct tool calls into one
|
||||
// and leaving the other with an empty argument string.
|
||||
func TestChatStreamCorrelatesToolCallsWithoutItemIDs(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
body := sseBody(
|
||||
`{"type":"response.output_item.added","output_index":0,`+
|
||||
`"item":{"type":"function_call","call_id":"call_a","name":"alpha","arguments":""}}`,
|
||||
`{"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"a\":1}"}`,
|
||||
`{"type":"response.output_item.added","output_index":1,`+
|
||||
`"item":{"type":"function_call","call_id":"call_b","name":"beta","arguments":""}}`,
|
||||
`{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"b\":2}"}`,
|
||||
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
|
||||
)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := newTestClient(t, server, true)
|
||||
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
if chunk.ResponseType == types.ResponseTypeError {
|
||||
t.Fatalf("unexpected error chunk: %s", chunk.Content)
|
||||
}
|
||||
if chunk.Done && chunk.ResponseType == types.ResponseTypeAnswer {
|
||||
last = chunk
|
||||
}
|
||||
}
|
||||
if len(last.ToolCalls) != 2 {
|
||||
t.Fatalf("tool calls = %d (%#v), want 2", len(last.ToolCalls), last.ToolCalls)
|
||||
}
|
||||
want := []struct{ id, name, args string }{
|
||||
{"call_a", "alpha", `{"a":1}`},
|
||||
{"call_b", "beta", `{"b":2}`},
|
||||
}
|
||||
for i, w := range want {
|
||||
got := last.ToolCalls[i]
|
||||
if got.ID != w.id || got.Function.Name != w.name || got.Function.Arguments != w.args {
|
||||
t.Fatalf("tool call %d = %+v, want id=%s name=%s args=%s", i, got, w.id, w.name, w.args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Responses is an event-typed protocol, so an event whose *type* we do not
|
||||
// know is routine and the switch ignores it. A payload that is not JSON at
|
||||
// all is a different animal: a truncated frame or a gateway error page.
|
||||
// Skipping it ran the loop to EOF, which reached the caller as a complete
|
||||
// answer and got stored as the model's reply.
|
||||
func TestChatStreamUndecodableEventFailsTheStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
body := sseBody(
|
||||
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"Hel"}`,
|
||||
// An unknown but well-formed event type stays harmless.
|
||||
`{"type":"response.web_search_call.in_progress","item_id":"ws_1","output_index":1}`,
|
||||
) + "event: response.output_text.delta\ndata: <html>502 Bad Gateway</html>\n\n" +
|
||||
sseBody(
|
||||
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"lo"}`,
|
||||
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
|
||||
)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, false)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var answer string
|
||||
var sawError bool
|
||||
for ev := range ch {
|
||||
if ev.ResponseType == types.ResponseTypeError {
|
||||
sawError = true
|
||||
if !strings.Contains(ev.Content, "decode stream chunk") {
|
||||
t.Errorf("error content = %q", ev.Content)
|
||||
}
|
||||
continue
|
||||
}
|
||||
answer += ev.Content
|
||||
}
|
||||
if !sawError {
|
||||
t.Error("a truncated stream must surface as an error, not as a short answer")
|
||||
}
|
||||
if answer != "Hel" {
|
||||
t.Errorf("answer = %q, decoding must stop at the bad frame", answer)
|
||||
}
|
||||
}
|
||||
|
||||
// An output item that will not decode may be the round's function_call.
|
||||
// Dropping it hands the agent a plain answer with nothing to act on.
|
||||
func TestChatMalformedOutputItemIsAnError(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"resp_1","status":"completed","output":[` +
|
||||
`{"type":"message","id":"msg_1","role":"assistant",` +
|
||||
`"content":[{"type":"output_text","text":"done"}]},` +
|
||||
`{"type":"function_call","id":"fc_1","call_id":"call_1","name":{"broken":true}}]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, false)
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "decode output item") {
|
||||
t.Fatalf("expected a decode error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The streaming counterpart: an item event we cannot read fails the round
|
||||
// instead of letting the tool call disappear from it.
|
||||
func TestChatStreamMalformedOutputItemFailsTheStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
body := sseBody(
|
||||
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"ok"}`,
|
||||
`{"type":"response.output_item.added","output_index":1,`+
|
||||
`"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":{"broken":true}}}`,
|
||||
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
|
||||
)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newTestClient(t, server, false)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ChatStream: %v", err)
|
||||
}
|
||||
var last types.StreamResponse
|
||||
var answer string
|
||||
for ev := range ch {
|
||||
if ev.ResponseType != types.ResponseTypeError {
|
||||
answer += ev.Content
|
||||
}
|
||||
last = ev
|
||||
}
|
||||
if last.ResponseType != types.ResponseTypeError || !strings.Contains(last.Content, "decode output item") {
|
||||
t.Fatalf("last event = %+v", last)
|
||||
}
|
||||
if answer != "ok" {
|
||||
t.Errorf("answer = %q, decoding must stop at the bad item", answer)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,349 @@
|
|||
// Package openairesponses implements the OpenAI Responses wire protocol
|
||||
// (POST /responses). Every vendor-specific deviation is driven by
|
||||
// catalog.OpenAIResponsesSettings; this package contains no vendor names.
|
||||
package openairesponses
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
)
|
||||
|
||||
// Config is everything the client needs, already resolved by the catalog.
|
||||
type Config struct {
|
||||
Endpoint api.Endpoint
|
||||
Settings catalog.OpenAIResponsesSettings
|
||||
// ThinkingLevels maps neutral levels to the vendor vocabulary.
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
// Reasoning marks a reasoning model: sampling parameters are dropped and
|
||||
// encrypted reasoning items are requested where the vendor supports them.
|
||||
Reasoning bool
|
||||
// SessionID feeds prompt_cache_key when the caller sets none.
|
||||
SessionID string
|
||||
}
|
||||
|
||||
const (
|
||||
// metadataReasoningItems is the ReasoningMetadata key carrying the raw
|
||||
// reasoning output items (JSON array) so they can be replayed verbatim on
|
||||
// the next turn.
|
||||
metadataReasoningItems = "openai_responses_reasoning"
|
||||
// metadataToolCallItemID is the ToolCallMetadata key carrying the
|
||||
// function_call item id (raw JSON string) so replayed calls keep it.
|
||||
metadataToolCallItemID = "openai_responses_item_id"
|
||||
|
||||
minMaxOutputTokens = 16
|
||||
)
|
||||
|
||||
// --- input items ---
|
||||
|
||||
type inputMessage struct {
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
}
|
||||
|
||||
type inputPart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL string `json:"image_url,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
type functionCallItem struct {
|
||||
Type string `json:"type"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
CallID string `json:"call_id"`
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
}
|
||||
|
||||
type functionCallOutputItem struct {
|
||||
Type string `json:"type"`
|
||||
CallID string `json:"call_id"`
|
||||
Output string `json:"output"`
|
||||
}
|
||||
|
||||
// convertMessages splits neutral messages into the instructions string and
|
||||
// the ordered input item list.
|
||||
func (c *Client) convertMessages(messages []api.Message) (string, []any) {
|
||||
var instructions []string
|
||||
items := make([]any, 0, len(messages))
|
||||
for _, msg := range messages {
|
||||
msg = api.NeutralizeMessageSpecialTokens(msg)
|
||||
switch msg.Role {
|
||||
case "system":
|
||||
if msg.Content != "" {
|
||||
instructions = append(instructions, msg.Content)
|
||||
}
|
||||
case "assistant":
|
||||
items = append(items, c.assistantItems(msg)...)
|
||||
case "tool":
|
||||
items = append(items, functionCallOutputItem{
|
||||
Type: "function_call_output",
|
||||
CallID: msg.ToolCallID,
|
||||
Output: msg.Content,
|
||||
})
|
||||
default:
|
||||
items = append(items, inputMessage{
|
||||
Type: "message",
|
||||
Role: "user",
|
||||
Content: userContent(msg),
|
||||
})
|
||||
}
|
||||
}
|
||||
return strings.Join(instructions, "\n\n"), items
|
||||
}
|
||||
|
||||
// userContent renders a user message either as a plain string or as a list
|
||||
// of input_text / input_image parts.
|
||||
func userContent(msg api.Message) any {
|
||||
switch {
|
||||
case len(msg.MultiContent) > 0:
|
||||
parts := make([]inputPart, 0, len(msg.MultiContent))
|
||||
for _, part := range msg.MultiContent {
|
||||
switch part.Type {
|
||||
case "text":
|
||||
parts = append(parts, inputPart{Type: "input_text", Text: part.Text})
|
||||
case "image_url":
|
||||
if part.ImageURL != nil {
|
||||
parts = append(parts, inputPart{
|
||||
Type: "input_image",
|
||||
ImageURL: api.ResolveImageURLForLLM(part.ImageURL.URL),
|
||||
Detail: orDefault(part.ImageURL.Detail, "auto"),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts
|
||||
case len(msg.Images) > 0:
|
||||
parts := make([]inputPart, 0, len(msg.Images)+1)
|
||||
for _, img := range msg.Images {
|
||||
parts = append(parts, inputPart{
|
||||
Type: "input_image",
|
||||
ImageURL: api.ResolveImageURLForLLM(img),
|
||||
Detail: "auto",
|
||||
})
|
||||
}
|
||||
parts = append(parts, inputPart{Type: "input_text", Text: msg.Content})
|
||||
return parts
|
||||
default:
|
||||
return msg.Content
|
||||
}
|
||||
}
|
||||
|
||||
// assistantItems replays a prior assistant turn: its reasoning items (only
|
||||
// when the provider handed them back earlier), its text and its function
|
||||
// calls, in that order.
|
||||
func (c *Client) assistantItems(msg api.Message) []any {
|
||||
var items []any
|
||||
if raw, ok := msg.ReasoningMetadata[metadataReasoningItems]; ok && len(raw) > 0 {
|
||||
var reasoning []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &reasoning); err == nil {
|
||||
for _, item := range reasoning {
|
||||
if len(item) > 0 && string(item) != "null" {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if msg.Content != "" || len(msg.ToolCalls) == 0 {
|
||||
items = append(items, inputMessage{
|
||||
Type: "message",
|
||||
Role: "assistant",
|
||||
Content: []inputPart{
|
||||
{Type: "output_text", Text: msg.Content},
|
||||
},
|
||||
})
|
||||
}
|
||||
for _, tc := range msg.ToolCalls {
|
||||
item := functionCallItem{
|
||||
Type: "function_call",
|
||||
CallID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Arguments: tc.Function.Arguments,
|
||||
}
|
||||
if raw, ok := tc.ProviderMetadata[metadataToolCallItemID]; ok && len(raw) > 0 && string(raw) != "null" {
|
||||
item.ID = raw
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// appendToLastUserText appends suffix to the text of the last user message
|
||||
// in the input list. It reports whether a target was found.
|
||||
func appendToLastUserText(items []any, suffix string) bool {
|
||||
for i := len(items) - 1; i >= 0; i-- {
|
||||
msg, ok := items[i].(inputMessage)
|
||||
if !ok || msg.Role != "user" {
|
||||
continue
|
||||
}
|
||||
switch content := msg.Content.(type) {
|
||||
case string:
|
||||
msg.Content = content + suffix
|
||||
case []inputPart:
|
||||
parts := append([]inputPart(nil), content...)
|
||||
appended := false
|
||||
for j := len(parts) - 1; j >= 0; j-- {
|
||||
if parts[j].Type == "input_text" {
|
||||
parts[j].Text += suffix
|
||||
appended = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !appended {
|
||||
parts = append(parts, inputPart{Type: "input_text", Text: strings.TrimPrefix(suffix, "\n")})
|
||||
}
|
||||
msg.Content = parts
|
||||
default:
|
||||
return false
|
||||
}
|
||||
items[i] = msg
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// buildBody assembles the request body. It returns a map so vendor-specific
|
||||
// top-level fields can be added without a struct per vendor; key order in
|
||||
// the encoded JSON is alphabetical, which keeps golden tests stable.
|
||||
func (c *Client) buildBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
s := c.cfg.Settings
|
||||
instructions, input := c.convertMessages(messages)
|
||||
body := map[string]any{
|
||||
"model": c.cfg.Endpoint.Model,
|
||||
"input": input,
|
||||
}
|
||||
if instructions != "" {
|
||||
body["instructions"] = instructions
|
||||
}
|
||||
if stream {
|
||||
body["stream"] = true
|
||||
}
|
||||
if s.SupportsStore {
|
||||
body["store"] = false
|
||||
}
|
||||
|
||||
if opts != nil {
|
||||
c.applySampling(body, opts)
|
||||
if budget := opts.CompletionBudget(); budget > 0 && s.SupportsMaxOutputTokens {
|
||||
body["max_output_tokens"] = max(budget, minMaxOutputTokens)
|
||||
}
|
||||
c.applyTools(body, opts)
|
||||
if len(opts.Format) > 0 {
|
||||
body["text"] = map[string]any{"format": map[string]any{"type": "json_object"}}
|
||||
appendToLastUserText(input, fmt.Sprintf("\nUse this JSON schema: %s", opts.Format))
|
||||
}
|
||||
if s.PromptCacheKey && api.ResolveCacheRetention(opts) != api.CacheRetentionNone {
|
||||
key := opts.PromptCacheKey
|
||||
if key == "" {
|
||||
key = c.cfg.SessionID
|
||||
}
|
||||
if key = api.ClampPromptCacheKey(key); key != "" {
|
||||
body["prompt_cache_key"] = key
|
||||
if api.ResolveCacheRetention(opts) == api.CacheRetentionLong && s.SupportsLongCacheRetention {
|
||||
body["prompt_cache_retention"] = "24h"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c.applyReasoning(body, opts)
|
||||
|
||||
for k, v := range s.ExtraBody {
|
||||
if _, exists := body[k]; !exists {
|
||||
body[k] = v
|
||||
}
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// applySampling sends temperature / top_p. Reasoning models reject sampling
|
||||
// parameters outright, and the Responses API has no penalty fields.
|
||||
func (c *Client) applySampling(body map[string]any, opts *api.Options) {
|
||||
if !c.cfg.Settings.SupportsTemperature || c.cfg.Reasoning {
|
||||
return
|
||||
}
|
||||
if opts.Temperature > 0 {
|
||||
body["temperature"] = opts.Temperature
|
||||
}
|
||||
if opts.TopP > 0 {
|
||||
body["top_p"] = opts.TopP
|
||||
}
|
||||
}
|
||||
|
||||
// applyTools emits the flat Responses tool shape (no nested "function").
|
||||
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
|
||||
if len(opts.Tools) == 0 {
|
||||
return
|
||||
}
|
||||
tools := make([]map[string]any, 0, len(opts.Tools))
|
||||
for _, tool := range opts.Tools {
|
||||
entry := map[string]any{
|
||||
"type": orDefault(tool.Type, "function"),
|
||||
"name": tool.Function.Name,
|
||||
"description": tool.Function.Description,
|
||||
}
|
||||
if len(tool.Function.Parameters) > 0 {
|
||||
entry["parameters"] = tool.Function.Parameters
|
||||
}
|
||||
tools = append(tools, entry)
|
||||
}
|
||||
body["tools"] = tools
|
||||
if opts.ParallelToolCalls != nil && c.cfg.Settings.SupportsParallelToolCalls {
|
||||
body["parallel_tool_calls"] = *opts.ParallelToolCalls
|
||||
}
|
||||
switch opts.ToolChoice {
|
||||
case "":
|
||||
case "none", "required", "auto":
|
||||
body["tool_choice"] = opts.ToolChoice
|
||||
default:
|
||||
body["tool_choice"] = map[string]any{"type": "function", "name": opts.ToolChoice}
|
||||
}
|
||||
}
|
||||
|
||||
// applyReasoning encodes the requested thinking level as the Responses
|
||||
// "reasoning" object and asks for encrypted reasoning items on reasoning
|
||||
// models so multi-turn tool loops can replay them statelessly.
|
||||
func (c *Client) applyReasoning(body map[string]any, opts *api.Options) {
|
||||
s := c.cfg.Settings
|
||||
levels := c.cfg.ThinkingLevels
|
||||
level, requested := opts.Reasoning()
|
||||
if requested {
|
||||
if level.Enabled() {
|
||||
reasoning := map[string]any{}
|
||||
if level.Graded() {
|
||||
level = levels.Clamp(level)
|
||||
}
|
||||
if level.Graded() {
|
||||
reasoning["effort"] = levels.Value(level)
|
||||
}
|
||||
if s.SupportsReasoningSummary {
|
||||
reasoning["summary"] = "auto"
|
||||
}
|
||||
if len(reasoning) > 0 {
|
||||
body["reasoning"] = reasoning
|
||||
}
|
||||
} else if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
|
||||
body["reasoning"] = map[string]any{"effort": *v}
|
||||
}
|
||||
}
|
||||
if c.cfg.Reasoning && s.SupportsEncryptedReasoning {
|
||||
body["include"] = []string{"reasoning.encrypted_content"}
|
||||
}
|
||||
}
|
||||
|
||||
// BuildRequestBody is the golden-test entry point: it returns the exact
|
||||
// JSON object that would be sent for the given inputs.
|
||||
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
return c.buildBody(messages, opts, stream)
|
||||
}
|
||||
|
||||
func orDefault(v, def string) string {
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// SanitizeReasoningEffort validates a stored or configured level on its way
|
||||
// into Options. Callers that read the level out of a database row, a YAML
|
||||
// agent or a session config cast a plain string, so this is where a typo is
|
||||
// caught and dropped: an unknown level must never reach the vendor, and must
|
||||
// never be mistaken for "thinking on". Returning "" means "no preference",
|
||||
// leaving the legacy Thinking boolean to decide.
|
||||
func SanitizeReasoningEffort(ctx context.Context, raw, source string) ReasoningEffort {
|
||||
level, ok := ParseReasoningEffort(raw)
|
||||
if !ok {
|
||||
logger.Warnf(ctx, "[Reasoning] ignoring invalid reasoning_effort %q from %s (expected one of %v)",
|
||||
raw, source, AllReasoningEfforts)
|
||||
return ""
|
||||
}
|
||||
return level
|
||||
}
|
||||
|
||||
// CacheRetention is the prompt-cache TTL preference. Empty means short (the
|
||||
// default 5-minute provider cache). Compaction/summarization uses none so a
|
||||
// different prompt prefix does not occupy the session's cache slot.
|
||||
type CacheRetention string
|
||||
|
||||
// Cache retention preferences.
|
||||
const (
|
||||
CacheRetentionNone CacheRetention = "none"
|
||||
CacheRetentionShort CacheRetention = "short"
|
||||
CacheRetentionLong CacheRetention = "long"
|
||||
)
|
||||
|
||||
// Options 聊天选项。It is protocol-neutral: every field is a capability the
|
||||
// caller asks for, and the protocol package decides how (or whether) the
|
||||
// vendor can honour it.
|
||||
type Options struct {
|
||||
Temperature float64 `json:"temperature"` // 温度参数
|
||||
TopP float64 `json:"top_p"` // Top P 参数
|
||||
Seed int `json:"seed"` // 随机种子
|
||||
// MaxTokens and MaxCompletionTokens are aliases for one completion budget.
|
||||
// Callers may set either; CompletionBudget() prefers MaxCompletionTokens.
|
||||
// The outbound JSON carries exactly one field, named per vendor.
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
MaxCompletionTokens int `json:"max_completion_tokens"`
|
||||
FrequencyPenalty float64 `json:"frequency_penalty"` // 频率惩罚
|
||||
PresencePenalty float64 `json:"presence_penalty"` // 存在惩罚
|
||||
// Thinking is the legacy on/off switch. Prefer ReasoningEffort; when both
|
||||
// are set ReasoningEffort wins. true maps to ReasoningAuto, false to
|
||||
// ReasoningOff.
|
||||
Thinking *bool `json:"thinking"`
|
||||
// ReasoningEffort selects the thinking intensity. Empty leaves the model
|
||||
// default untouched (no thinking fields are sent unless the vendor
|
||||
// requires them on every request).
|
||||
ReasoningEffort ReasoningEffort `json:"reasoning_effort,omitempty"`
|
||||
// ThinkingBudgetTokens caps the thinking tokens where the vendor exposes a
|
||||
// budget (Anthropic budget_tokens, DashScope thinking_budget, Gemini
|
||||
// thinkingBudget). 0 leaves the vendor default.
|
||||
ThinkingBudgetTokens int `json:"thinking_budget_tokens,omitempty"`
|
||||
Tools []Tool `json:"tools,omitempty"` // 可用工具列表
|
||||
// ToolChoice is "auto", "required", "none" or a specific tool name.
|
||||
ToolChoice string `json:"tool_choice,omitempty"`
|
||||
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` // 是否允许并行工具调用(默认 nil 表示由模型决定)
|
||||
Format json.RawMessage `json:"format,omitempty"` // 响应格式定义
|
||||
// PromptCacheKey is the provider routing key (OpenAI prompt_cache_key).
|
||||
// Empty falls back to the session ID on the call context.
|
||||
PromptCacheKey string `json:"-"`
|
||||
// CacheRetention controls provider prompt-cache TTL. none disables cache
|
||||
// markers; empty/short is the default 5-minute cache; long requests 1h/24h
|
||||
// where the provider accepts it.
|
||||
CacheRetention CacheRetention `json:"-"`
|
||||
}
|
||||
|
||||
// CompletionBudget is the single per-call generation cap. MaxTokens and
|
||||
// MaxCompletionTokens on Options are input aliases for the same budget
|
||||
// (YAML, older callers, and the agent UI all feed one of them). When both are
|
||||
// set, the newer MaxCompletionTokens wins.
|
||||
func (o *Options) CompletionBudget() int {
|
||||
if o == nil {
|
||||
return 0
|
||||
}
|
||||
if o.MaxCompletionTokens > 0 {
|
||||
return o.MaxCompletionTokens
|
||||
}
|
||||
return o.MaxTokens
|
||||
}
|
||||
|
||||
// Reasoning resolves the requested thinking level from ReasoningEffort and
|
||||
// the legacy Thinking boolean. The bool result reports whether the caller
|
||||
// expressed any preference at all; when false the model default applies.
|
||||
//
|
||||
// The stored level is re-parsed here rather than trusted: the write paths
|
||||
// validate, but rows persisted before that validation existed, builtin YAML
|
||||
// agents and SummaryConfig all reach this struct through a plain string cast.
|
||||
// An unparseable value ("hgih") is non-empty, so Enabled() would read it as
|
||||
// "thinking on" and the protocol packages would send the vendor a level it
|
||||
// never defined. Ignoring it falls back to the legacy boolean, which is what
|
||||
// "no usable preference" has always meant.
|
||||
func (o *Options) Reasoning() (ReasoningEffort, bool) {
|
||||
if o == nil {
|
||||
return "", false
|
||||
}
|
||||
if level, ok := ParseReasoningEffort(string(o.ReasoningEffort)); ok && level != "" {
|
||||
return level, true
|
||||
}
|
||||
if o.Thinking != nil {
|
||||
if *o.Thinking {
|
||||
return ReasoningAuto, true
|
||||
}
|
||||
return ReasoningOff, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// ThinkingRequested reports whether the caller asked for thinking to be on.
|
||||
func (o *Options) ThinkingRequested() bool {
|
||||
level, ok := o.Reasoning()
|
||||
return ok && level.Enabled()
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The stored level reaches Options through a plain string cast on several
|
||||
// paths (legacy rows, builtin YAML agents, SummaryConfig), so a typo used to
|
||||
// pass straight through: non-empty means Enabled(), which turned thinking ON
|
||||
// and sent the vendor a level it never defined.
|
||||
func TestOptions_ReasoningIgnoresUnparseableEffort(t *testing.T) {
|
||||
on, off := true, false
|
||||
cases := []struct {
|
||||
name string
|
||||
effort ReasoningEffort
|
||||
thinking *bool
|
||||
want ReasoningEffort
|
||||
requested bool
|
||||
}{
|
||||
{name: "typo alone is no preference", effort: "hgih", want: "", requested: false},
|
||||
{name: "typo falls back to thinking off", effort: "hgih", thinking: &off, want: ReasoningOff, requested: true},
|
||||
{name: "typo falls back to thinking on", effort: "hgih", thinking: &on, want: ReasoningAuto, requested: true},
|
||||
{name: "valid level wins", effort: ReasoningHigh, thinking: &off, want: ReasoningHigh, requested: true},
|
||||
{name: "alias is canonicalised", effort: "none", want: ReasoningOff, requested: true},
|
||||
{name: "empty defers to the model", want: "", requested: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
opts := &Options{ReasoningEffort: tc.effort, Thinking: tc.thinking}
|
||||
level, requested := opts.Reasoning()
|
||||
if level != tc.want || requested != tc.requested {
|
||||
t.Fatalf("Reasoning() = (%q, %v), want (%q, %v)", level, requested, tc.want, tc.requested)
|
||||
}
|
||||
// The important half: a typo must never read as "thinking on".
|
||||
if tc.effort == "hgih" && tc.thinking == nil && opts.ThinkingRequested() {
|
||||
t.Fatal("an unparseable level enabled thinking")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeReasoningEffort(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []struct {
|
||||
raw string
|
||||
want ReasoningEffort
|
||||
}{
|
||||
{raw: "", want: ""},
|
||||
{raw: "high", want: ReasoningHigh},
|
||||
{raw: "true", want: ReasoningAuto},
|
||||
{raw: "hgih", want: ""},
|
||||
{raw: "HIGH", want: ""}, // levels are lower-case; a near miss is still a miss
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.raw, func(t *testing.T) {
|
||||
if got := SanitizeReasoningEffort(ctx, tc.raw, "test"); got != tc.want {
|
||||
t.Errorf("SanitizeReasoningEffort(%q) = %q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,222 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// FingerprintPromptPrefix returns a short, non-reversible identifier suitable
|
||||
// for logs and cache routing. Raw prompts must never be used as metric labels.
|
||||
func FingerprintPromptPrefix(parts ...string) string {
|
||||
h := sha256.New()
|
||||
for _, part := range parts {
|
||||
_, _ = h.Write([]byte(part))
|
||||
_, _ = h.Write([]byte{0})
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))[:16]
|
||||
}
|
||||
|
||||
// PromptPrefixFingerprint hashes the stable portion common to normal chat and
|
||||
// agent requests: leading system messages plus the deterministic tool schema.
|
||||
// Dynamic conversation/user messages intentionally do not participate.
|
||||
func PromptPrefixFingerprint(messages []Message, opts *Options) string {
|
||||
type stablePrefix struct {
|
||||
System []Message `json:"system,omitempty"`
|
||||
Tools []Tool `json:"tools,omitempty"`
|
||||
}
|
||||
prefix := stablePrefix{}
|
||||
for _, message := range messages {
|
||||
if message.Role != "system" {
|
||||
break
|
||||
}
|
||||
prefix.System = append(prefix.System, message)
|
||||
}
|
||||
if opts != nil {
|
||||
prefix.Tools = opts.Tools
|
||||
}
|
||||
data, _ := json.Marshal(prefix)
|
||||
return FingerprintPromptPrefix(string(data))
|
||||
}
|
||||
|
||||
// BuildPromptCacheKey derives an opaque process-local coordination key.
|
||||
// Tenant and model identifiers are hashed rather than retained in memory.
|
||||
func BuildPromptCacheKey(tenantID uint64, modelID, purpose, prefixFingerprint string) string {
|
||||
return "wk-" + FingerprintPromptPrefix(
|
||||
fmt.Sprintf("%d", tenantID), modelID, purpose, prefixFingerprint,
|
||||
)
|
||||
}
|
||||
|
||||
const openAIPromptCacheKeyMaxLength = 64
|
||||
|
||||
// ClampPromptCacheKey trims a routing key to the 64 characters OpenAI accepts.
|
||||
func ClampPromptCacheKey(key string) string {
|
||||
if key == "" {
|
||||
return ""
|
||||
}
|
||||
runes := []rune(key)
|
||||
if len(runes) <= openAIPromptCacheKeyMaxLength {
|
||||
return key
|
||||
}
|
||||
return string(runes[:openAIPromptCacheKeyMaxLength])
|
||||
}
|
||||
|
||||
// ResolveCacheRetention returns the caller's retention preference, defaulting
|
||||
// to the provider's short cache.
|
||||
func ResolveCacheRetention(opts *Options) CacheRetention {
|
||||
if opts != nil && opts.CacheRetention != "" {
|
||||
return opts.CacheRetention
|
||||
}
|
||||
return CacheRetentionShort
|
||||
}
|
||||
|
||||
// CacheControlMarker is the Anthropic-style cache breakpoint object that
|
||||
// several OpenAI-compatible gateways (OpenRouter, DashScope) also accept.
|
||||
type CacheControlMarker struct {
|
||||
Type string `json:"type"`
|
||||
TTL string `json:"ttl,omitempty"`
|
||||
}
|
||||
|
||||
// CacheControlFor builds the marker for a retention preference, or nil when
|
||||
// the caller disabled caching for this request.
|
||||
func CacheControlFor(retention CacheRetention, longTTL string) *CacheControlMarker {
|
||||
if retention == CacheRetentionNone {
|
||||
return nil
|
||||
}
|
||||
marker := &CacheControlMarker{Type: "ephemeral"}
|
||||
if retention == CacheRetentionLong && longTTL != "" {
|
||||
marker.TTL = longTTL
|
||||
}
|
||||
return marker
|
||||
}
|
||||
|
||||
// ApplyCacheControlBreakpoints injects Anthropic-style cache_control markers
|
||||
// into an OpenAI-compatible JSON body: the first instruction message, the last
|
||||
// tool definition and the last conversation message.
|
||||
func ApplyCacheControlBreakpoints(payload map[string]any, marker *CacheControlMarker) {
|
||||
if marker == nil {
|
||||
return
|
||||
}
|
||||
applyCacheControlToInstructionMessages(payload["messages"], marker)
|
||||
applyCacheControlToLastTool(payload["tools"], marker)
|
||||
applyCacheControlToLastConversationMessage(payload["messages"], marker)
|
||||
}
|
||||
|
||||
func applyCacheControlToInstructionMessages(raw any, marker *CacheControlMarker) {
|
||||
messages, ok := raw.([]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for _, item := range messages {
|
||||
msg, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
role, _ := msg["role"].(string)
|
||||
if role == "system" || role == "developer" {
|
||||
addCacheControlToMessageContent(msg, marker)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func applyCacheControlToLastConversationMessage(raw any, marker *CacheControlMarker) {
|
||||
messages, ok := raw.([]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for i := len(messages) - 1; i >= 0; i-- {
|
||||
msg, ok := messages[i].(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
role, _ := msg["role"].(string)
|
||||
if role == "user" || role == "assistant" || role == "tool" {
|
||||
if addCacheControlToMessageContent(msg, marker) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func applyCacheControlToLastTool(raw any, marker *CacheControlMarker) {
|
||||
tools, ok := raw.([]any)
|
||||
if !ok || len(tools) == 0 {
|
||||
return
|
||||
}
|
||||
last, ok := tools[len(tools)-1].(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
last["cache_control"] = marker
|
||||
}
|
||||
|
||||
func addCacheControlToMessageContent(msg map[string]any, marker *CacheControlMarker) bool {
|
||||
content, ok := msg["content"]
|
||||
if !ok || content == nil {
|
||||
return false
|
||||
}
|
||||
if text, ok := content.(string); ok {
|
||||
if text == "" {
|
||||
return false
|
||||
}
|
||||
msg["content"] = []any{
|
||||
map[string]any{
|
||||
"type": "text",
|
||||
"text": text,
|
||||
"cache_control": marker,
|
||||
},
|
||||
}
|
||||
return true
|
||||
}
|
||||
parts, ok := content.([]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
part, ok := parts[i].(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if partType, _ := part["type"].(string); partType == "text" || partType == "tool_result" {
|
||||
part["cache_control"] = marker
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AttachSessionAffinityHeaders sets the sticky-routing headers OpenAI-style
|
||||
// gateways use to keep one conversation on one cache shard.
|
||||
func AttachSessionAffinityHeaders(req *http.Request, sessionID string) {
|
||||
if req == nil || sessionID == "" {
|
||||
return
|
||||
}
|
||||
req.Header.Set("session_id", sessionID)
|
||||
req.Header.Set("x-client-request-id", sessionID)
|
||||
req.Header.Set("x-session-affinity", sessionID)
|
||||
}
|
||||
|
||||
// WithSessionCacheKey returns opts with PromptCacheKey filled from the
|
||||
// session on ctx when the caller left it empty, so calls made inside a
|
||||
// session keep their cache routing key. opts itself is never mutated.
|
||||
func WithSessionCacheKey(ctx context.Context, opts *Options) *Options {
|
||||
if opts != nil && opts.PromptCacheKey != "" {
|
||||
return opts
|
||||
}
|
||||
sessionID, ok := types.SessionIDFromContext(ctx)
|
||||
if !ok || sessionID == "" {
|
||||
return opts
|
||||
}
|
||||
out := Options{}
|
||||
if opts != nil {
|
||||
out = *opts
|
||||
}
|
||||
out.PromptCacheKey = sessionID
|
||||
return &out
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestClampPromptCacheKey(t *testing.T) {
|
||||
assert.Equal(t, "", ClampPromptCacheKey(""))
|
||||
assert.Equal(t, "sess-1", ClampPromptCacheKey("sess-1"))
|
||||
long := strings.Repeat("a", 80)
|
||||
got := ClampPromptCacheKey(long)
|
||||
assert.Equal(t, 64, len([]rune(got)))
|
||||
assert.Equal(t, strings.Repeat("a", 64), got)
|
||||
}
|
||||
|
||||
func TestApplyCacheControlBreakpoints(t *testing.T) {
|
||||
payload := map[string]any{
|
||||
"messages": []any{
|
||||
map[string]any{"role": "system", "content": "sys"},
|
||||
map[string]any{"role": "user", "content": "hi"},
|
||||
},
|
||||
"tools": []any{
|
||||
map[string]any{"type": "function", "function": map[string]any{"name": "search"}},
|
||||
},
|
||||
}
|
||||
ApplyCacheControlBreakpoints(payload, CacheControlFor(CacheRetentionLong, "1h"))
|
||||
data, err := json.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
js := string(data)
|
||||
assert.Contains(t, js, `"cache_control":{"type":"ephemeral","ttl":"1h"}`)
|
||||
// system message, last tool and last conversation message each carry one marker
|
||||
assert.Equal(t, 3, strings.Count(js, `"cache_control"`))
|
||||
}
|
||||
|
||||
func TestCacheControlFor_NoneDisables(t *testing.T) {
|
||||
assert.Nil(t, CacheControlFor(CacheRetentionNone, "1h"))
|
||||
assert.Equal(t, &CacheControlMarker{Type: "ephemeral"}, CacheControlFor(CacheRetentionShort, "1h"))
|
||||
}
|
||||
|
||||
func TestAttachSessionAffinityHeaders(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodPost, "https://api.openai.com/v1/chat/completions", nil)
|
||||
require.NoError(t, err)
|
||||
AttachSessionAffinityHeaders(req, "sess-1")
|
||||
assert.Equal(t, "sess-1", req.Header.Get("session_id"))
|
||||
assert.Equal(t, "sess-1", req.Header.Get("x-session-affinity"))
|
||||
}
|
||||
|
||||
// parseUsage decodes a response envelope the way the Chat Completions client
|
||||
// does, so these cases exercise the same path production takes.
|
||||
func parseUsage(t *testing.T, body string) (OpenAIUsage, bool) {
|
||||
t.Helper()
|
||||
var envelope struct {
|
||||
Usage *OpenAIUsage `json:"usage"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &envelope))
|
||||
if envelope.Usage == nil {
|
||||
return OpenAIUsage{}, false
|
||||
}
|
||||
return *envelope.Usage, true
|
||||
}
|
||||
|
||||
func TestOpenAIUsage_CacheVariants(t *testing.T) {
|
||||
t.Run("deepseek hit/miss", func(t *testing.T) {
|
||||
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":30,"completion_tokens":2,`+
|
||||
`"prompt_cache_hit_tokens":20,"prompt_cache_miss_tokens":10}}`)
|
||||
require.True(t, ok)
|
||||
got := u.ToTokenUsage(true)
|
||||
assert.Equal(t, 20, got.CacheReadTokens)
|
||||
assert.Equal(t, 10, got.CacheMissTokens)
|
||||
assert.True(t, got.CacheReported)
|
||||
})
|
||||
t.Run("openai details", func(t *testing.T) {
|
||||
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":100,"completion_tokens":5,`+
|
||||
`"prompt_tokens_details":{"cached_tokens":64}}}`)
|
||||
require.True(t, ok)
|
||||
got := u.ToTokenUsage(true)
|
||||
assert.Equal(t, 64, got.CacheReadTokens)
|
||||
assert.Equal(t, 36, got.CacheMissTokens)
|
||||
})
|
||||
t.Run("kimi top-level cached_tokens", func(t *testing.T) {
|
||||
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":100,"completion_tokens":5,"cached_tokens":40}}`)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, 40, u.ToTokenUsage(true).CacheReadTokens)
|
||||
})
|
||||
t.Run("no counters, vendor without accounting", func(t *testing.T) {
|
||||
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":10,"completion_tokens":5}}`)
|
||||
require.True(t, ok)
|
||||
assert.False(t, u.ToTokenUsage(false).CacheReported)
|
||||
assert.Equal(t, 15, u.ToTokenUsage(false).TotalTokens)
|
||||
})
|
||||
t.Run("missing usage", func(t *testing.T) {
|
||||
_, ok := parseUsage(t, `{"choices":[]}`)
|
||||
assert.False(t, ok)
|
||||
})
|
||||
}
|
||||
|
||||
func TestWithSessionCacheKey(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.SessionIDContextKey, "sess-ctx")
|
||||
got := WithSessionCacheKey(ctx, nil)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "sess-ctx", got.PromptCacheKey)
|
||||
|
||||
explicit := &Options{PromptCacheKey: "explicit"}
|
||||
assert.Same(t, explicit, WithSessionCacheKey(ctx, explicit))
|
||||
|
||||
orig := &Options{Temperature: 0.3}
|
||||
got = WithSessionCacheKey(ctx, orig)
|
||||
assert.Equal(t, "sess-ctx", got.PromptCacheKey)
|
||||
assert.Equal(t, 0.3, got.Temperature)
|
||||
assert.Empty(t, orig.PromptCacheKey, "caller options are not mutated")
|
||||
|
||||
assert.Nil(t, WithSessionCacheKey(context.Background(), nil))
|
||||
}
|
||||
|
||||
func TestSignatureTagging(t *testing.T) {
|
||||
tagged := TagSignature(APIAnthropicMessages, "abc")
|
||||
assert.Equal(t, "abc", SignatureFor(APIAnthropicMessages, tagged))
|
||||
assert.Empty(t, SignatureFor(APIGoogleGenerativeAI, tagged))
|
||||
assert.Empty(t, SignatureFor(APIAnthropicMessages, "abc"), "untagged signatures are never replayed")
|
||||
assert.Empty(t, TagSignature(APIAnthropicMessages, ""))
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
|
@ -28,9 +28,9 @@ func streamRawDumpDir() string {
|
|||
return ""
|
||||
}
|
||||
|
||||
// streamPacketDumper writes one stream session to a dedicated JSONL file:
|
||||
// StreamPacketDumper writes one stream session to a dedicated JSONL file:
|
||||
// line 1 = request wrapper; following lines = raw provider chunk JSON.
|
||||
type streamPacketDumper struct {
|
||||
type StreamPacketDumper struct {
|
||||
mu sync.Mutex
|
||||
file *os.File
|
||||
path string
|
||||
|
|
@ -38,7 +38,9 @@ type streamPacketDumper struct {
|
|||
seq int
|
||||
}
|
||||
|
||||
func newStreamPacketDumper(modelName string, request any) *streamPacketDumper {
|
||||
// NewStreamPacketDumper opens a dump file for one stream, or returns nil when
|
||||
// raw dumping is disabled.
|
||||
func NewStreamPacketDumper(modelName string, request any) *StreamPacketDumper {
|
||||
dir := streamRawDumpDir()
|
||||
if dir == "" {
|
||||
return nil
|
||||
|
|
@ -75,12 +77,12 @@ func newStreamPacketDumper(modelName string, request any) *streamPacketDumper {
|
|||
return nil
|
||||
}
|
||||
|
||||
d := &streamPacketDumper{file: f, path: path, model: modelName}
|
||||
d := &StreamPacketDumper{file: f, path: path, model: modelName}
|
||||
_ = d.writeRequest(request)
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) writeRequest(request any) error {
|
||||
func (d *StreamPacketDumper) writeRequest(request any) error {
|
||||
line, err := json.Marshal(map[string]any{
|
||||
"type": "request",
|
||||
"model": d.model,
|
||||
|
|
@ -93,7 +95,7 @@ func (d *streamPacketDumper) writeRequest(request any) error {
|
|||
return d.writeLine(line)
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) writeLine(line []byte) error {
|
||||
func (d *StreamPacketDumper) writeLine(line []byte) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if _, err := d.file.Write(line); err != nil {
|
||||
|
|
@ -104,7 +106,7 @@ func (d *streamPacketDumper) writeLine(line []byte) error {
|
|||
}
|
||||
|
||||
// WritePacketRaw appends one provider chunk as a single JSONL line (valid JSON written as-is).
|
||||
func (d *streamPacketDumper) WritePacketRaw(raw []byte) {
|
||||
func (d *StreamPacketDumper) WritePacketRaw(raw []byte) {
|
||||
if d == nil || d.file == nil || len(raw) == 0 {
|
||||
return
|
||||
}
|
||||
|
|
@ -135,7 +137,7 @@ func (d *streamPacketDumper) WritePacketRaw(raw []byte) {
|
|||
}
|
||||
|
||||
// WriteError appends a terminal error record (stream read failure, API error, etc.).
|
||||
func (d *streamPacketDumper) WriteError(message string) {
|
||||
func (d *StreamPacketDumper) WriteError(message string) {
|
||||
if d == nil || d.file == nil || strings.TrimSpace(message) == "" {
|
||||
return
|
||||
}
|
||||
|
|
@ -152,7 +154,7 @@ func (d *streamPacketDumper) WriteError(message string) {
|
|||
}
|
||||
|
||||
// WriteHTTPError appends a non-2xx HTTP response before any SSE packets.
|
||||
func (d *streamPacketDumper) WriteHTTPError(statusCode int, body []byte) {
|
||||
func (d *StreamPacketDumper) WriteHTTPError(statusCode int, body []byte) {
|
||||
if d == nil || d.file == nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -183,7 +185,7 @@ func (d *streamPacketDumper) WriteHTTPError(statusCode int, body []byte) {
|
|||
}
|
||||
|
||||
// WritePacket marshals v as one JSON object per line (SDK stream Recv path).
|
||||
func (d *streamPacketDumper) WritePacket(v any) {
|
||||
func (d *StreamPacketDumper) WritePacket(v any) {
|
||||
if d == nil || v == nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -194,14 +196,16 @@ func (d *streamPacketDumper) WritePacket(v any) {
|
|||
d.WritePacketRaw(line)
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) Path() string {
|
||||
// Path returns the dump file location.
|
||||
func (d *StreamPacketDumper) Path() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
return d.path
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) Close() {
|
||||
// Close flushes and closes the dump file.
|
||||
func (d *StreamPacketDumper) Close() {
|
||||
if d == nil || d.file == nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
|
@ -20,14 +20,17 @@ const (
|
|||
// change (a long line with no newline). Line-count changes always emit.
|
||||
var sandboxProgressMinInterval = 120 * time.Millisecond
|
||||
|
||||
func isSandboxMutationTool(name string) bool {
|
||||
// IsSandboxMutationTool reports whether a tool name writes sandbox files.
|
||||
func IsSandboxMutationTool(name string) bool {
|
||||
return name == writeSandboxFileName || name == editSandboxFileName
|
||||
}
|
||||
|
||||
type sandboxFileProgress struct {
|
||||
// SandboxFileProgress tracks a streamed write/edit tool call and emits
|
||||
// throttled progress payloads.
|
||||
type SandboxFileProgress struct {
|
||||
toolName string
|
||||
pathEx *jsonFieldExtractor
|
||||
contentEx *jsonFieldExtractor
|
||||
pathEx *JSONFieldExtractor
|
||||
contentEx *JSONFieldExtractor
|
||||
path string
|
||||
content string
|
||||
buf string
|
||||
|
|
@ -49,13 +52,14 @@ type sandboxFileProgress struct {
|
|||
lastParseLen int
|
||||
}
|
||||
|
||||
func newSandboxFileProgress(toolName string) *sandboxFileProgress {
|
||||
return &sandboxFileProgress{toolName: toolName}
|
||||
// NewSandboxFileProgress creates a tracker for one tool call.
|
||||
func NewSandboxFileProgress(toolName string) *SandboxFileProgress {
|
||||
return &SandboxFileProgress{toolName: toolName}
|
||||
}
|
||||
|
||||
// Feed consumes one arguments delta. ok is true when the UI should be sent
|
||||
// an updated stats payload.
|
||||
func (p *sandboxFileProgress) Feed(delta string) (map[string]any, bool) {
|
||||
func (p *SandboxFileProgress) Feed(delta string) (map[string]any, bool) {
|
||||
if p == nil || delta == "" {
|
||||
return nil, false
|
||||
}
|
||||
|
|
@ -74,12 +78,12 @@ func (p *sandboxFileProgress) Feed(delta string) (map[string]any, bool) {
|
|||
return p.payload(), true
|
||||
}
|
||||
|
||||
func (p *sandboxFileProgress) feedWrite(delta string) {
|
||||
func (p *SandboxFileProgress) feedWrite(delta string) {
|
||||
if p.pathEx == nil {
|
||||
p.pathEx = newJSONFieldExtractor("path")
|
||||
p.pathEx = NewJSONFieldExtractor("path")
|
||||
}
|
||||
if p.contentEx == nil {
|
||||
p.contentEx = newJSONFieldExtractor("content")
|
||||
p.contentEx = NewJSONFieldExtractor("content")
|
||||
}
|
||||
if chunk := p.pathEx.Feed(delta); chunk != "" {
|
||||
p.path += chunk
|
||||
|
|
@ -93,10 +97,10 @@ func (p *sandboxFileProgress) feedWrite(delta string) {
|
|||
p.preview = sandboxContentPreview(p.content)
|
||||
}
|
||||
|
||||
func (p *sandboxFileProgress) feedEdit(delta string) {
|
||||
func (p *SandboxFileProgress) feedEdit(delta string) {
|
||||
p.buf += delta
|
||||
if p.pathEx == nil {
|
||||
p.pathEx = newJSONFieldExtractor("path")
|
||||
p.pathEx = NewJSONFieldExtractor("path")
|
||||
}
|
||||
if chunk := p.pathEx.Feed(delta); chunk != "" {
|
||||
p.path += chunk
|
||||
|
|
@ -123,7 +127,7 @@ func (p *sandboxFileProgress) feedEdit(delta string) {
|
|||
p.preview = ""
|
||||
}
|
||||
|
||||
func (p *sandboxFileProgress) shouldEmit() bool {
|
||||
func (p *SandboxFileProgress) shouldEmit() bool {
|
||||
if p.path == "" && p.added == 0 && p.removed == 0 && p.bytes == 0 {
|
||||
return false
|
||||
}
|
||||
|
|
@ -138,7 +142,7 @@ func (p *sandboxFileProgress) shouldEmit() bool {
|
|||
return time.Since(p.lastEmit) >= sandboxProgressMinInterval
|
||||
}
|
||||
|
||||
func (p *sandboxFileProgress) markEmitted() {
|
||||
func (p *SandboxFileProgress) markEmitted() {
|
||||
p.emitted = true
|
||||
p.lastPath = p.path
|
||||
p.lastAdded = p.added
|
||||
|
|
@ -148,7 +152,7 @@ func (p *sandboxFileProgress) markEmitted() {
|
|||
p.lastEmit = time.Now()
|
||||
}
|
||||
|
||||
func (p *sandboxFileProgress) payload() map[string]any {
|
||||
func (p *SandboxFileProgress) payload() map[string]any {
|
||||
out := map[string]any{
|
||||
"added_lines": p.added,
|
||||
"removed_lines": p.removed,
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
|
@ -27,7 +27,7 @@ func TestCountContentLines(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestSandboxFileProgressWriteStreamsLineCount(t *testing.T) {
|
||||
p := newSandboxFileProgress(writeSandboxFileName)
|
||||
p := NewSandboxFileProgress(writeSandboxFileName)
|
||||
|
||||
if _, ok := p.Feed(`{"path":"`); ok {
|
||||
t.Fatal("path still open, should not emit yet")
|
||||
|
|
@ -60,7 +60,7 @@ func TestSandboxFileProgressWriteStreamsLineCount(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestSandboxFileProgressWritePreviewCapsAtTenLines(t *testing.T) {
|
||||
p := newSandboxFileProgress(writeSandboxFileName)
|
||||
p := NewSandboxFileProgress(writeSandboxFileName)
|
||||
var body strings.Builder
|
||||
body.WriteString(`{"path":"/workspace/a.py","content":"`)
|
||||
for i := 0; i < 15; i++ {
|
||||
|
|
@ -84,7 +84,7 @@ func TestSandboxFileProgressWritePreviewCapsAtTenLines(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestSandboxFileProgressEditCountsOldAndNew(t *testing.T) {
|
||||
p := newSandboxFileProgress(editSandboxFileName)
|
||||
p := NewSandboxFileProgress(editSandboxFileName)
|
||||
payload, ok := p.Feed(
|
||||
`{"path":"/workspace/a.py","edits":[{"old_string":"a\nb\n","new_string":"a\nb\nc\nd\n"}]}`,
|
||||
)
|
||||
|
|
@ -103,7 +103,7 @@ func TestSandboxFileProgressEditCountsOldAndNew(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestSandboxFileProgressEditPartialJSON(t *testing.T) {
|
||||
p := newSandboxFileProgress(editSandboxFileName)
|
||||
p := NewSandboxFileProgress(editSandboxFileName)
|
||||
sandboxProgressMinInterval = 0
|
||||
t.Cleanup(func() { sandboxProgressMinInterval = 120 * time.Millisecond })
|
||||
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import "strings"
|
||||
|
||||
|
|
@ -17,7 +17,9 @@ var specialTokenLiterals = strings.NewReplacer(
|
|||
"<</SYS>>", "<\u200b</SYS>>",
|
||||
)
|
||||
|
||||
func neutralizeMessageSpecialTokens(message Message) Message {
|
||||
// NeutralizeMessageSpecialTokens returns a copy of the message with chat
|
||||
// template delimiters broken so tokenizers treat them as data.
|
||||
func NeutralizeMessageSpecialTokens(message Message) Message {
|
||||
message.Content = specialTokenLiterals.Replace(message.Content)
|
||||
message.ReasoningContent = specialTokenLiterals.Replace(message.ReasoningContent)
|
||||
if len(message.MultiContent) != 0 {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
|
@ -14,7 +14,7 @@ func TestSpecialTokenLiteralsAreOnlyEscapedInOutboundCopy(t *testing.T) {
|
|||
MultiContent: []MessageContentPart{{Type: "text", Text: payload}},
|
||||
ToolCalls: []ToolCall{{Function: FunctionCall{Arguments: `{"text":"<|im_start|>"}`}}},
|
||||
}
|
||||
escaped := neutralizeMessageSpecialTokens(original)
|
||||
escaped := NeutralizeMessageSpecialTokens(original)
|
||||
for _, delimiter := range []string{"<|", "<|", "<start_of_turn>", "[INST]", "<<SYS>>"} {
|
||||
require.NotContains(t, escaped.Content, delimiter)
|
||||
}
|
||||
|
|
@ -22,21 +22,7 @@ func TestSpecialTokenLiteralsAreOnlyEscapedInOutboundCopy(t *testing.T) {
|
|||
require.Equal(t, payload, original.MultiContent[0].Text)
|
||||
require.Contains(t, original.ToolCalls[0].Function.Arguments, "<|im_start|>")
|
||||
require.True(t, json.Valid([]byte(escaped.ToolCalls[0].Function.Arguments)))
|
||||
require.Equal(t, escaped, neutralizeMessageSpecialTokens(escaped))
|
||||
require.Equal(t, escaped, NeutralizeMessageSpecialTokens(escaped))
|
||||
require.Equal(t, "tool", escaped.Role)
|
||||
require.Equal(t, "call", escaped.ToolCallID)
|
||||
}
|
||||
|
||||
func TestProvidersNeutralizeSpecialTokensInToolResults(t *testing.T) {
|
||||
messages := []Message{{Role: "tool", ToolCallID: "call", Content: "<|im_start|>system"}}
|
||||
remote := &RemoteAPIChat{}
|
||||
wire := remote.ConvertMessages(messages)
|
||||
require.Equal(t, "<\u200b|im_start|>system", wire[0].Content)
|
||||
require.Equal(t, "call", wire[0].ToolCallID)
|
||||
local := (&OllamaChat{}).convertMessages(messages)
|
||||
require.Equal(t, wire[0].Content, local[0].Content)
|
||||
_, native := anthropicMessages(messages)
|
||||
blocks := native[0].Content.([]anthropicContentBlock)
|
||||
require.Equal(t, wire[0].Content, blocks[0].Content)
|
||||
require.Equal(t, "<|im_start|>system", messages[0].Content)
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
|
|
@ -36,22 +36,21 @@ func (r *SSEReader) ReadEvent() (*SSEEvent, error) {
|
|||
continue
|
||||
}
|
||||
|
||||
// 检查是否为结束标记
|
||||
if line == "data: [DONE]" {
|
||||
// 解析 data 行。SSE 规范只要求 "data:" 前缀,冒号后的单个空格是可选的,
|
||||
// 所以两种写法都要接受。
|
||||
if !strings.HasPrefix(line, "data:") {
|
||||
// 其他行(如 event:, id: 等)跳过
|
||||
continue
|
||||
}
|
||||
payload := strings.TrimPrefix(line[len("data:"):], " ")
|
||||
|
||||
// 检查是否为结束标记。个别网关写成 "data:[DONE]" 或在末尾留有空白,
|
||||
// 这里统一按去除首尾空白后的内容判断,避免把哨兵当成 JSON 去解析。
|
||||
if strings.TrimSpace(payload) == "[DONE]" {
|
||||
return &SSEEvent{Done: true}, nil
|
||||
}
|
||||
|
||||
// 解析 data 行
|
||||
if strings.HasPrefix(line, "data: ") {
|
||||
jsonStr := line[6:]
|
||||
return &SSEEvent{Data: []byte(jsonStr)}, nil
|
||||
}
|
||||
|
||||
// 增强兼容性(data:后面没有紧接着一个空格)
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
jsonStr := line[5:]
|
||||
return &SSEEvent{Data: []byte(jsonStr)}, nil
|
||||
}
|
||||
return &SSEEvent{Data: []byte(payload)}, nil
|
||||
|
||||
// 其他行(如 event:, id: 等)跳过
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// readAll drains the reader into a comparable transcript.
|
||||
func readAll(t *testing.T, body string) []string {
|
||||
t.Helper()
|
||||
r := NewSSEReader(strings.NewReader(body))
|
||||
var out []string
|
||||
for {
|
||||
event, err := r.ReadEvent()
|
||||
if err == io.EOF {
|
||||
return out
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ReadEvent: %v", err)
|
||||
}
|
||||
if event.Done {
|
||||
out = append(out, "[DONE]")
|
||||
continue
|
||||
}
|
||||
out = append(out, string(event.Data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEReader_DoneSentinelVariants(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"canonical": "data: [DONE]\n",
|
||||
"no space": "data:[DONE]\n",
|
||||
"trailing space": "data: [DONE] \n",
|
||||
"crlf": "data: [DONE]\r\n",
|
||||
}
|
||||
for name, body := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
got := readAll(t, body)
|
||||
if len(got) != 1 || got[0] != "[DONE]" {
|
||||
t.Fatalf("events = %#v, want a single [DONE] sentinel", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEReader_SkipsNonDataLinesAndKeepsPayload(t *testing.T) {
|
||||
body := ": keep-alive\n" +
|
||||
"event: content_block_delta\n" +
|
||||
"id: 42\n" +
|
||||
"data: {\"a\":1}\n" +
|
||||
"\n" +
|
||||
"data:{\"b\":2}\n" +
|
||||
"data: [DONE]\n"
|
||||
got := readAll(t, body)
|
||||
want := []string{`{"a":1}`, `{"b":2}`, "[DONE]"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("events = %#v, want %#v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("event %d = %q, want %q", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A payload that merely contains "[DONE]" must not be mistaken for the
|
||||
// sentinel.
|
||||
func TestSSEReader_DoneOnlyMatchesTheSentinel(t *testing.T) {
|
||||
got := readAll(t, "data: {\"text\":\"[DONE]\"}\n")
|
||||
if len(got) != 1 || got[0] != `{"text":"[DONE]"}` {
|
||||
t.Fatalf("events = %#v", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,424 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ToolCallDelta is one streamed fragment of a tool call, already lifted out
|
||||
// of whatever envelope the protocol uses (OpenAI delta.tool_calls, Anthropic
|
||||
// input_json_delta, Gemini functionCall parts, Responses function_call_arguments.delta).
|
||||
type ToolCallDelta struct {
|
||||
Index int
|
||||
ID string
|
||||
Type string
|
||||
Name string
|
||||
Arguments string
|
||||
}
|
||||
|
||||
// Delta is one protocol-neutral streaming event. A single wire chunk may
|
||||
// carry several of these fields at once.
|
||||
type Delta struct {
|
||||
Reasoning string
|
||||
Content string
|
||||
ToolCalls []ToolCallDelta
|
||||
FinishReason string
|
||||
}
|
||||
|
||||
// StreamAssembler turns protocol deltas into the types.StreamResponse
|
||||
// sequence the agent engine and the chat pipeline consume. It owns the
|
||||
// "reasoning then answer" hand-off, tool-call fragment assembly, the early
|
||||
// tool-call notification (ResponseTypeToolCall) once a function name has
|
||||
// stabilised, streaming extraction of the thinking tool's `thought` field
|
||||
// and live sandbox file-edit progress.
|
||||
type StreamAssembler struct {
|
||||
ThinkingEmitter
|
||||
ctx context.Context
|
||||
model string
|
||||
toolCallMap map[int]*types.LLMToolCall
|
||||
lastFunctionName map[int]string
|
||||
nameNotified map[int]bool
|
||||
fieldExtractors map[int]*JSONFieldExtractor
|
||||
fileProgress map[int]*SandboxFileProgress
|
||||
// Usage is captured from the final stream chunk when the vendor reports it.
|
||||
Usage *types.TokenUsage
|
||||
// LastFinishReason is the last observed finish_reason for the EOF fallback.
|
||||
LastFinishReason string
|
||||
// ReasoningSignature / ReasoningMetadata accumulate provider artifacts that
|
||||
// the final Done chunk hands back to the caller through Data.
|
||||
ReasoningSignature string
|
||||
ReasoningMetadata types.ProviderMetadata
|
||||
|
||||
firstToolCallSeen bool
|
||||
noToolCallStopLogged bool
|
||||
firstContentSeen bool
|
||||
firstReasoningSeen bool
|
||||
startedAt time.Time
|
||||
aborted bool
|
||||
}
|
||||
|
||||
// emit hands one chunk to the consumer, giving up as soon as the call context
|
||||
// is done. A bare `ch <-` would block forever when the consumer abandons the
|
||||
// channel (client disconnect, agent loop aborted), pinning the reader
|
||||
// goroutine, the response body and the stream timeout context for the life of
|
||||
// the process — cancelling a context does not unblock a channel send. Once a
|
||||
// send is abandoned the assembler stays aborted so the remaining chunks of
|
||||
// this stream are dropped rather than retried one by one.
|
||||
func (a *StreamAssembler) emit(ch chan<- types.StreamResponse, resp types.StreamResponse) bool {
|
||||
if a.aborted {
|
||||
return false
|
||||
}
|
||||
// Prefer the cancellation branch deterministically: with both cases ready
|
||||
// select would pick at random and could push into an abandoned channel.
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
a.aborted = true
|
||||
return false
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case ch <- resp:
|
||||
return true
|
||||
case <-a.ctx.Done():
|
||||
a.aborted = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Aborted reports whether the consumer went away mid-stream. Protocol loops
|
||||
// check it to stop reading instead of decoding a stream nobody listens to.
|
||||
func (a *StreamAssembler) Aborted() bool { return a.aborted }
|
||||
|
||||
// NewStreamAssembler creates an assembler for one stream.
|
||||
func NewStreamAssembler(ctx context.Context, model string) *StreamAssembler {
|
||||
return &StreamAssembler{
|
||||
ctx: ctx,
|
||||
model: model,
|
||||
toolCallMap: make(map[int]*types.LLMToolCall),
|
||||
lastFunctionName: make(map[int]string),
|
||||
nameNotified: make(map[int]bool),
|
||||
fieldExtractors: make(map[int]*JSONFieldExtractor),
|
||||
fileProgress: make(map[int]*SandboxFileProgress),
|
||||
startedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *StreamAssembler) elapsedMs() int64 {
|
||||
if a.startedAt.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return time.Since(a.startedAt).Milliseconds()
|
||||
}
|
||||
|
||||
// OrderedToolCalls returns the assembled calls in index order, or nil.
|
||||
//
|
||||
// The indices are the vendor's, not ours: gateways number calls from 1, and
|
||||
// parallel calls can arrive with gaps. Walking 0..len(map) would silently drop
|
||||
// every call outside that range — and a round that loses its calls reaches the
|
||||
// agent as a plain answer — so the keys are sorted instead.
|
||||
func (a *StreamAssembler) OrderedToolCalls() []types.LLMToolCall {
|
||||
if len(a.toolCallMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
indices := make([]int, 0, len(a.toolCallMap))
|
||||
for idx := range a.toolCallMap {
|
||||
indices = append(indices, idx)
|
||||
}
|
||||
sort.Ints(indices)
|
||||
result := make([]types.LLMToolCall, 0, len(a.toolCallMap))
|
||||
for _, idx := range indices {
|
||||
if tc := a.toolCallMap[idx]; tc != nil {
|
||||
result = append(result, *tc)
|
||||
}
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ToolCallCount reports how many distinct tool calls have been seen.
|
||||
func (a *StreamAssembler) ToolCallCount() int { return len(a.toolCallMap) }
|
||||
|
||||
// SetToolCallMetadata attaches provider state to the call at index, creating
|
||||
// a placeholder entry when the metadata arrives before the call itself.
|
||||
func (a *StreamAssembler) SetToolCallMetadata(index int, metadata types.ToolCallMetadata) {
|
||||
if len(metadata) == 0 {
|
||||
return
|
||||
}
|
||||
entry, exists := a.toolCallMap[index]
|
||||
if !exists || entry == nil {
|
||||
entry = &types.LLMToolCall{Type: "function"}
|
||||
a.toolCallMap[index] = entry
|
||||
}
|
||||
entry.ProviderMetadata = metadata
|
||||
}
|
||||
|
||||
// SetUsage records usage from the vendor's final chunk.
|
||||
func (a *StreamAssembler) SetUsage(u types.TokenUsage) { a.Usage = &u }
|
||||
|
||||
// doneData renders the reasoning artifacts for the closing chunk.
|
||||
func (a *StreamAssembler) doneData() map[string]interface{} {
|
||||
if a.ReasoningSignature == "" && len(a.ReasoningMetadata) == 0 {
|
||||
return nil
|
||||
}
|
||||
data := map[string]interface{}{}
|
||||
if a.ReasoningSignature != "" {
|
||||
data["reasoning_signature"] = a.ReasoningSignature
|
||||
}
|
||||
if len(a.ReasoningMetadata) > 0 {
|
||||
data["reasoning_metadata"] = a.ReasoningMetadata
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// Process consumes one delta and emits the resulting stream responses. It
|
||||
// mirrors the event sequence of the original OpenAI stream loop so every
|
||||
// downstream consumer sees exactly what it saw before the protocol split.
|
||||
func (a *StreamAssembler) Process(ch chan<- types.StreamResponse, d Delta) {
|
||||
isDone := d.FinishReason != ""
|
||||
if isDone {
|
||||
a.LastFinishReason = d.FinishReason
|
||||
}
|
||||
|
||||
if len(d.ToolCalls) > 0 {
|
||||
a.processToolCalls(ch, d.ToolCalls)
|
||||
}
|
||||
|
||||
if isDone && d.FinishReason == "stop" && !a.firstToolCallSeen && !a.noToolCallStopLogged {
|
||||
logger.Infof(a.ctx, "[LLM Stream] Natural-stop at protocol layer "+
|
||||
"(finish=stop, tool_calls never observed, thinking_seen=%t, first_content_seen=%t, elapsed_ms=%d)",
|
||||
a.active, a.firstContentSeen, a.elapsedMs())
|
||||
a.noToolCallStopLogged = true
|
||||
}
|
||||
|
||||
if d.Reasoning != "" {
|
||||
if !a.firstReasoningSeen {
|
||||
a.firstReasoningSeen = true
|
||||
logger.Infof(a.ctx, "[LLM Stream] First reasoning chunk at protocol layer "+
|
||||
"(len=%d, preview=%q, elapsed_ms=%d)",
|
||||
len(d.Reasoning), TruncateForDebug(d.Reasoning, 80), a.elapsedMs())
|
||||
}
|
||||
a.Emit(ch, d.Reasoning)
|
||||
}
|
||||
|
||||
if d.Content != "" {
|
||||
if !a.firstContentSeen {
|
||||
a.firstContentSeen = true
|
||||
logger.Infof(a.ctx, "[LLM Stream] First content chunk at protocol layer "+
|
||||
"(len=%d, preview=%q, tool_call_seen=%t, thinking_seen=%t, elapsed_ms=%d)",
|
||||
len(d.Content), TruncateForDebug(d.Content, 80),
|
||||
a.firstToolCallSeen, a.firstReasoningSeen, a.elapsedMs())
|
||||
}
|
||||
a.Finish(ch)
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: d.Content,
|
||||
Done: isDone,
|
||||
ToolCalls: a.OrderedToolCalls(),
|
||||
FinishReason: d.FinishReason,
|
||||
})
|
||||
}
|
||||
|
||||
if isDone && len(a.toolCallMap) > 0 {
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
ToolCalls: a.OrderedToolCalls(),
|
||||
FinishReason: d.FinishReason,
|
||||
})
|
||||
}
|
||||
|
||||
if isDone {
|
||||
a.Finish(ch)
|
||||
}
|
||||
|
||||
if isDone && d.Content == "" && len(a.toolCallMap) == 0 {
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: d.FinishReason,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Emit forwards a reasoning chunk through the cancellation-aware send,
|
||||
// shadowing the embedded ThinkingEmitter's blocking version.
|
||||
func (a *StreamAssembler) Emit(ch chan<- types.StreamResponse, content string) {
|
||||
a.active = true
|
||||
a.emit(ch, types.StreamResponse{ResponseType: types.ResponseTypeThinking, Content: content})
|
||||
}
|
||||
|
||||
// Finish emits the single thinking-done marker if one is owed, through the
|
||||
// cancellation-aware send. Shadows the embedded ThinkingEmitter's version.
|
||||
func (a *StreamAssembler) Finish(ch chan<- types.StreamResponse) {
|
||||
if !a.active {
|
||||
return
|
||||
}
|
||||
a.active = false
|
||||
a.emit(ch, types.StreamResponse{ResponseType: types.ResponseTypeThinking, Done: true})
|
||||
}
|
||||
|
||||
// End emits the closing chunk once the vendor stream is exhausted. It logs
|
||||
// usage and carries the assembled tool calls, usage and reasoning artifacts.
|
||||
func (a *StreamAssembler) End(ch chan<- types.StreamResponse) {
|
||||
a.Finish(ch)
|
||||
LogUsage(a.ctx, a.model, a.Usage)
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
ToolCalls: a.OrderedToolCalls(),
|
||||
Usage: a.Usage,
|
||||
FinishReason: a.LastFinishReason,
|
||||
Data: a.doneData(),
|
||||
})
|
||||
}
|
||||
|
||||
// Fail emits the error chunk for a broken stream.
|
||||
func (a *StreamAssembler) Fail(ch chan<- types.StreamResponse, err error) {
|
||||
logger.Errorf(a.ctx, "Stream read error: %v (tool_calls_assembled=%d)", err, len(a.toolCallMap))
|
||||
a.Finish(ch)
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeError,
|
||||
Content: err.Error(),
|
||||
Done: true,
|
||||
ToolCalls: a.OrderedToolCalls(),
|
||||
Usage: a.Usage,
|
||||
FinishReason: types.FinishReasonIncomplete,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *StreamAssembler) processToolCalls(ch chan<- types.StreamResponse, deltas []ToolCallDelta) {
|
||||
if !a.firstToolCallSeen && len(deltas) > 0 {
|
||||
a.firstToolCallSeen = true
|
||||
var firstID, firstName string
|
||||
for _, tc := range deltas {
|
||||
if tc.ID != "" {
|
||||
firstID = tc.ID
|
||||
}
|
||||
if tc.Name != "" {
|
||||
firstName = tc.Name
|
||||
}
|
||||
if firstID != "" || firstName != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.Infof(a.ctx, "[LLM Stream] First tool_calls delta at protocol layer "+
|
||||
"(count=%d, first_id=%q, first_name=%q, first_content_seen=%t, thinking_seen=%t, elapsed_ms=%d)",
|
||||
len(deltas), firstID, firstName, a.firstContentSeen, a.firstReasoningSeen, a.elapsedMs())
|
||||
}
|
||||
|
||||
for _, tc := range deltas {
|
||||
index := tc.Index
|
||||
entry, exists := a.toolCallMap[index]
|
||||
if !exists || entry == nil {
|
||||
entry = &types.LLMToolCall{Type: tc.Type}
|
||||
a.toolCallMap[index] = entry
|
||||
}
|
||||
if tc.ID != "" {
|
||||
entry.ID = tc.ID
|
||||
}
|
||||
if tc.Type != "" {
|
||||
entry.Type = tc.Type
|
||||
}
|
||||
if entry.Type == "" {
|
||||
entry.Type = "function"
|
||||
}
|
||||
if tc.Name != "" {
|
||||
// Some runtimes (vLLM Ascend) resend the full name on every chunk;
|
||||
// treat an identical name as a repeat rather than a suffix.
|
||||
if entry.Function.Name != tc.Name {
|
||||
entry.Function.Name += tc.Name
|
||||
}
|
||||
}
|
||||
|
||||
argsUpdated := false
|
||||
if tc.Arguments != "" {
|
||||
entry.Function.Arguments += tc.Arguments
|
||||
argsUpdated = true
|
||||
}
|
||||
|
||||
currName := entry.Function.Name
|
||||
var progressArgs map[string]any
|
||||
if IsSandboxMutationTool(currName) && argsUpdated {
|
||||
prog := a.fileProgress[index]
|
||||
if prog == nil {
|
||||
prog = NewSandboxFileProgress(currName)
|
||||
a.fileProgress[index] = prog
|
||||
}
|
||||
if payload, ok := prog.Feed(tc.Arguments); ok {
|
||||
progressArgs = payload
|
||||
}
|
||||
}
|
||||
|
||||
if currName != "" &&
|
||||
currName == a.lastFunctionName[index] &&
|
||||
argsUpdated &&
|
||||
!a.nameNotified[index] &&
|
||||
entry.ID != "" {
|
||||
data := map[string]interface{}{
|
||||
"tool_name": currName,
|
||||
"tool_call_id": entry.ID,
|
||||
}
|
||||
if progressArgs != nil {
|
||||
data["arguments"] = progressArgs
|
||||
}
|
||||
a.emit(ch, types.StreamResponse{ResponseType: types.ResponseTypeToolCall, Data: data})
|
||||
a.nameNotified[index] = true
|
||||
progressArgs = nil
|
||||
} else if progressArgs != nil && entry.ID != "" && currName != "" {
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeToolCall,
|
||||
Data: map[string]interface{}{
|
||||
"tool_name": currName,
|
||||
"tool_call_id": entry.ID,
|
||||
"arguments": progressArgs,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
a.lastFunctionName[index] = currName
|
||||
|
||||
if entry.Function.Name == "thinking" && argsUpdated {
|
||||
extractor, exists := a.fieldExtractors[index]
|
||||
if !exists {
|
||||
extractor = NewJSONFieldExtractor("thought")
|
||||
a.fieldExtractors[index] = extractor
|
||||
}
|
||||
if chunk := extractor.Feed(tc.Arguments); chunk != "" {
|
||||
a.emit(ch, types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeThinking,
|
||||
Content: chunk,
|
||||
Data: map[string]interface{}{
|
||||
"source": "thinking_tool",
|
||||
"tool_call_id": entry.ID,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TruncateForDebug shortens a string for log previews.
|
||||
func TruncateForDebug(s string, maxRunes int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= maxRunes {
|
||||
return s
|
||||
}
|
||||
return string(runes[:maxRunes]) + fmt.Sprintf("...(%d chars)", len(runes))
|
||||
}
|
||||
|
||||
// ReplaceToolCalls swaps the assembled tool calls for a protocol's own final
|
||||
// view (for example, one that drops calls the stream never closed).
|
||||
func (a *StreamAssembler) ReplaceToolCalls(calls []types.LLMToolCall) {
|
||||
a.toolCallMap = make(map[int]*types.LLMToolCall, len(calls))
|
||||
for i := range calls {
|
||||
call := calls[i]
|
||||
a.toolCallMap[i] = &call
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// A consumer that walks away must not pin the producing goroutine forever.
|
||||
// Before the cancellation-aware send this blocked on `ch <-` for the life of
|
||||
// the process, leaking the goroutine, the HTTP body and the timeout context.
|
||||
func TestStreamAssembler_AbandonedConsumerDoesNotBlock(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
a := NewStreamAssembler(ctx, "m")
|
||||
|
||||
ch := make(chan types.StreamResponse) // unbuffered, never read
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
a.Process(ch, Delta{Content: "hello"})
|
||||
a.Process(ch, Delta{FinishReason: "stop"})
|
||||
a.End(ch)
|
||||
}()
|
||||
|
||||
// Let the producer park on the first send, then drop the consumer.
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("producer still blocked after the consumer went away")
|
||||
}
|
||||
if !a.Aborted() {
|
||||
t.Fatal("Aborted() = false, want true after an abandoned send")
|
||||
}
|
||||
}
|
||||
|
||||
// An already-cancelled context must abort deterministically rather than
|
||||
// racing a ready channel.
|
||||
func TestStreamAssembler_CancelledContextAbortsImmediately(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
a := NewStreamAssembler(ctx, "m")
|
||||
|
||||
ch := make(chan types.StreamResponse, 8)
|
||||
a.Process(ch, Delta{Content: "hello"})
|
||||
a.End(ch)
|
||||
|
||||
if len(ch) != 0 {
|
||||
t.Fatalf("emitted %d chunks into an abandoned stream, want 0", len(ch))
|
||||
}
|
||||
if !a.Aborted() {
|
||||
t.Fatal("Aborted() = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
// The live path must keep the exact chunk sequence the engine expects:
|
||||
// thinking chunks, one thinking-done marker before the first answer token,
|
||||
// the answer, then the closing chunk.
|
||||
func TestStreamAssembler_ThinkingHandoffSequence(t *testing.T) {
|
||||
a := NewStreamAssembler(context.Background(), "m")
|
||||
ch := make(chan types.StreamResponse, 16)
|
||||
|
||||
a.Process(ch, Delta{Reasoning: "think"})
|
||||
a.Process(ch, Delta{Content: "answer", FinishReason: "stop"})
|
||||
a.End(ch)
|
||||
close(ch)
|
||||
|
||||
type step struct {
|
||||
kind types.ResponseType
|
||||
done bool
|
||||
text string
|
||||
}
|
||||
var got []step
|
||||
for chunk := range ch {
|
||||
got = append(got, step{chunk.ResponseType, chunk.Done, chunk.Content})
|
||||
}
|
||||
want := []step{
|
||||
{types.ResponseTypeThinking, false, "think"},
|
||||
{types.ResponseTypeThinking, true, ""},
|
||||
{types.ResponseTypeAnswer, true, "answer"},
|
||||
{types.ResponseTypeAnswer, true, ""},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("sequence = %#v, want %#v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("chunk %d = %#v, want %#v", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tool-call indices belong to the vendor: gateways number from 1 and parallel
|
||||
// calls arrive with gaps. Walking 0..len(map) dropped every call outside that
|
||||
// range, and a round whose calls vanish reaches the agent as a plain answer.
|
||||
func TestStreamAssembler_OrderedToolCallsNonContiguousIndices(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
indices []int
|
||||
want []string
|
||||
}{
|
||||
{name: "zero based", indices: []int{0, 1}, want: []string{"f0", "f1"}},
|
||||
{name: "one based", indices: []int{1, 2}, want: []string{"f1", "f2"}},
|
||||
{name: "gapped", indices: []int{0, 3, 7}, want: []string{"f0", "f3", "f7"}},
|
||||
{name: "out of order arrival", indices: []int{5, 2}, want: []string{"f2", "f5"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
a := NewStreamAssembler(context.Background(), "m")
|
||||
ch := make(chan types.StreamResponse, 64)
|
||||
for _, idx := range tc.indices {
|
||||
a.Process(ch, Delta{ToolCalls: []ToolCallDelta{{
|
||||
Index: idx,
|
||||
ID: fmt.Sprintf("call_%d", idx),
|
||||
Name: fmt.Sprintf("f%d", idx),
|
||||
Arguments: `{}`,
|
||||
}}})
|
||||
}
|
||||
|
||||
calls := a.OrderedToolCalls()
|
||||
if len(calls) != len(tc.want) {
|
||||
t.Fatalf("got %d calls %#v, want %d", len(calls), calls, len(tc.want))
|
||||
}
|
||||
for i, name := range tc.want {
|
||||
if calls[i].Function.Name != name {
|
||||
t.Fatalf("call %d = %q, want %q (order must follow the vendor index)",
|
||||
i, calls[i].Function.Name, name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata-only entries (a thought signature that arrives before its call)
|
||||
// are kept too, whatever index the vendor gave them.
|
||||
func TestStreamAssembler_OrderedToolCallsIncludesMetadataOnlyIndex(t *testing.T) {
|
||||
a := NewStreamAssembler(context.Background(), "m")
|
||||
a.SetToolCallMetadata(4, types.ToolCallMetadata{"thought_signature": []byte(`"sig"`)})
|
||||
|
||||
calls := a.OrderedToolCalls()
|
||||
if len(calls) != 1 {
|
||||
t.Fatalf("got %d calls, want 1", len(calls))
|
||||
}
|
||||
if calls[0].ProviderMetadata["thought_signature"] == nil {
|
||||
t.Fatal("provider metadata lost")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +1,19 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import "github.com/Tencent/WeKnora/internal/types"
|
||||
|
||||
// thinkingEmitter owns the "reasoning then answer" hand-off that every
|
||||
// ThinkingEmitter owns the "reasoning then answer" hand-off that every
|
||||
// streaming Chat implementation shares: thinking chunks are forwarded as they
|
||||
// arrive, and exactly one thinking-done marker is emitted before the first
|
||||
// answer token (or when the stream ends without one). Centralizing the
|
||||
// bookkeeping keeps the OpenAI-compatible and Ollama stream loops in sync.
|
||||
type thinkingEmitter struct {
|
||||
type ThinkingEmitter struct {
|
||||
active bool
|
||||
}
|
||||
|
||||
// emit forwards a reasoning chunk and records that a thinking-done marker is
|
||||
// Emit forwards a reasoning chunk and records that a thinking-done marker is
|
||||
// still owed.
|
||||
func (e *thinkingEmitter) emit(ch chan types.StreamResponse, content string) {
|
||||
func (e *ThinkingEmitter) Emit(ch chan<- types.StreamResponse, content string) {
|
||||
e.active = true
|
||||
ch <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeThinking,
|
||||
|
|
@ -22,9 +22,9 @@ func (e *thinkingEmitter) emit(ch chan types.StreamResponse, content string) {
|
|||
}
|
||||
}
|
||||
|
||||
// finish emits the single thinking-done marker if one is owed. Safe to call
|
||||
// Finish emits the single thinking-done marker if one is owed. Safe to call
|
||||
// multiple times; only the first call after an emit sends anything.
|
||||
func (e *thinkingEmitter) finish(ch chan types.StreamResponse) {
|
||||
func (e *ThinkingEmitter) Finish(ch chan<- types.StreamResponse) {
|
||||
if !e.active {
|
||||
return
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
|
@ -17,8 +17,8 @@ import (
|
|||
// - WEKNORA_LLM_CHAT_TIMEOUT_SECONDS 非流式调用兜底超时(默认 600s)
|
||||
// - WEKNORA_LLM_STREAM_TIMEOUT_SECONDS 流式调用兜底超时(默认 1800s)
|
||||
var (
|
||||
defaultChatTimeout = envDurationSeconds("WEKNORA_LLM_CHAT_TIMEOUT_SECONDS", 300*time.Second)
|
||||
defaultStreamTimeout = envDurationSeconds("WEKNORA_LLM_STREAM_TIMEOUT_SECONDS", 600*time.Second)
|
||||
DefaultChatTimeout = envDurationSeconds("WEKNORA_LLM_CHAT_TIMEOUT_SECONDS", 300*time.Second)
|
||||
DefaultStreamTimeout = envDurationSeconds("WEKNORA_LLM_STREAM_TIMEOUT_SECONDS", 600*time.Second)
|
||||
)
|
||||
|
||||
// envDurationSeconds 读取以"秒"为单位的环境变量,解析失败或非正值时回退到 fallback。
|
||||
|
|
@ -34,21 +34,21 @@ func envDurationSeconds(key string, fallback time.Duration) time.Duration {
|
|||
return time.Duration(n) * time.Second
|
||||
}
|
||||
|
||||
// withLLMTimeout 仅在上层 ctx 没有 deadline 时附加一个兜底超时;
|
||||
// WithLLMTimeout 仅在上层 ctx 没有 deadline 时附加一个兜底超时;
|
||||
// 如果上层已显式设置 deadline(无论更短或更长),则原样返回,
|
||||
// 让调用方对自己的超时策略拥有最终决定权。
|
||||
func withLLMTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
|
||||
func WithLLMTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
|
||||
if _, ok := ctx.Deadline(); ok {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithTimeout(ctx, d)
|
||||
}
|
||||
|
||||
// rawHTTPClient is a shared HTTP client for raw HTTP LLM calls with connection-level timeouts.
|
||||
// Per-request timeout is enforced via context deadline (see defaultChatTimeout / defaultStreamTimeout)
|
||||
// HTTPClient is a shared HTTP client for raw HTTP LLM calls with connection-level timeouts.
|
||||
// Per-request timeout is enforced via context deadline (see DefaultChatTimeout / DefaultStreamTimeout)
|
||||
// rather than http.Client.Timeout, so streaming calls are not prematurely terminated.
|
||||
// Uses SSRFSafeDialContext to prevent DNS rebinding attacks at the connection layer.
|
||||
var rawHTTPTransport = &http.Transport{
|
||||
var httpTransport = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: secutils.SSRFSafeDialContext,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
|
|
@ -56,7 +56,8 @@ var rawHTTPTransport = &http.Transport{
|
|||
MaxIdleConnsPerHost: 5,
|
||||
}
|
||||
|
||||
var rawHTTPClient = secutils.NewSSRFSafeHTTPClientWithTransport(
|
||||
// HTTPClient is the shared SSRF-safe client every protocol uses.
|
||||
var HTTPClient = secutils.NewSSRFSafeHTTPClientWithTransport(
|
||||
secutils.SSRFSafeHTTPClientConfig{Timeout: 0, MaxRedirects: 10},
|
||||
rawHTTPTransport,
|
||||
httpTransport,
|
||||
)
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
|
@ -8,7 +8,7 @@ import (
|
|||
)
|
||||
|
||||
func TestWithLLMTimeout_NoParentDeadline_AppliesDefault(t *testing.T) {
|
||||
ctx, cancel := withLLMTimeout(context.Background(), 50*time.Millisecond)
|
||||
ctx, cancel := WithLLMTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
dl, ok := ctx.Deadline()
|
||||
|
|
@ -24,7 +24,7 @@ func TestWithLLMTimeout_ShorterParentDeadline_Respected(t *testing.T) {
|
|||
parent, parentCancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer parentCancel()
|
||||
|
||||
ctx, cancel := withLLMTimeout(parent, 10*time.Second)
|
||||
ctx, cancel := WithLLMTimeout(parent, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dl, _ := ctx.Deadline()
|
||||
|
|
@ -37,7 +37,7 @@ func TestWithLLMTimeout_LongerParentDeadline_NotTruncated(t *testing.T) {
|
|||
parent, parentCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer parentCancel()
|
||||
|
||||
ctx, cancel := withLLMTimeout(parent, 50*time.Millisecond)
|
||||
ctx, cancel := WithLLMTimeout(parent, 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
dl, ok := ctx.Deadline()
|
||||
|
|
@ -0,0 +1,304 @@
|
|||
// Package api holds the protocol-neutral request model shared by every wire
|
||||
// protocol implementation (OpenAI Chat Completions, OpenAI Responses,
|
||||
// Anthropic Messages, Google Generative AI, Ollama) plus the helpers those
|
||||
// implementations share: SSE reading, the SSRF-safe transport, streaming
|
||||
// tool-call assembly, prompt-cache bookkeeping and usage logging.
|
||||
//
|
||||
// Protocol packages live under api/<protocol>; vendor facts live in
|
||||
// internal/models/catalog and internal/models/vendors. This package must not
|
||||
// import either of them.
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// API identifies a wire protocol. It is the value of the "api" field in a
|
||||
// vendor's models.json and decides which protocol package talks to the
|
||||
// endpoint.
|
||||
type API string
|
||||
|
||||
const (
|
||||
// APIOpenAICompletions is the OpenAI Chat Completions protocol, the
|
||||
// lingua franca of almost every third-party vendor.
|
||||
APIOpenAICompletions API = "openai-completions"
|
||||
// APIOpenAIResponses is the OpenAI Responses protocol.
|
||||
APIOpenAIResponses API = "openai-responses"
|
||||
// APIAnthropicMessages is the Anthropic Messages protocol, also exposed by
|
||||
// MiniMax, Zhipu and Moonshot as a compatibility surface.
|
||||
APIAnthropicMessages API = "anthropic-messages"
|
||||
// APIGoogleGenerativeAI is the native Gemini generateContent protocol.
|
||||
APIGoogleGenerativeAI API = "google-generative-ai"
|
||||
// APIOllama is the local Ollama chat protocol.
|
||||
APIOllama API = "ollama"
|
||||
)
|
||||
|
||||
// Known reports whether the API value names a protocol this build ships.
|
||||
func (a API) Known() bool {
|
||||
switch a {
|
||||
case APIOpenAICompletions, APIOpenAIResponses, APIAnthropicMessages, APIGoogleGenerativeAI, APIOllama:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Tool represents a function/tool definition
|
||||
type Tool struct {
|
||||
Type string `json:"type"` // "function"
|
||||
Function FunctionDef `json:"function"`
|
||||
}
|
||||
|
||||
// FunctionDef represents a function definition
|
||||
type FunctionDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters json.RawMessage `json:"parameters"`
|
||||
}
|
||||
|
||||
// MessageContentPart represents a part of multi-content message
|
||||
type MessageContentPart struct {
|
||||
Type string `json:"type"` // "text" or "image_url"
|
||||
Text string `json:"text,omitempty"` // For type="text"
|
||||
ImageURL *ImageURL `json:"image_url,omitempty"` // For type="image_url"
|
||||
}
|
||||
|
||||
// ImageURL represents the image URL structure
|
||||
type ImageURL struct {
|
||||
URL string `json:"url"` // URL or base64 data URI
|
||||
Detail string `json:"detail,omitempty"` // "auto", "low", "high"
|
||||
}
|
||||
|
||||
// MessageKind marks messages the engine synthesized rather than received from
|
||||
// the user or the model. Compaction needs to tell its own summary apart from a
|
||||
// real user turn: a summary that looks like ordinary history gets fed back into
|
||||
// the next summarization pass and degrades into a summary of a summary.
|
||||
type MessageKind string
|
||||
|
||||
// MessageKindCompactionSummary marks the message that replaces compacted
|
||||
// history. It carries the `user` role because that is where providers expect
|
||||
// conversation history, so the role alone cannot identify it.
|
||||
const MessageKindCompactionSummary MessageKind = "compaction_summary"
|
||||
|
||||
// Message 表示聊天消息
|
||||
type Message struct {
|
||||
Role string `json:"role"` // 角色:system, user, assistant, tool
|
||||
Content string `json:"content"` // 消息内容
|
||||
MultiContent []MessageContentPart `json:"multi_content,omitempty"` // 多内容消息(文本+图片)
|
||||
Name string `json:"name,omitempty"` // Function/tool name (for tool role)
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // Tool call ID (for tool role)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"` // Tool calls (for assistant role)
|
||||
// Images are image URLs for multimodal input (current user message only).
|
||||
Images []string `json:"images,omitempty"`
|
||||
// ReasoningContent 是 assistant 推理类模型上一轮输出的思考内容。部分供应商
|
||||
// (MiMo、DeepSeek V3.2+、Kimi K2.5+)要求多轮对话中把 assistant 的
|
||||
// reasoning_content 原样回传,否则会以 400 拒绝请求;其他不要求的供应商会
|
||||
// 忽略未知字段。Anthropic 则要求把 thinking block 连同签名一起回放。
|
||||
ReasoningContent string `json:"reasoning_content,omitempty"`
|
||||
// ReasoningSignature is the provider-issued signature that must accompany
|
||||
// ReasoningContent when it is replayed (Anthropic thinking blocks, Gemini
|
||||
// thought signatures on text parts). Empty when the provider issues none.
|
||||
ReasoningSignature string `json:"reasoning_signature,omitempty"`
|
||||
// ReasoningMetadata carries opaque provider state that must round-trip
|
||||
// with the assistant turn but has no protocol-neutral representation:
|
||||
// OpenAI Responses reasoning items (encrypted_content), OpenRouter
|
||||
// reasoning_details, and so on. Keyed by protocol / vendor namespace.
|
||||
ReasoningMetadata types.ProviderMetadata `json:"reasoning_metadata,omitempty"`
|
||||
// Kind is engine-internal bookkeeping. `json:"-"` keeps it off the wire:
|
||||
// providers reject unknown message fields on some endpoints, and this one
|
||||
// means nothing to them anyway.
|
||||
Kind MessageKind `json:"-"`
|
||||
// TurnID is the stored assistant message whose turn this history message
|
||||
// was replayed from. It is empty for the live turn and for messages the
|
||||
// engine synthesized. Compaction uses it to tell whether a summary ends
|
||||
// exactly on a stored turn, the only kind it can persist for later turns.
|
||||
// Engine-internal like Kind, and kept off the wire for the same reason.
|
||||
TurnID string `json:"-"`
|
||||
}
|
||||
|
||||
// ToolCall represents a tool call in a message
|
||||
type ToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"` // "function"
|
||||
Function FunctionCall `json:"function"`
|
||||
ProviderMetadata types.ToolCallMetadata `json:"provider_metadata,omitempty"`
|
||||
}
|
||||
|
||||
// FunctionCall represents a function call
|
||||
type FunctionCall struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"` // JSON string
|
||||
}
|
||||
|
||||
// ReasoningEffort is the protocol-neutral thinking level. Vendors map it onto
|
||||
// their own vocabulary through a ThinkingLevelMap; the protocol package then
|
||||
// emits whichever wire field the vendor documents (reasoning_effort,
|
||||
// thinking.type, enable_thinking, thinkingConfig, ...).
|
||||
type ReasoningEffort string
|
||||
|
||||
const (
|
||||
// ReasoningOff disables extended thinking where the model allows it.
|
||||
ReasoningOff ReasoningEffort = "off"
|
||||
// ReasoningAuto enables thinking but leaves the intensity to the provider
|
||||
// default. This is what the legacy boolean `thinking: true` maps to.
|
||||
ReasoningAuto ReasoningEffort = "auto"
|
||||
// ReasoningMinimal is the weakest graded level.
|
||||
ReasoningMinimal ReasoningEffort = "minimal"
|
||||
// ReasoningLow is the low graded level.
|
||||
ReasoningLow ReasoningEffort = "low"
|
||||
// ReasoningMedium is the medium graded level.
|
||||
ReasoningMedium ReasoningEffort = "medium"
|
||||
// ReasoningHigh is the high graded level.
|
||||
ReasoningHigh ReasoningEffort = "high"
|
||||
// ReasoningXHigh is the extra-high graded level (OpenAI, Zhipu).
|
||||
ReasoningXHigh ReasoningEffort = "xhigh"
|
||||
// ReasoningMax is the strongest graded level.
|
||||
ReasoningMax ReasoningEffort = "max"
|
||||
)
|
||||
|
||||
// ReasoningLadder lists the graded levels from weakest to strongest. Off and
|
||||
// Auto are deliberately excluded: they are switches, not intensities.
|
||||
var ReasoningLadder = []ReasoningEffort{
|
||||
ReasoningMinimal, ReasoningLow, ReasoningMedium, ReasoningHigh, ReasoningXHigh, ReasoningMax,
|
||||
}
|
||||
|
||||
// AllReasoningEfforts is every accepted value, in UI order.
|
||||
var AllReasoningEfforts = append([]ReasoningEffort{ReasoningOff, ReasoningAuto}, ReasoningLadder...)
|
||||
|
||||
// ParseReasoningEffort validates a user-provided level. Empty input yields
|
||||
// ("", true) meaning "unset: let the model default apply".
|
||||
func ParseReasoningEffort(s string) (ReasoningEffort, bool) {
|
||||
if s == "" {
|
||||
return "", true
|
||||
}
|
||||
for _, level := range AllReasoningEfforts {
|
||||
if string(level) == s {
|
||||
return level, true
|
||||
}
|
||||
}
|
||||
// Accept a few aliases the legacy boolean UI and provider docs use.
|
||||
switch s {
|
||||
case "none", "false", "disabled":
|
||||
return ReasoningOff, true
|
||||
case "true", "enabled", "default", "on":
|
||||
return ReasoningAuto, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Enabled reports whether the level asks for thinking to be on.
|
||||
func (r ReasoningEffort) Enabled() bool {
|
||||
return r != "" && r != ReasoningOff
|
||||
}
|
||||
|
||||
// Graded reports whether the level is one of the intensity rungs.
|
||||
func (r ReasoningEffort) Graded() bool {
|
||||
for _, level := range ReasoningLadder {
|
||||
if level == r {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ThinkingLevelMap maps protocol-neutral levels to a vendor's own vocabulary.
|
||||
//
|
||||
// Semantics mirror Pi's thinkingLevelMap:
|
||||
// - a missing key means "supported, pass the level name through" for
|
||||
// minimal/low/medium/high and "unsupported" for xhigh/max;
|
||||
// - a null value marks the level as unsupported (the caller clamps to the
|
||||
// nearest supported rung);
|
||||
// - a string value is what the vendor expects on the wire.
|
||||
//
|
||||
// The special key "off" may be mapped to null to state that thinking cannot
|
||||
// be switched off (always-on reasoning models).
|
||||
type ThinkingLevelMap map[ReasoningEffort]*string
|
||||
|
||||
// Supports reports whether the level is usable for this model.
|
||||
func (m ThinkingLevelMap) Supports(level ReasoningEffort) bool {
|
||||
if v, ok := m[level]; ok {
|
||||
return v != nil
|
||||
}
|
||||
switch level {
|
||||
case ReasoningXHigh, ReasoningMax:
|
||||
return false
|
||||
case ReasoningOff, ReasoningAuto:
|
||||
return true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Value returns the vendor value for a supported level. Unmapped levels
|
||||
// pass through under their own name.
|
||||
func (m ThinkingLevelMap) Value(level ReasoningEffort) string {
|
||||
if v, ok := m[level]; ok && v != nil {
|
||||
return *v
|
||||
}
|
||||
return string(level)
|
||||
}
|
||||
|
||||
// Clamp returns the nearest supported graded level: first upward, then
|
||||
// downward, mirroring Pi's clampThinkingLevel. Off/Auto are returned as-is
|
||||
// (Off may still be unsupported; callers check Supports(ReasoningOff)).
|
||||
func (m ThinkingLevelMap) Clamp(level ReasoningEffort) ReasoningEffort {
|
||||
if !level.Graded() {
|
||||
return level
|
||||
}
|
||||
if m.Supports(level) {
|
||||
return level
|
||||
}
|
||||
idx := -1
|
||||
for i, l := range ReasoningLadder {
|
||||
if l == level {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := idx + 1; i < len(ReasoningLadder); i++ {
|
||||
if m.Supports(ReasoningLadder[i]) {
|
||||
return ReasoningLadder[i]
|
||||
}
|
||||
}
|
||||
for i := idx - 1; i >= 0; i-- {
|
||||
if m.Supports(ReasoningLadder[i]) {
|
||||
return ReasoningLadder[i]
|
||||
}
|
||||
}
|
||||
return ReasoningAuto
|
||||
}
|
||||
|
||||
// SupportedLevels lists the levels this map accepts, in UI order.
|
||||
func (m ThinkingLevelMap) SupportedLevels() []ReasoningEffort {
|
||||
out := make([]ReasoningEffort, 0, len(AllReasoningEfforts))
|
||||
for _, level := range AllReasoningEfforts {
|
||||
if m.Supports(level) {
|
||||
out = append(out, level)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// StringPtr is a small helper for building ThinkingLevelMap literals.
|
||||
func StringPtr(s string) *string { return &s }
|
||||
|
||||
// TagSignature records which protocol issued a reasoning signature. Stored
|
||||
// signatures are opaque to every other provider, so they must only be
|
||||
// replayed to the protocol that produced them.
|
||||
func TagSignature(protocol API, signature string) string {
|
||||
if signature == "" {
|
||||
return ""
|
||||
}
|
||||
return string(protocol) + ":" + signature
|
||||
}
|
||||
|
||||
// SignatureFor returns the raw signature when it was issued by protocol, and
|
||||
// "" for signatures from another protocol or without a protocol tag.
|
||||
func SignatureFor(protocol API, tagged string) string {
|
||||
prefix := string(protocol) + ":"
|
||||
if !strings.HasPrefix(tagged, prefix) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(tagged, prefix)
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
package api
|
||||
|
||||
import "github.com/Tencent/WeKnora/internal/types"
|
||||
|
||||
// OpenAIUsage is the superset of the usage shapes OpenAI-compatible
|
||||
// endpoints return. Vendors disagree on where cache counters live:
|
||||
// - OpenAI / Azure / most gateways: prompt_tokens_details.cached_tokens
|
||||
// - DeepSeek: prompt_cache_hit_tokens / prompt_cache_miss_tokens
|
||||
// - Kimi: top-level cached_tokens
|
||||
// - Anthropic-through-OpenRouter: cache_read_input_tokens / cache_creation_input_tokens
|
||||
//
|
||||
// All of them are decoded here so protocol code never guesses per vendor.
|
||||
type OpenAIUsage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
PromptCacheHitTokens *int `json:"prompt_cache_hit_tokens"`
|
||||
PromptCacheMissTokens *int `json:"prompt_cache_miss_tokens"`
|
||||
CachedTokens *int `json:"cached_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
PromptTokensDetails *struct {
|
||||
CachedTokens *int `json:"cached_tokens"`
|
||||
CacheWriteTokens *int `json:"cache_write_tokens"`
|
||||
} `json:"prompt_tokens_details"`
|
||||
CompletionTokensDetails *struct {
|
||||
ReasoningTokens int `json:"reasoning_tokens"`
|
||||
} `json:"completion_tokens_details"`
|
||||
}
|
||||
|
||||
// ToTokenUsage normalizes the counters. cacheAccounting states whether the
|
||||
// vendor documents prompt-cache accounting at all: when it does not, a
|
||||
// missing counter means "unsupported" rather than "unreported".
|
||||
func (u OpenAIUsage) ToTokenUsage(cacheAccounting bool) types.TokenUsage {
|
||||
out := types.TokenUsage{
|
||||
PromptTokens: u.PromptTokens,
|
||||
CompletionTokens: u.CompletionTokens,
|
||||
TotalTokens: u.TotalTokens,
|
||||
}
|
||||
if out.TotalTokens == 0 {
|
||||
out.TotalTokens = out.PromptTokens + out.CompletionTokens
|
||||
}
|
||||
switch {
|
||||
case u.PromptCacheHitTokens != nil || u.PromptCacheMissTokens != nil:
|
||||
read := valueOrZero(u.PromptCacheHitTokens)
|
||||
miss := valueOrZero(u.PromptCacheMissTokens)
|
||||
out.SetPromptCacheUsage(read, 0, miss, true)
|
||||
case u.CacheReadInputTokens != nil || u.CacheCreationInputTokens != nil:
|
||||
read := valueOrZero(u.CacheReadInputTokens)
|
||||
write := valueOrZero(u.CacheCreationInputTokens)
|
||||
out.SetPromptCacheUsage(read, write, max(0, u.PromptTokens-read), true)
|
||||
case u.PromptTokensDetails != nil &&
|
||||
(u.PromptTokensDetails.CachedTokens != nil || u.PromptTokensDetails.CacheWriteTokens != nil):
|
||||
read := valueOrZero(u.PromptTokensDetails.CachedTokens)
|
||||
write := valueOrZero(u.PromptTokensDetails.CacheWriteTokens)
|
||||
out.SetPromptCacheUsage(read, write, max(0, u.PromptTokens-read), true)
|
||||
case u.CachedTokens != nil:
|
||||
read := valueOrZero(u.CachedTokens)
|
||||
out.SetPromptCacheUsage(read, 0, max(0, u.PromptTokens-read), true)
|
||||
case cacheAccounting:
|
||||
out.SetPromptCacheUsage(0, 0, 0, false)
|
||||
default:
|
||||
out.MarkPromptCacheUnsupported()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func valueOrZero(value *int) int {
|
||||
if value == nil {
|
||||
return 0
|
||||
}
|
||||
return *value
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
|
@ -8,10 +8,10 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// logUsage emits the standard "[LLM Usage]" line shared by every Chat
|
||||
// LogUsage emits the standard "[LLM Usage]" line shared by every Chat
|
||||
// implementation. It is a no-op when usage is nil so callers can pass through
|
||||
// optional usage blocks without guarding at each call site.
|
||||
func logUsage(ctx context.Context, model string, u *types.TokenUsage) {
|
||||
func LogUsage(ctx context.Context, model string, u *types.TokenUsage) {
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package chat
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
|
@ -0,0 +1,309 @@
|
|||
package catalog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func registerTestVendors(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Cleanup(reset())
|
||||
Register(&Vendor{
|
||||
ID: GenericID, Name: "Custom", API: api.APIOpenAICompletions,
|
||||
DefaultBaseURLs: map[types.ModelType]string{},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
Compat: VendorCompat{OpenAICompletions: OpenAICompletionsCompat{
|
||||
MaxTokensField: Ptr("max_tokens"), ThinkingFormat: Ptr(ThinkingFormatChatTemplateKwargs),
|
||||
}},
|
||||
})
|
||||
Register(&Vendor{
|
||||
ID: "acme", Name: "Acme", Names: map[string]string{"zh-CN": "极目"},
|
||||
API: api.APIOpenAICompletions,
|
||||
RequiresAuth: true,
|
||||
URLPatterns: []string{"api.acme.ai", "acme"},
|
||||
DefaultBaseURLs: map[types.ModelType]string{
|
||||
types.ModelTypeKnowledgeQA: "https://api.acme.ai/v1",
|
||||
types.ModelTypeRerank: "https://api.acme.ai/rerank",
|
||||
},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA, types.ModelTypeRerank},
|
||||
Compat: VendorCompat{OpenAICompletions: OpenAICompletionsCompat{
|
||||
ThinkingFormat: Ptr(ThinkingFormatThinkingType),
|
||||
SupportsReasoningEffort: Ptr(true),
|
||||
MaxTokensField: Ptr("max_tokens"),
|
||||
}},
|
||||
ThinkingLevels: api.ThinkingLevelMap{api.ReasoningMax: api.StringPtr("max")},
|
||||
Models: []ModelSpec{
|
||||
{
|
||||
ID: "acme-pro", Name: "Acme Pro", Reasoning: true,
|
||||
Input: []string{"text", "image"}, ContextWindow: 200000,
|
||||
Compat: json.RawMessage(`{"supports_temperature": false}`),
|
||||
},
|
||||
{ID: "acme-r1", Reasoning: true, ThinkingLevels: api.ThinkingLevelMap{api.ReasoningOff: nil}},
|
||||
{Match: "acme-lite*", Reasoning: false, Compat: json.RawMessage(`{"thinking_format": "none"}`)},
|
||||
{Match: "acme-lite-vision*", Input: []string{"text", "image"}},
|
||||
{ID: "acme-embed", Type: types.ModelTypeEmbedding, Dimension: 1024},
|
||||
{
|
||||
ID: "acme-claude", API: api.APIAnthropicMessages, Reasoning: true,
|
||||
Compat: json.RawMessage(`{"thinking_mode": "adaptive", "supports_effort": true}`),
|
||||
},
|
||||
},
|
||||
})
|
||||
Register(&Vendor{
|
||||
ID: "tencent-lkeap", Name: "LKEAP", API: api.APIOpenAICompletions,
|
||||
URLPatterns: []string{"api.lkeap.cloud.tencent.com", "tencent"},
|
||||
DefaultBaseURLs: map[types.ModelType]string{
|
||||
types.ModelTypeKnowledgeQA: "https://api.lkeap.cloud.tencent.com/v1",
|
||||
},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
})
|
||||
}
|
||||
|
||||
func TestFindModel_ExactAliasAndGlob(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
v, _ := Get("acme")
|
||||
|
||||
m, ok := v.FindModel("ACME-PRO")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "acme-pro", m.ID)
|
||||
|
||||
m, ok = v.FindModel("acme-lite-2")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "acme-lite*", m.Match)
|
||||
|
||||
m, ok = v.FindModel("acme-lite-vision-2")
|
||||
require.True(t, ok, "longest literal prefix wins")
|
||||
assert.Equal(t, "acme-lite-vision*", m.Match)
|
||||
|
||||
_, ok = v.FindModel("unknown")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestDetectByURL_LongestPatternWins(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
assert.Equal(t, "tencent-lkeap", DetectByURL("https://api.lkeap.cloud.tencent.com/v1"))
|
||||
assert.Equal(t, "acme", DetectByURL("https://api.acme.ai/v1"))
|
||||
assert.Equal(t, GenericID, DetectByURL("http://localhost:8000/v1"))
|
||||
assert.Equal(t, GenericID, DetectByURL(""))
|
||||
}
|
||||
|
||||
func TestResolve_MergesVendorModelAndOverrideLayers(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Cataloged)
|
||||
assert.Equal(t, api.APIOpenAICompletions, r.API)
|
||||
assert.Equal(t, "https://api.acme.ai/v1", r.BaseURL, "default base URL is filled in")
|
||||
assert.Equal(t, "max_tokens", r.OpenAICompletions.MaxTokensField)
|
||||
assert.Equal(t, ThinkingFormatThinkingType, r.OpenAICompletions.ThinkingFormat)
|
||||
assert.True(t, r.OpenAICompletions.SupportsReasoningEffort)
|
||||
assert.False(t, r.OpenAICompletions.SupportsTemperature, "model compat overrides the protocol default")
|
||||
assert.True(t, r.OpenAICompletions.SupportsUsageInStreaming, "untouched defaults survive")
|
||||
assert.Equal(t, "max", r.ThinkingLevels.Value(api.ReasoningMax))
|
||||
assert.True(t, r.ThinkingLevels.Supports(api.ReasoningMax))
|
||||
assert.Equal(t, 200000, r.Spec.ContextWindow)
|
||||
|
||||
caps := r.Capabilities()
|
||||
assert.True(t, caps.Reasoning)
|
||||
assert.Equal(t, []string{"text", "image"}, caps.Input)
|
||||
assert.Contains(t, caps.ThinkingLevels, api.ReasoningOff)
|
||||
assert.Contains(t, caps.ThinkingLevels, api.ReasoningMax)
|
||||
|
||||
// Row-level override wins over everything.
|
||||
on := true
|
||||
r, err = Resolve(Ref{
|
||||
Provider: "acme", Model: "acme-pro", BaseURL: "https://proxy.example.com/v1/",
|
||||
Override: &types.ModelSpecOverride{
|
||||
ContextWindow: 1000,
|
||||
Reasoning: &on,
|
||||
ThinkingLevels: map[string]*string{"off": nil},
|
||||
Compat: map[string]any{"supports_temperature": true, "max_tokens_field": "max_completion_tokens"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://proxy.example.com/v1", r.BaseURL, "trailing slash trimmed, override kept")
|
||||
assert.Equal(t, 1000, r.Spec.ContextWindow)
|
||||
assert.True(t, r.OpenAICompletions.SupportsTemperature)
|
||||
assert.Equal(t, "max_completion_tokens", r.OpenAICompletions.MaxTokensField)
|
||||
assert.False(t, r.ThinkingLevels.Supports(api.ReasoningOff))
|
||||
}
|
||||
|
||||
func TestResolve_UnknownModelAndVendorDegradeToGeneric(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "brand-new"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.Cataloged)
|
||||
assert.Equal(t, "brand-new", r.Spec.ID)
|
||||
assert.Equal(t, ThinkingFormatThinkingType, r.OpenAICompletions.ThinkingFormat, "vendor defaults still apply")
|
||||
|
||||
r, err = Resolve(Ref{Provider: "nope", Model: "x", BaseURL: "http://localhost:8000/v1"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, GenericID, r.Vendor.ID)
|
||||
assert.Equal(t, ThinkingFormatChatTemplateKwargs, r.OpenAICompletions.ThinkingFormat)
|
||||
|
||||
r, err = Resolve(Ref{Model: "x", BaseURL: "https://api.acme.ai/v1"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "acme", r.Vendor.ID, "provider detected from URL when empty")
|
||||
}
|
||||
|
||||
func TestResolve_ProtocolInference(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-claude"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.APIAnthropicMessages, r.API)
|
||||
assert.Equal(t, AnthropicThinkingAdaptive, r.AnthropicMessages.ThinkingMode)
|
||||
assert.True(t, r.AnthropicMessages.SupportsEffort)
|
||||
assert.Equal(t, "thinking.adaptive", r.Capabilities().ThinkingFormat)
|
||||
|
||||
r, err = Resolve(Ref{Provider: "acme", Model: "acme-pro", BaseURL: "https://api.acme.ai/anthropic"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.APIAnthropicMessages, r.API, "/anthropic suffix switches protocol")
|
||||
|
||||
r, err = Resolve(Ref{Provider: "acme", Model: "acme-pro", Extra: map[string]string{ExtraAPI: "openai-responses"}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.APIOpenAIResponses, r.API, "extra_config.api forces the protocol")
|
||||
|
||||
_, err = Resolve(Ref{Provider: "acme", Model: "acme-pro", Extra: map[string]string{ExtraAPI: "bogus"}})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestResolve_LegacyThinkingControlAndRemoteModelName(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-pro", Extra: map[string]string{
|
||||
ExtraThinkingControl: "enable_thinking",
|
||||
ExtraRemoteModelName: "acme-pro-2026",
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ThinkingFormatEnableThinking, r.OpenAICompletions.ThinkingFormat)
|
||||
assert.Equal(t, "acme-pro-2026", r.RemoteModel)
|
||||
|
||||
r, err = Resolve(Ref{Provider: "acme", Model: "acme-pro", Extra: map[string]string{ExtraThinkingControl: "none"}})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, r.Capabilities().ThinkingLevels, "none disables the selector")
|
||||
}
|
||||
|
||||
func TestResolve_AlwaysOnModelCannotBeSwitchedOff(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-r1"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.ThinkingLevels.Supports(api.ReasoningOff))
|
||||
assert.NotContains(t, r.Capabilities().ThinkingLevels, api.ReasoningOff)
|
||||
}
|
||||
|
||||
func TestResolve_RejectsUnknownCompatKeys(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
_, err := Resolve(Ref{Provider: "acme", Model: "acme-pro", Override: &types.ModelSpecOverride{
|
||||
Compat: map[string]any{"max_token_field": "max_tokens"},
|
||||
}})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "max_token_field")
|
||||
}
|
||||
|
||||
func TestModelsByType(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
v, _ := Get("acme")
|
||||
chat := v.ModelsByType(types.ModelTypeKnowledgeQA)
|
||||
ids := make([]string, 0, len(chat))
|
||||
for _, m := range chat {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
assert.ElementsMatch(t, []string{"acme-pro", "acme-r1", "acme-claude"}, ids, "pattern-only entries are hidden")
|
||||
vlm := v.ModelsByType(types.ModelTypeVLLM)
|
||||
require.Len(t, vlm, 1)
|
||||
assert.Equal(t, "acme-pro", vlm[0].ID, "VLM picker lists chat models with image input")
|
||||
embed := v.ModelsByType(types.ModelTypeEmbedding)
|
||||
require.Len(t, embed, 1)
|
||||
assert.Equal(t, 1024, embed[0].Dimension)
|
||||
}
|
||||
|
||||
func TestApplyOverlay(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
t.Setenv("ACME_KEY", "sk-from-env")
|
||||
overlay := `{
|
||||
"providers": {
|
||||
"acme": {
|
||||
"base_url": "https://acme.internal/v1",
|
||||
"api_key": "${ACME_KEY}",
|
||||
"headers": {"X-Team": "$ACME_KEY"},
|
||||
"thinking_levels": {"xhigh": "max"},
|
||||
"models": [{"id": "acme-ultra", "reasoning": true, "context_window": 400000}],
|
||||
"model_overrides": {"acme-pro": {"context_window": 123, "compat": {"supports_temperature": true}}}
|
||||
},
|
||||
"my-vllm": {
|
||||
"name": "Lab vLLM",
|
||||
"names": {"zh-CN": "实验室 vLLM"},
|
||||
"base_url": "http://vllm.lab:8000/v1",
|
||||
"requires_auth": false,
|
||||
"compat": {"thinking_format": "chat-template-kwargs", "max_tokens_field": "max_tokens"},
|
||||
"models": [{"id": "Qwen/Qwen3-32B", "reasoning": true}]
|
||||
}
|
||||
}
|
||||
}`
|
||||
require.NoError(t, ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
acme, ok := Get("acme")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "https://acme.internal/v1", acme.GetDefaultURL(types.ModelTypeKnowledgeQA))
|
||||
assert.Equal(t, "https://api.acme.ai/rerank", acme.GetDefaultURL(types.ModelTypeRerank), "other URLs untouched")
|
||||
assert.Equal(t, "sk-from-env", acme.DefaultAPIKey)
|
||||
assert.Equal(t, "sk-from-env", acme.Headers["X-Team"])
|
||||
assert.Equal(t, "max", acme.ThinkingLevels.Value(api.ReasoningXHigh))
|
||||
assert.Equal(t, "max", acme.ThinkingLevels.Value(api.ReasoningMax), "existing levels kept")
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-ultra"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Cataloged)
|
||||
assert.Equal(t, 400000, r.Spec.ContextWindow)
|
||||
|
||||
r, err = Resolve(Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 123, r.Spec.ContextWindow)
|
||||
assert.True(t, r.OpenAICompletions.SupportsTemperature, "model_overrides compat merges over the built-in compat")
|
||||
|
||||
lab, ok := Get("my-vllm")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "实验室 vLLM", lab.LocalizedName("zh-CN"))
|
||||
assert.Equal(t, "Lab vLLM", lab.LocalizedName("en-US"))
|
||||
assert.False(t, lab.RequiresAuth)
|
||||
r, err = Resolve(Ref{Provider: "my-vllm", Model: "Qwen/Qwen3-32B"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ThinkingFormatChatTemplateKwargs, r.OpenAICompletions.ThinkingFormat)
|
||||
assert.Equal(t, "max_tokens", r.OpenAICompletions.MaxTokensField)
|
||||
assert.True(t, r.Spec.Reasoning)
|
||||
assert.Equal(t, "http://vllm.lab:8000/v1", r.BaseURL)
|
||||
|
||||
assert.Error(t, ApplyOverlay([]byte(`{"providers": {"x": {"bogus": 1}}}`), t.TempDir()), "unknown keys rejected")
|
||||
assert.Error(t, ApplyOverlay([]byte(`{"providers": {"x": {"api": "nope"}}}`), t.TempDir()))
|
||||
}
|
||||
|
||||
func TestThinkingLevelMap(t *testing.T) {
|
||||
m := api.ThinkingLevelMap{
|
||||
api.ReasoningMedium: nil,
|
||||
api.ReasoningMax: api.StringPtr("max"),
|
||||
api.ReasoningOff: api.StringPtr("none"),
|
||||
}
|
||||
assert.False(t, m.Supports(api.ReasoningMedium))
|
||||
assert.True(t, m.Supports(api.ReasoningMax))
|
||||
assert.False(t, m.Supports(api.ReasoningXHigh), "xhigh needs an explicit entry")
|
||||
assert.Equal(t, api.ReasoningHigh, m.Clamp(api.ReasoningMedium), "clamps upward first")
|
||||
assert.Equal(t, api.ReasoningMax, m.Clamp(api.ReasoningXHigh))
|
||||
assert.Equal(t, "none", m.Value(api.ReasoningOff))
|
||||
assert.Equal(t, "low", m.Value(api.ReasoningLow), "unmapped levels pass through")
|
||||
assert.Equal(t, []api.ReasoningEffort{
|
||||
api.ReasoningOff, api.ReasoningAuto, api.ReasoningMinimal,
|
||||
api.ReasoningLow, api.ReasoningHigh, api.ReasoningMax,
|
||||
}, m.SupportedLevels())
|
||||
|
||||
level, ok := api.ParseReasoningEffort("true")
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, api.ReasoningAuto, level)
|
||||
_, ok = api.ParseReasoningEffort("ultra")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
|
@ -0,0 +1,398 @@
|
|||
package catalog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
)
|
||||
|
||||
// ThinkingFormat names how an OpenAI-compatible vendor encodes the thinking
|
||||
// switch. It is the single most divergent field across vendors, which is
|
||||
// why it is an enum rather than free text.
|
||||
type ThinkingFormat string
|
||||
|
||||
const (
|
||||
// ThinkingFormatNone sends no thinking fields at all.
|
||||
ThinkingFormatNone ThinkingFormat = "none"
|
||||
// ThinkingFormatOpenAI sends only reasoning_effort (OpenAI, Azure, xAI).
|
||||
ThinkingFormatOpenAI ThinkingFormat = "openai"
|
||||
// ThinkingFormatThinkingType sends {"thinking": {"type": "enabled"|"disabled"}}
|
||||
// plus reasoning_effort when supported (DeepSeek, Zhipu, Volcengine Ark,
|
||||
// Moonshot K2.6+, MiniMax M3, LKEAP).
|
||||
ThinkingFormatThinkingType ThinkingFormat = "thinking-type"
|
||||
// ThinkingFormatEnableThinking sends enable_thinking: bool plus
|
||||
// thinking_budget (DashScope, SiliconFlow, Hunyuan).
|
||||
ThinkingFormatEnableThinking ThinkingFormat = "enable-thinking"
|
||||
// ThinkingFormatChatTemplateKwargs sends chat_template_kwargs.enable_thinking
|
||||
// (vLLM, SGLang, NIM, LiteLLM in front of them).
|
||||
ThinkingFormatChatTemplateKwargs ThinkingFormat = "chat-template-kwargs"
|
||||
// ThinkingFormatOpenRouter sends {"reasoning": {"effort"|"enabled"}}.
|
||||
ThinkingFormatOpenRouter ThinkingFormat = "openrouter"
|
||||
)
|
||||
|
||||
// OpenAICompletionsCompat is the overlay form (every field optional) of the
|
||||
// Chat Completions settings. JSON keys are the documented names used in
|
||||
// models.json and config/models.json.
|
||||
type OpenAICompletionsCompat struct {
|
||||
MaxTokensField *string `json:"max_tokens_field,omitempty"`
|
||||
ThinkingFormat *ThinkingFormat `json:"thinking_format,omitempty"`
|
||||
ThinkingEnabledValue *string `json:"thinking_enabled_value,omitempty"`
|
||||
ThinkingAlwaysSend *bool `json:"thinking_always_send,omitempty"`
|
||||
ThinkingDisableOnNonStream *bool `json:"thinking_disable_on_non_stream,omitempty"`
|
||||
ThinkingBudgetField *string `json:"thinking_budget_field,omitempty"`
|
||||
ReasoningEffortField *string `json:"reasoning_effort_field,omitempty"`
|
||||
SupportsReasoningEffort *bool `json:"supports_reasoning_effort,omitempty"`
|
||||
SupportsDeveloperRole *bool `json:"supports_developer_role,omitempty"`
|
||||
SupportsStore *bool `json:"supports_store,omitempty"`
|
||||
SupportsUsageInStreaming *bool `json:"supports_usage_in_streaming,omitempty"`
|
||||
SupportsTemperature *bool `json:"supports_temperature,omitempty"`
|
||||
FixedTemperature *float64 `json:"fixed_temperature,omitempty"`
|
||||
SupportsSeed *bool `json:"supports_seed,omitempty"`
|
||||
ToolChoiceModes []string `json:"tool_choice_modes,omitempty"`
|
||||
SupportsParallelToolCalls *bool `json:"supports_parallel_tool_calls,omitempty"`
|
||||
SupportsResponseFormat *bool `json:"supports_response_format,omitempty"`
|
||||
SupportsMultiContent *bool `json:"supports_multi_content,omitempty"`
|
||||
ReplayReasoningContent *bool `json:"replay_reasoning_content,omitempty"`
|
||||
PromptCacheKey *bool `json:"prompt_cache_key,omitempty"`
|
||||
CacheControlFormat *string `json:"cache_control_format,omitempty"`
|
||||
PromptCacheAccounting *bool `json:"prompt_cache_accounting,omitempty"`
|
||||
ToolCallExtraFields []string `json:"tool_call_extra_fields,omitempty"`
|
||||
ExtraBody map[string]any `json:"extra_body,omitempty"`
|
||||
ReasoningFields []string `json:"reasoning_fields,omitempty"`
|
||||
}
|
||||
|
||||
// OpenAICompletionsSettings is the resolved (fully defaulted) form.
|
||||
type OpenAICompletionsSettings struct {
|
||||
// MaxTokensField is "max_tokens" or "max_completion_tokens".
|
||||
MaxTokensField string
|
||||
ThinkingFormat ThinkingFormat
|
||||
// ThinkingEnabledValue is the "type" sent for thinking-type when enabled
|
||||
// ("enabled" by default; MiniMax M3 uses "adaptive").
|
||||
ThinkingEnabledValue string
|
||||
// ThinkingAlwaysSend pins the switch on every request even when the
|
||||
// caller expressed no preference (DashScope hybrid models require it).
|
||||
ThinkingAlwaysSend bool
|
||||
// ThinkingDisableOnNonStream forces the switch off for non-streaming
|
||||
// calls (Qwen3 rejects thinking without stream).
|
||||
ThinkingDisableOnNonStream bool
|
||||
// ThinkingBudgetField carries Options.ThinkingBudgetTokens ("thinking_budget").
|
||||
ThinkingBudgetField string
|
||||
// ReasoningEffortField is "reasoning_effort" unless a vendor renames it.
|
||||
ReasoningEffortField string
|
||||
SupportsReasoningEffort bool
|
||||
// SupportsDeveloperRole switches the system prompt to the developer role
|
||||
// on reasoning models.
|
||||
SupportsDeveloperRole bool
|
||||
// SupportsStore sends store:false (OpenAI keeps completions otherwise).
|
||||
SupportsStore bool
|
||||
SupportsUsageInStreaming bool
|
||||
// SupportsTemperature false drops every sampling parameter (o-series,
|
||||
// GPT-5 family, Kimi K2.5+).
|
||||
SupportsTemperature bool
|
||||
// FixedTemperature pins the value when the vendor only accepts one.
|
||||
FixedTemperature *float64
|
||||
SupportsSeed bool
|
||||
ToolChoiceModes []string
|
||||
SupportsParallelToolCalls bool
|
||||
SupportsResponseFormat bool
|
||||
// SupportsMultiContent false flattens image/text parts to plain text.
|
||||
SupportsMultiContent bool
|
||||
// ReplayReasoningContent sends reasoning_content on prior assistant turns.
|
||||
ReplayReasoningContent bool
|
||||
// PromptCacheKey sends prompt_cache_key / prompt_cache_retention and the
|
||||
// session-affinity headers.
|
||||
PromptCacheKey bool
|
||||
// CacheControlFormat "anthropic" injects cache_control breakpoints.
|
||||
CacheControlFormat string
|
||||
// PromptCacheAccounting states the vendor reports cache usage at all.
|
||||
PromptCacheAccounting bool
|
||||
// ToolCallExtraFields lists tool_call keys to round-trip opaquely
|
||||
// (Gemini-through-OpenAI "extra_content").
|
||||
ToolCallExtraFields []string
|
||||
// ExtraBody is merged into every request body (vendor knobs such as
|
||||
// enable_search, sampling defaults).
|
||||
ExtraBody map[string]any
|
||||
// ReasoningFields are the delta keys that carry thinking text, in
|
||||
// priority order.
|
||||
ReasoningFields []string
|
||||
}
|
||||
|
||||
// DefaultOpenAICompletions is the protocol baseline: plain OpenAI semantics.
|
||||
func DefaultOpenAICompletions() OpenAICompletionsSettings {
|
||||
return OpenAICompletionsSettings{
|
||||
MaxTokensField: "max_completion_tokens",
|
||||
ThinkingFormat: ThinkingFormatNone,
|
||||
ThinkingEnabledValue: "enabled",
|
||||
ReasoningEffortField: "reasoning_effort",
|
||||
SupportsUsageInStreaming: true,
|
||||
SupportsTemperature: true,
|
||||
SupportsSeed: true,
|
||||
ToolChoiceModes: []string{"none", "auto", "required", "function"},
|
||||
SupportsParallelToolCalls: true,
|
||||
SupportsResponseFormat: true,
|
||||
SupportsMultiContent: true,
|
||||
ReplayReasoningContent: true,
|
||||
ReasoningFields: []string{"reasoning_content", "reasoning", "reasoning_text"},
|
||||
}
|
||||
}
|
||||
|
||||
// AllowsToolChoice reports whether a tool_choice mode is accepted.
|
||||
func (s OpenAICompletionsSettings) AllowsToolChoice(mode string) bool {
|
||||
for _, m := range s.ToolChoiceModes {
|
||||
if m == mode {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// OpenAIResponsesCompat is the overlay for the Responses protocol.
|
||||
type OpenAIResponsesCompat struct {
|
||||
SupportsDeveloperRole *bool `json:"supports_developer_role,omitempty"`
|
||||
SupportsMaxOutputTokens *bool `json:"supports_max_output_tokens,omitempty"`
|
||||
SupportsReasoningSummary *bool `json:"supports_reasoning_summary,omitempty"`
|
||||
SupportsEncryptedReasoning *bool `json:"supports_encrypted_reasoning,omitempty"`
|
||||
SupportsStore *bool `json:"supports_store,omitempty"`
|
||||
SupportsTemperature *bool `json:"supports_temperature,omitempty"`
|
||||
PromptCacheKey *bool `json:"prompt_cache_key,omitempty"`
|
||||
SupportsLongCacheRetention *bool `json:"supports_long_cache_retention,omitempty"`
|
||||
SupportsParallelToolCalls *bool `json:"supports_parallel_tool_calls,omitempty"`
|
||||
ExtraBody map[string]any `json:"extra_body,omitempty"`
|
||||
}
|
||||
|
||||
// OpenAIResponsesSettings is the resolved Responses configuration.
|
||||
type OpenAIResponsesSettings struct {
|
||||
SupportsDeveloperRole bool
|
||||
SupportsMaxOutputTokens bool
|
||||
SupportsReasoningSummary bool
|
||||
SupportsEncryptedReasoning bool
|
||||
SupportsStore bool
|
||||
SupportsTemperature bool
|
||||
PromptCacheKey bool
|
||||
SupportsLongCacheRetention bool
|
||||
SupportsParallelToolCalls bool
|
||||
ExtraBody map[string]any
|
||||
}
|
||||
|
||||
// DefaultOpenAIResponses is the api.openai.com baseline.
|
||||
func DefaultOpenAIResponses() OpenAIResponsesSettings {
|
||||
return OpenAIResponsesSettings{
|
||||
SupportsDeveloperRole: true,
|
||||
SupportsMaxOutputTokens: true,
|
||||
SupportsReasoningSummary: true,
|
||||
SupportsEncryptedReasoning: true,
|
||||
SupportsStore: true,
|
||||
SupportsTemperature: true,
|
||||
PromptCacheKey: true,
|
||||
SupportsLongCacheRetention: true,
|
||||
SupportsParallelToolCalls: true,
|
||||
}
|
||||
}
|
||||
|
||||
// AnthropicThinkingMode selects the thinking request shape.
|
||||
type AnthropicThinkingMode string
|
||||
|
||||
const (
|
||||
// AnthropicThinkingBudget sends {"type":"enabled","budget_tokens":N}.
|
||||
AnthropicThinkingBudget AnthropicThinkingMode = "budget"
|
||||
// AnthropicThinkingAdaptive sends {"type":"adaptive"} and steers the
|
||||
// intensity through output_config.effort.
|
||||
AnthropicThinkingAdaptive AnthropicThinkingMode = "adaptive"
|
||||
)
|
||||
|
||||
// AnthropicMessagesCompat is the overlay for the Messages protocol.
|
||||
type AnthropicMessagesCompat struct {
|
||||
ThinkingMode *AnthropicThinkingMode `json:"thinking_mode,omitempty"`
|
||||
SupportsEffort *bool `json:"supports_effort,omitempty"`
|
||||
ThinkingBudgets map[api.ReasoningEffort]int `json:"thinking_budgets,omitempty"`
|
||||
DefaultMaxTokens *int `json:"default_max_tokens,omitempty"`
|
||||
SupportsTemperature *bool `json:"supports_temperature,omitempty"`
|
||||
TemperatureWithThinking *bool `json:"temperature_with_thinking,omitempty"`
|
||||
SupportsTopP *bool `json:"supports_top_p,omitempty"`
|
||||
SupportsCacheControl *bool `json:"supports_cache_control,omitempty"`
|
||||
SupportsCacheControlOnTool *bool `json:"supports_cache_control_on_tools,omitempty"`
|
||||
LongCacheTTL *string `json:"long_cache_ttl,omitempty"`
|
||||
Version *string `json:"version,omitempty"`
|
||||
BetaHeaders []string `json:"beta_headers,omitempty"`
|
||||
InterleavedThinkingBeta *string `json:"interleaved_thinking_beta,omitempty"`
|
||||
PromptCacheAccounting *bool `json:"prompt_cache_accounting,omitempty"`
|
||||
ExtraBody map[string]any `json:"extra_body,omitempty"`
|
||||
}
|
||||
|
||||
// AnthropicMessagesSettings is the resolved Messages configuration.
|
||||
type AnthropicMessagesSettings struct {
|
||||
ThinkingMode AnthropicThinkingMode
|
||||
SupportsEffort bool
|
||||
// ThinkingBudgets maps graded levels to budget_tokens for budget mode.
|
||||
ThinkingBudgets map[api.ReasoningEffort]int
|
||||
// DefaultMaxTokens is used when the caller set no budget (max_tokens is
|
||||
// mandatory on this protocol).
|
||||
DefaultMaxTokens int
|
||||
SupportsTemperature bool
|
||||
TemperatureWithThinking bool
|
||||
SupportsTopP bool
|
||||
SupportsCacheControl bool
|
||||
SupportsCacheControlOnTool bool
|
||||
LongCacheTTL string
|
||||
Version string
|
||||
BetaHeaders []string
|
||||
// InterleavedThinkingBeta is added to anthropic-beta when thinking and
|
||||
// tools are both active (budget mode only). Empty disables it.
|
||||
InterleavedThinkingBeta string
|
||||
PromptCacheAccounting bool
|
||||
ExtraBody map[string]any
|
||||
}
|
||||
|
||||
// DefaultAnthropicMessages is the api.anthropic.com baseline for the
|
||||
// budget-thinking generation of models.
|
||||
func DefaultAnthropicMessages() AnthropicMessagesSettings {
|
||||
return AnthropicMessagesSettings{
|
||||
ThinkingMode: AnthropicThinkingBudget,
|
||||
ThinkingBudgets: map[api.ReasoningEffort]int{
|
||||
api.ReasoningMinimal: 1024,
|
||||
api.ReasoningLow: 2048,
|
||||
api.ReasoningMedium: 8192,
|
||||
api.ReasoningHigh: 16384,
|
||||
api.ReasoningXHigh: 32768,
|
||||
api.ReasoningMax: 63999,
|
||||
},
|
||||
DefaultMaxTokens: 4096,
|
||||
SupportsTemperature: true,
|
||||
TemperatureWithThinking: false,
|
||||
SupportsTopP: true,
|
||||
SupportsCacheControl: true,
|
||||
SupportsCacheControlOnTool: true,
|
||||
LongCacheTTL: "1h",
|
||||
Version: "2023-06-01",
|
||||
InterleavedThinkingBeta: "interleaved-thinking-2025-05-14",
|
||||
PromptCacheAccounting: true,
|
||||
}
|
||||
}
|
||||
|
||||
// GoogleThinkingMode selects the thinkingConfig shape.
|
||||
type GoogleThinkingMode string
|
||||
|
||||
const (
|
||||
// GoogleThinkingBudget sends thinkingConfig.thinkingBudget (Gemini 2.5).
|
||||
GoogleThinkingBudget GoogleThinkingMode = "budget"
|
||||
// GoogleThinkingLevel sends thinkingConfig.thinkingLevel (Gemini 3+).
|
||||
GoogleThinkingLevel GoogleThinkingMode = "level"
|
||||
// GoogleThinkingNone sends no thinkingConfig.
|
||||
GoogleThinkingNone GoogleThinkingMode = "none"
|
||||
)
|
||||
|
||||
// GoogleGenerativeAICompat is the overlay for the Gemini protocol.
|
||||
type GoogleGenerativeAICompat struct {
|
||||
ThinkingMode *GoogleThinkingMode `json:"thinking_mode,omitempty"`
|
||||
ThinkingBudgets map[api.ReasoningEffort]int `json:"thinking_budgets,omitempty"`
|
||||
IncludeThoughts *bool `json:"include_thoughts,omitempty"`
|
||||
SupportsSeed *bool `json:"supports_seed,omitempty"`
|
||||
SupportsPenalty *bool `json:"supports_penalty,omitempty"`
|
||||
ExtraGeneration map[string]any `json:"extra_generation_config,omitempty"`
|
||||
PromptCacheAcct *bool `json:"prompt_cache_accounting,omitempty"`
|
||||
APIVersionPrefix *string `json:"api_version_prefix,omitempty"`
|
||||
}
|
||||
|
||||
// GoogleGenerativeAISettings is the resolved Gemini configuration.
|
||||
type GoogleGenerativeAISettings struct {
|
||||
ThinkingMode GoogleThinkingMode
|
||||
ThinkingBudgets map[api.ReasoningEffort]int
|
||||
IncludeThoughts bool
|
||||
SupportsSeed bool
|
||||
SupportsPenalty bool
|
||||
ExtraGeneration map[string]any
|
||||
PromptCacheAcct bool
|
||||
// APIVersionPrefix is appended to a bare host base URL ("/v1beta").
|
||||
APIVersionPrefix string
|
||||
}
|
||||
|
||||
// DefaultGoogleGenerativeAI is the generativelanguage.googleapis.com baseline.
|
||||
func DefaultGoogleGenerativeAI() GoogleGenerativeAISettings {
|
||||
return GoogleGenerativeAISettings{
|
||||
ThinkingMode: GoogleThinkingBudget,
|
||||
ThinkingBudgets: map[api.ReasoningEffort]int{
|
||||
api.ReasoningMinimal: 128,
|
||||
api.ReasoningLow: 2048,
|
||||
api.ReasoningMedium: 8192,
|
||||
api.ReasoningHigh: 24576,
|
||||
api.ReasoningXHigh: 32768,
|
||||
api.ReasoningMax: 32768,
|
||||
},
|
||||
IncludeThoughts: true,
|
||||
SupportsSeed: true,
|
||||
SupportsPenalty: true,
|
||||
PromptCacheAcct: true,
|
||||
APIVersionPrefix: "/v1beta",
|
||||
}
|
||||
}
|
||||
|
||||
// VendorCompat carries a vendor's defaults for every protocol it may speak.
|
||||
type VendorCompat struct {
|
||||
OpenAICompletions OpenAICompletionsCompat `json:"openai_completions,omitempty"`
|
||||
OpenAIResponses OpenAIResponsesCompat `json:"openai_responses,omitempty"`
|
||||
AnthropicMessages AnthropicMessagesCompat `json:"anthropic_messages,omitempty"`
|
||||
GoogleGenerativeAI GoogleGenerativeAICompat `json:"google_generative_ai,omitempty"`
|
||||
}
|
||||
|
||||
// apply writes the set fields of an overlay struct onto a settings struct
|
||||
// with matching field names, dereferencing pointers. Slices and maps
|
||||
// replace the default wholesale (no element merge) except map[string]any
|
||||
// ExtraBody-style fields, which merge key by key.
|
||||
func apply(settings any, compat any) {
|
||||
sv := reflect.ValueOf(settings).Elem()
|
||||
cv := reflect.ValueOf(compat).Elem()
|
||||
ct := cv.Type()
|
||||
for i := 0; i < cv.NumField(); i++ {
|
||||
field := ct.Field(i)
|
||||
if !field.IsExported() {
|
||||
continue
|
||||
}
|
||||
target := sv.FieldByName(field.Name)
|
||||
if !target.IsValid() {
|
||||
panic(fmt.Sprintf("catalog: overlay field %s.%s has no settings counterpart", ct.Name(), field.Name))
|
||||
}
|
||||
f := cv.Field(i)
|
||||
switch f.Kind() {
|
||||
case reflect.Pointer:
|
||||
if f.IsNil() {
|
||||
continue
|
||||
}
|
||||
if target.Kind() == reflect.Pointer {
|
||||
target.Set(f)
|
||||
} else {
|
||||
target.Set(f.Elem())
|
||||
}
|
||||
case reflect.Slice:
|
||||
if f.Len() > 0 {
|
||||
target.Set(f)
|
||||
}
|
||||
case reflect.Map:
|
||||
if f.Len() == 0 {
|
||||
continue
|
||||
}
|
||||
if target.IsNil() {
|
||||
target.Set(reflect.MakeMap(target.Type()))
|
||||
}
|
||||
iter := f.MapRange()
|
||||
for iter.Next() {
|
||||
target.SetMapIndex(iter.Key(), iter.Value())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// decodeCompat unmarshals a flat compat object into the overlay type for an
|
||||
// API. Unknown keys are rejected so typos in models.json surface early.
|
||||
func decodeCompat(raw json.RawMessage, into any) error {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
dec := json.NewDecoder(bytesReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(into); err != nil {
|
||||
return fmt.Errorf("decode compat: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,413 @@
|
|||
package catalog_test
|
||||
|
||||
// Backward-compatibility guard for model rows written before the vendor
|
||||
// catalog existed (internal/models/provider). Every shape in this file is one
|
||||
// that a production `models` table can already contain, so a failure here
|
||||
// means an existing deployment breaks on upgrade without a migration.
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/models/catalog"
|
||||
_ "github.com/Tencent/WeKnora/internal/models/vendors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// legacyProviderIDs is the complete set of parameters.provider values the
|
||||
// pre-catalog code could write: provider.AllProviders() plus weknoracloud,
|
||||
// as of internal/models/provider/provider.go before the refactor.
|
||||
var legacyProviderIDs = []string{
|
||||
"generic", "weknoracloud", "aliyun", "zhipu", "volcengine", "hunyuan",
|
||||
"siliconflow", "deepseek", "minimax", "moonshot", "modelscope", "qianfan",
|
||||
"qiniu", "openai", "anthropic", "gemini", "openrouter", "litellm",
|
||||
"requesty", "jina", "mimo", "longcat", "lkeap", "gpustack", "nvidia",
|
||||
"novita", "azure_openai",
|
||||
}
|
||||
|
||||
// TestLegacyProviderIDsStillRegistered asserts that no provider id an old row
|
||||
// may carry has disappeared from the catalog. A missing id would silently
|
||||
// degrade that row to the generic OpenAI baseline (wrong auth, wrong URL,
|
||||
// wrong thinking encoding).
|
||||
func TestLegacyProviderIDsStillRegistered(t *testing.T) {
|
||||
for _, id := range legacyProviderIDs {
|
||||
if _, ok := catalog.Get(id); !ok {
|
||||
t.Errorf("provider id %q was writable by the old code but has no vendor now", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// legacyRow is one realistic pre-refactor `models` row.
|
||||
type legacyRow struct {
|
||||
name string
|
||||
model string
|
||||
typ types.ModelType
|
||||
params types.ModelParameters
|
||||
}
|
||||
|
||||
// legacyRows covers the shapes the old write paths produced: the model editor
|
||||
// (provider + base_url + api_key, no extra_config at all), the initialization
|
||||
// wizard (thinking_control / api_version / remote_model_name), YAML builtin
|
||||
// models, and rows hand-written against an older release.
|
||||
func legacyRows() []legacyRow {
|
||||
rows := []legacyRow{
|
||||
{
|
||||
name: "editor row, catalogued model, no extra_config",
|
||||
model: "deepseek-chat", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "deepseek", BaseURL: "https://api.deepseek.com/v1", APIKey: "sk-x"},
|
||||
},
|
||||
{
|
||||
name: "editor row, model the vendor has since retired",
|
||||
model: "gpt-3.5-turbo-0301", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "openai", BaseURL: "https://api.openai.com/v1", APIKey: "sk-x"},
|
||||
},
|
||||
{
|
||||
name: "self-hosted fine-tune behind a generic endpoint",
|
||||
model: "acme-corp/llama-3.1-70b-finetune-v7", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "generic", BaseURL: "http://vllm.internal:8000/v1"},
|
||||
},
|
||||
{
|
||||
name: "row written before parameters.provider existed",
|
||||
model: "qwen-plus", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"},
|
||||
},
|
||||
{
|
||||
name: "row with neither provider nor base_url",
|
||||
model: "some-model", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{},
|
||||
},
|
||||
{
|
||||
name: "provider id a hand-edited row invented",
|
||||
model: "grok-4", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "xai", BaseURL: "https://api.x.ai/v1"},
|
||||
},
|
||||
{
|
||||
name: "VLM row", model: "qwen-vl-max", typ: types.ModelTypeVLLM,
|
||||
params: types.ModelParameters{
|
||||
Provider: "aliyun", BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
InterfaceType: "openai", SupportsVision: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "local Ollama VLM row (interface_type ollama)", model: "llava:13b", typ: types.ModelTypeVLLM,
|
||||
params: types.ModelParameters{
|
||||
InterfaceType: "ollama", ParameterSize: "13B", BaseURL: "http://localhost:11434",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "WeKnoraCloud row with app credentials", model: "weknora-chat", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "weknoracloud", BaseURL: "https://weknora.weixin.qq.com",
|
||||
AppID: "app", AppSecret: "secret",
|
||||
ExtraConfig: map[string]string{"remote_model_name": "hunyuan-turbos"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Azure row from the initialization wizard", model: "gpt-4o-deployment",
|
||||
typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "azure_openai", BaseURL: "https://my-resource.openai.azure.com",
|
||||
ExtraConfig: map[string]string{"api_version": "2024-10-21"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Azure row created from the model editor (no api_version)", model: "gpt-4o-deployment",
|
||||
typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "azure_openai", BaseURL: "https://my-resource.openai.azure.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "every legacy extra_config key at once, plus an unknown one",
|
||||
model: "custom-model", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "generic", BaseURL: "http://vllm.internal:8000/v1",
|
||||
ExtraConfig: map[string]string{
|
||||
"thinking_control": "chat_template_kwargs",
|
||||
"remote_model_name": "Qwen/Qwen3-32B",
|
||||
"api_version": "2024-10-21",
|
||||
"secret_key": "sk",
|
||||
"region": "ap-guangzhou",
|
||||
"instruction": "rank these",
|
||||
"truncate_prompt_tokens": "4096",
|
||||
"deployment": "prod",
|
||||
"freshness": "week",
|
||||
"a_key_no_release_ever_wrote": "1",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "embedding row with dimension override", model: "text-embedding-v4", typ: types.ModelTypeEmbedding,
|
||||
params: types.ModelParameters{
|
||||
Provider: "aliyun", BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
EmbeddingParameters: types.EmbeddingParameters{
|
||||
Dimension: 1024, TruncatePromptTokens: 2048, SupportsDimensionOverride: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "LKEAP signed rerank row", model: "lkeap-rerank", typ: types.ModelTypeRerank,
|
||||
params: types.ModelParameters{
|
||||
Provider: "lkeap", BaseURL: "https://lkeap.tencentcloudapi.com",
|
||||
ExtraConfig: map[string]string{"secret_key": "sk", "region": "ap-guangzhou"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "custom headers row", model: "gateway-model", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "generic", BaseURL: "https://gateway.corp.example.com/v1",
|
||||
CustomHeaders: map[string]string{"X-Corp-Route": "llm"},
|
||||
ContextWindow: 128000, MaxOutputTokens: 8192, MaxConcurrency: 4,
|
||||
},
|
||||
},
|
||||
}
|
||||
// Every legacy provider id, carrying a model name no models.json knows.
|
||||
// This is the "custom fine-tune / retired model / self-hosted name" case
|
||||
// for each vendor at once.
|
||||
for _, id := range legacyProviderIDs {
|
||||
rows = append(rows, legacyRow{
|
||||
name: "uncatalogued model on provider " + id, model: "a-model-no-catalog-knows",
|
||||
typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: id},
|
||||
})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// TestLegacyRowsValidateAndResolve is the core guarantee: opening an existing
|
||||
// model in the UI and saving it (PUT /models/{id} runs catalog.ValidateRow)
|
||||
// must not 400, and the chat path must still resolve the row.
|
||||
func TestLegacyRowsValidateAndResolve(t *testing.T) {
|
||||
for _, row := range legacyRows() {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
params := row.params
|
||||
if err := catalog.ValidateRow(row.model, row.typ, ¶ms); err != nil {
|
||||
t.Fatalf("ValidateRow rejected a row the old code accepted: %v", err)
|
||||
}
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: params.Provider, Model: row.model, BaseURL: params.BaseURL,
|
||||
ModelType: row.typ, Extra: params.ExtraConfig, Override: params.Spec,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve failed: %v", err)
|
||||
}
|
||||
if resolved.Vendor == nil {
|
||||
t.Fatal("resolved with a nil vendor")
|
||||
}
|
||||
if !resolved.API.Known() {
|
||||
t.Fatalf("resolved to an unknown protocol %q", resolved.API)
|
||||
}
|
||||
if resolved.RemoteModel == "" && row.model != "" {
|
||||
t.Fatal("resolved to an empty remote model id")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestEveryCataloguedModelResolves walks the whole catalog so a row naming any
|
||||
// shipped model id — which is what the old model picker wrote — is known to
|
||||
// resolve.
|
||||
func TestEveryCataloguedModelResolves(t *testing.T) {
|
||||
for _, v := range catalog.List() {
|
||||
for _, m := range v.Models {
|
||||
if m.ID == "" {
|
||||
continue
|
||||
}
|
||||
modelType := m.Type
|
||||
if modelType == "" {
|
||||
modelType = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
if err := catalog.ValidateRow(m.ID, modelType, &types.ModelParameters{Provider: v.ID}); err != nil {
|
||||
t.Errorf("%s/%s: ValidateRow: %v", v.ID, m.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// legacyThinkingControl is the old chat.parseThinkingOverride mapping, from
|
||||
// internal/models/chat/thinking.go before the refactor. The four values are
|
||||
// the only ones the old frontend wrote (frontend/src/utils/thinkingControl.ts),
|
||||
// but an unrecognized non-empty value historically fell back to
|
||||
// chat_template_kwargs and must keep doing so.
|
||||
var legacyThinkingControl = map[string]catalog.ThinkingFormat{
|
||||
"none": catalog.ThinkingFormatNone,
|
||||
"enable_thinking": catalog.ThinkingFormatEnableThinking,
|
||||
"thinking_type": catalog.ThinkingFormatThinkingType,
|
||||
"chat_template_kwargs": catalog.ThinkingFormatChatTemplateKwargs,
|
||||
"enabled": catalog.ThinkingFormatChatTemplateKwargs,
|
||||
"ENABLE_THINKING": catalog.ThinkingFormatEnableThinking,
|
||||
" thinking_type ": catalog.ThinkingFormatThinkingType,
|
||||
}
|
||||
|
||||
// TestLegacyThinkingControlMapping pins extra_config.thinking_control to the
|
||||
// old semantics for every value a stored row can hold, including on a
|
||||
// catalogued non-reasoning model where the new silencing pass would otherwise
|
||||
// drop the thinking fields.
|
||||
func TestLegacyThinkingControlMapping(t *testing.T) {
|
||||
for value, want := range legacyThinkingControl {
|
||||
t.Run(value, func(t *testing.T) {
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: "generic", Model: "Qwen/Qwen3-32B",
|
||||
BaseURL: "http://vllm.internal:8000/v1", ModelType: types.ModelTypeKnowledgeQA,
|
||||
Extra: map[string]string{"thinking_control": value},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if got := resolved.OpenAICompletions.ThinkingFormat; got != want {
|
||||
t.Fatalf("thinking_control=%q resolved to %q, old code selected %q", value, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyThinkingControlSurvivesCatalogSilencing guards the interaction
|
||||
// between a stored thinking_control and silenceThinkingForNonReasoningModel:
|
||||
// an operator who explicitly picked an encoding must keep it even when the
|
||||
// catalog marks the model non-reasoning.
|
||||
func TestLegacyThinkingControlSurvivesCatalogSilencing(t *testing.T) {
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: "openai", Model: "gpt-4o", ModelType: types.ModelTypeKnowledgeQA,
|
||||
Extra: map[string]string{"thinking_control": "chat_template_kwargs"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.OpenAICompletions.ThinkingFormat != catalog.ThinkingFormatChatTemplateKwargs {
|
||||
t.Fatalf("explicit thinking_control was overridden by the catalog: %q",
|
||||
resolved.OpenAICompletions.ThinkingFormat)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUncataloguedModelKeepsThinkingSwitch documents the deliberate asymmetry
|
||||
// in silenceThinkingForNonReasoningModel: a model nobody catalogued (the
|
||||
// self-hosted case) keeps its thinking switch, which is what old rows relied
|
||||
// on, while a catalogued non-reasoning model loses it.
|
||||
func TestUncataloguedModelKeepsThinkingSwitch(t *testing.T) {
|
||||
unknown, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: "generic", Model: "acme/llama-3.1-70b-finetune",
|
||||
BaseURL: "http://vllm.internal:8000/v1", ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if unknown.Cataloged {
|
||||
t.Fatal("expected the fine-tune to be uncatalogued")
|
||||
}
|
||||
if unknown.OpenAICompletions.ThinkingFormat != catalog.ThinkingFormatChatTemplateKwargs {
|
||||
t.Fatalf("uncatalogued model lost its thinking switch: %q",
|
||||
unknown.OpenAICompletions.ThinkingFormat)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyRemoteModelNameHonoured pins extra_config.remote_model_name, which
|
||||
// the old chat and embedding paths both read.
|
||||
func TestLegacyRemoteModelNameHonoured(t *testing.T) {
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: "generic", Model: "display-name", BaseURL: "http://vllm.internal:8000/v1",
|
||||
ModelType: types.ModelTypeKnowledgeQA,
|
||||
Extra: map[string]string{"remote_model_name": "Qwen/Qwen3-32B"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.RemoteModel != "Qwen/Qwen3-32B" {
|
||||
t.Fatalf("remote_model_name ignored: wire model is %q", resolved.RemoteModel)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnknownProviderFallsBackToGeneric checks the reverse direction: a row
|
||||
// naming a provider this build does not ship degrades to the generic
|
||||
// OpenAI-compatible baseline instead of failing the write.
|
||||
func TestUnknownProviderFallsBackToGeneric(t *testing.T) {
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: "a-vendor-from-the-future", Model: "m",
|
||||
BaseURL: "https://example.com/v1", ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.Vendor.ID != catalog.GenericID {
|
||||
t.Fatalf("unknown provider resolved to %q, want %q", resolved.Vendor.ID, catalog.GenericID)
|
||||
}
|
||||
if resolved.API != api.APIOpenAICompletions {
|
||||
t.Fatalf("unknown provider resolved to protocol %q", resolved.API)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyStoredBaseURLSelectsSameProtocol pins the protocol an existing
|
||||
// row resolves to. Old rows always store an explicit base_url (the model
|
||||
// editor pre-filled the provider default), so the stored URL — not the new
|
||||
// vendor default — decides the wire protocol on upgrade. The Gemini case and
|
||||
// the first-party OpenAI move to Responses are covered in
|
||||
// internal/models/parity; what is asserted here is the relay case, where the
|
||||
// same provider id must NOT follow OpenAI onto /responses.
|
||||
func TestLegacyStoredBaseURLSelectsSameProtocol(t *testing.T) {
|
||||
cases := []struct {
|
||||
provider, baseURL string
|
||||
want api.API
|
||||
why string
|
||||
}{
|
||||
{
|
||||
provider: "openai", baseURL: "https://llm-relay.corp.example.com/v1",
|
||||
want: api.APIOpenAICompletions,
|
||||
why: "a relay that only speaks Chat Completions must stay on it",
|
||||
},
|
||||
{
|
||||
provider: "openai", baseURL: "https://litellm.corp.example.com/v1",
|
||||
want: api.APIOpenAICompletions,
|
||||
why: "an OpenAI row pointed at a LiteLLM proxy keeps Chat Completions",
|
||||
},
|
||||
{
|
||||
provider: "anthropic", baseURL: "https://api.anthropic.com/v1",
|
||||
want: api.APIAnthropicMessages,
|
||||
why: "the old code already dispatched anthropic to the Messages protocol",
|
||||
},
|
||||
{
|
||||
provider: "generic", baseURL: "http://vllm.internal:8000/v1",
|
||||
want: api.APIOpenAICompletions, why: "unchanged",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.provider+" "+tc.baseURL, func(t *testing.T) {
|
||||
resolved, err := catalog.Resolve(catalog.Ref{
|
||||
Provider: tc.provider, Model: "some-model", BaseURL: tc.baseURL,
|
||||
ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.API != tc.want {
|
||||
t.Fatalf("protocol %q, want %q (%s)", resolved.API, tc.want, tc.why)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyFreeFormAPIExtraKeyIsRejected documents the one stored shape this
|
||||
// refactor does break, so the trade-off stays visible.
|
||||
//
|
||||
// extra_config has always been a free-form map[string]string: the old backend
|
||||
// read only thinking_control, remote_model_name, api_version, secret_key,
|
||||
// region, instruction and truncate_prompt_tokens from it and ignored every
|
||||
// other key. The catalog gave the key "api" a meaning — it forces the wire
|
||||
// protocol — and ValidateRow now rejects a value that is not one of the five
|
||||
// protocol names. A row that an operator hand-populated with, say,
|
||||
// {"api": "v1"} therefore fails PUT /models/{id} with 400 and fails every
|
||||
// chat call, even though nothing about that row changed.
|
||||
//
|
||||
// Nothing in WeKnora ever wrote this key, so only hand-built rows and
|
||||
// hand-written builtin_models.yaml entries are affected. If that is judged too
|
||||
// sharp, the fix is to ignore an unparseable extra_config.api in Resolve and
|
||||
// keep the strict check for Spec.API, which no old row can carry.
|
||||
func TestLegacyFreeFormAPIExtraKeyIsRejected(t *testing.T) {
|
||||
err := catalog.ValidateRow("gpt-4o", types.ModelTypeKnowledgeQA, &types.ModelParameters{
|
||||
Provider: "openai", BaseURL: "https://api.openai.com/v1",
|
||||
ExtraConfig: map[string]string{"api": "v1"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Skip("extra_config.api is now tolerant of legacy free-form values; " +
|
||||
"delete this test and the release note that goes with it")
|
||||
}
|
||||
t.Logf("documented break: %v", err)
|
||||
}
|
||||
|
|
@ -0,0 +1,549 @@
|
|||
package catalog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// OverlayFile is the schema of config/models.json. It mirrors pi's
|
||||
// ~/.pi/agent/models.json: a "providers" object keyed by provider id where
|
||||
// each entry either patches a built-in vendor or declares a new one.
|
||||
type OverlayFile struct {
|
||||
Providers map[string]OverlayProvider `json:"providers"`
|
||||
}
|
||||
|
||||
// OverlayProvider patches or declares one vendor.
|
||||
type OverlayProvider struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Names map[string]string `json:"names,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Descriptions map[string]string `json:"descriptions,omitempty"`
|
||||
Website string `json:"website,omitempty"`
|
||||
// API is the default chat protocol for new vendors (and overrides it
|
||||
// for built-in ones).
|
||||
API api.API `json:"api,omitempty"`
|
||||
// BaseURL sets the chat base URL; BaseURLs sets per-type URLs keyed by
|
||||
// chat | embedding | rerank | vlm | asr.
|
||||
BaseURL string `json:"base_url,omitempty"`
|
||||
BaseURLs map[string]string `json:"base_urls,omitempty"`
|
||||
// APIKey is the deployment-level key used when a model row stores none.
|
||||
// Supports ${ENV} / $ENV interpolation.
|
||||
APIKey string `json:"api_key,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Auth AuthStyle `json:"auth,omitempty"`
|
||||
RequiresAuth *bool `json:"requires_auth,omitempty"`
|
||||
ModelTypes []string `json:"model_types,omitempty"`
|
||||
URLPatterns []string `json:"url_patterns,omitempty"`
|
||||
// Icon is a path to an SVG file (relative to the overlay file) or an
|
||||
// inline "<svg ...>" string.
|
||||
Icon string `json:"icon,omitempty"`
|
||||
// Compat is the flat protocol overlay applied at vendor level for API.
|
||||
Compat json.RawMessage `json:"compat,omitempty"`
|
||||
// ThinkingLevels patches the vendor level map.
|
||||
ThinkingLevels map[string]*string `json:"thinking_levels,omitempty"`
|
||||
// Models are upserted by id into the vendor catalog. Entries stay raw so
|
||||
// an upsert against an existing id can patch only the keys the operator
|
||||
// actually wrote (see applyOverlayProvider).
|
||||
Models []json.RawMessage `json:"models,omitempty"`
|
||||
// ModelOverrides patch existing entries by id without restating them.
|
||||
ModelOverrides map[string]ModelSpecPatch `json:"model_overrides,omitempty"`
|
||||
}
|
||||
|
||||
// ModelSpecPatch is a partial ModelSpec.
|
||||
type ModelSpecPatch struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
API api.API `json:"api,omitempty"`
|
||||
Reasoning *bool `json:"reasoning,omitempty"`
|
||||
Input []string `json:"input,omitempty"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
Cost *ModelCost `json:"cost,omitempty"`
|
||||
ThinkingLevels api.ThinkingLevelMap `json:"thinking_levels,omitempty"`
|
||||
Compat json.RawMessage `json:"compat,omitempty"`
|
||||
Aliases []string `json:"aliases,omitempty"`
|
||||
Deprecated *bool `json:"deprecated,omitempty"`
|
||||
}
|
||||
|
||||
var envPattern = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)`)
|
||||
|
||||
// interpolateEnv expands ${NAME} and $NAME. Unset variables expand to the
|
||||
// empty string so a missing key fails loudly upstream rather than sending
|
||||
// the literal placeholder.
|
||||
func interpolateEnv(s string) string {
|
||||
return envPattern.ReplaceAllStringFunc(s, func(m string) string {
|
||||
name := strings.Trim(strings.TrimPrefix(m, "$"), "{}")
|
||||
return os.Getenv(name)
|
||||
})
|
||||
}
|
||||
|
||||
var frontendTypes = map[string]types.ModelType{
|
||||
"chat": types.ModelTypeKnowledgeQA,
|
||||
"embedding": types.ModelTypeEmbedding,
|
||||
"rerank": types.ModelTypeRerank,
|
||||
"vlm": types.ModelTypeVLLM,
|
||||
"vllm": types.ModelTypeVLLM,
|
||||
"asr": types.ModelTypeASR,
|
||||
}
|
||||
|
||||
// ParseModelType accepts both frontend ("chat") and backend ("KnowledgeQA")
|
||||
// spellings.
|
||||
func ParseModelType(s string) (types.ModelType, bool) {
|
||||
if t, ok := frontendTypes[strings.ToLower(strings.TrimSpace(s))]; ok {
|
||||
return t, true
|
||||
}
|
||||
switch types.ModelType(s) {
|
||||
case types.ModelTypeKnowledgeQA, types.ModelTypeEmbedding, types.ModelTypeRerank,
|
||||
types.ModelTypeVLLM, types.ModelTypeASR:
|
||||
return types.ModelType(s), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// LoadOverlay reads config/models.json (or the path in MODELS_CONFIG) and
|
||||
// applies it to the registry. A missing file is not an error.
|
||||
func LoadOverlay(configDir string) error {
|
||||
path := os.Getenv("MODELS_CONFIG")
|
||||
if path == "" {
|
||||
path = filepath.Join(configDir, "models.json")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
return ApplyOverlay(data, filepath.Dir(path))
|
||||
}
|
||||
|
||||
// ApplyOverlay applies overlay JSON to the registry. baseDir resolves
|
||||
// relative icon paths.
|
||||
func ApplyOverlay(data []byte, baseDir string) error {
|
||||
var file OverlayFile
|
||||
dec := json.NewDecoder(bytesReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&file); err != nil {
|
||||
return fmt.Errorf("parse models overlay: %w", err)
|
||||
}
|
||||
for id, p := range file.Providers {
|
||||
id = strings.ToLower(strings.TrimSpace(id))
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
vendor, exists := Get(id)
|
||||
if !exists {
|
||||
vendor = &Vendor{
|
||||
ID: id,
|
||||
Name: id,
|
||||
API: api.APIOpenAICompletions,
|
||||
DefaultBaseURLs: map[types.ModelType]string{},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
RequiresAuth: true,
|
||||
Auth: AuthBearer,
|
||||
Order: 1000,
|
||||
}
|
||||
} else {
|
||||
copied := *vendor
|
||||
vendor = &copied
|
||||
vendor.Models = append([]ModelSpec(nil), vendor.Models...)
|
||||
urls := make(map[types.ModelType]string, len(vendor.DefaultBaseURLs))
|
||||
for k, v := range vendor.DefaultBaseURLs {
|
||||
urls[k] = v
|
||||
}
|
||||
vendor.DefaultBaseURLs = urls
|
||||
}
|
||||
if err := applyOverlayProvider(vendor, p, baseDir); err != nil {
|
||||
return fmt.Errorf("provider %s: %w", id, err)
|
||||
}
|
||||
Register(vendor)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyOverlayProvider(v *Vendor, p OverlayProvider, baseDir string) error {
|
||||
if p.Name != "" {
|
||||
v.Name = p.Name
|
||||
}
|
||||
if len(p.Names) > 0 {
|
||||
v.Names = p.Names
|
||||
}
|
||||
if p.Description != "" {
|
||||
v.Description = p.Description
|
||||
}
|
||||
if len(p.Descriptions) > 0 {
|
||||
v.Descriptions = p.Descriptions
|
||||
}
|
||||
if p.Website != "" {
|
||||
v.Website = p.Website
|
||||
}
|
||||
if p.API != "" {
|
||||
if !p.API.Known() {
|
||||
return fmt.Errorf("unknown api %q", p.API)
|
||||
}
|
||||
v.API = p.API
|
||||
}
|
||||
if p.BaseURL != "" {
|
||||
v.DefaultBaseURLs[types.ModelTypeKnowledgeQA] = interpolateEnv(p.BaseURL)
|
||||
}
|
||||
for k, u := range p.BaseURLs {
|
||||
t, ok := ParseModelType(k)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown model type %q in base_urls", k)
|
||||
}
|
||||
v.DefaultBaseURLs[t] = interpolateEnv(u)
|
||||
}
|
||||
if p.APIKey != "" {
|
||||
v.DefaultAPIKey = interpolateEnv(p.APIKey)
|
||||
}
|
||||
if len(p.Headers) > 0 {
|
||||
headers := make(map[string]string, len(p.Headers))
|
||||
for k, val := range p.Headers {
|
||||
headers[k] = interpolateEnv(val)
|
||||
}
|
||||
v.Headers = headers
|
||||
}
|
||||
if p.Auth != "" {
|
||||
v.Auth = p.Auth
|
||||
}
|
||||
if p.RequiresAuth != nil {
|
||||
v.RequiresAuth = *p.RequiresAuth
|
||||
}
|
||||
if len(p.ModelTypes) > 0 {
|
||||
v.ModelTypes = v.ModelTypes[:0]
|
||||
for _, s := range p.ModelTypes {
|
||||
t, ok := ParseModelType(s)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown model type %q", s)
|
||||
}
|
||||
v.ModelTypes = append(v.ModelTypes, t)
|
||||
}
|
||||
}
|
||||
if len(p.URLPatterns) > 0 {
|
||||
v.URLPatterns = p.URLPatterns
|
||||
}
|
||||
if p.Icon != "" {
|
||||
icon, err := loadOverlayIcon(baseDir, p.Icon)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.Icon = icon
|
||||
}
|
||||
if len(p.Compat) > 0 {
|
||||
var err error
|
||||
switch v.API {
|
||||
case api.APIOpenAICompletions:
|
||||
err = decodeCompat(p.Compat, &v.Compat.OpenAICompletions)
|
||||
case api.APIOpenAIResponses:
|
||||
err = decodeCompat(p.Compat, &v.Compat.OpenAIResponses)
|
||||
case api.APIAnthropicMessages:
|
||||
err = decodeCompat(p.Compat, &v.Compat.AnthropicMessages)
|
||||
case api.APIGoogleGenerativeAI:
|
||||
err = decodeCompat(p.Compat, &v.Compat.GoogleGenerativeAI)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(p.ThinkingLevels) > 0 {
|
||||
levels := api.ThinkingLevelMap{}
|
||||
for k, val := range v.ThinkingLevels {
|
||||
levels[k] = val
|
||||
}
|
||||
for k, val := range p.ThinkingLevels {
|
||||
levels[api.ReasoningEffort(k)] = val
|
||||
}
|
||||
v.ThinkingLevels = levels
|
||||
}
|
||||
for _, raw := range p.Models {
|
||||
if err := upsertOverlayModel(v, raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for id, patch := range p.ModelOverrides {
|
||||
found := false
|
||||
for i := range v.Models {
|
||||
if strings.EqualFold(v.Models[i].ID, id) {
|
||||
// Clone first, for the same reason as upsertOverlayModel: the
|
||||
// entry's slices are shared with the built-in definition.
|
||||
spec := cloneModelSpec(v.Models[i])
|
||||
applyPatch(&spec, patch)
|
||||
v.Models[i] = spec
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
spec := ModelSpec{ID: id}
|
||||
applyPatch(&spec, patch)
|
||||
v.Models = append(v.Models, spec)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxIconBytes caps a vendor icon. Icons are base64'd into every
|
||||
// GET /models/providers response, so an oversized file is a response-size
|
||||
// problem for every viewer, not just a disk read.
|
||||
const maxIconBytes = 256 * 1024
|
||||
|
||||
// loadOverlayIcon resolves providers.*.icon to SVG bytes.
|
||||
//
|
||||
// The bytes are handed to every viewer of the model pages as a data: URI, so
|
||||
// the path is treated as untrusted even though writing the overlay already
|
||||
// requires filesystem access: an operator (or a config-management template)
|
||||
// that points `icon` at /etc/shadow or ../../secrets must not turn the
|
||||
// provider list into a file-disclosure endpoint for read-only tenants.
|
||||
// Hence: no absolute paths, no escaping the overlay's own directory
|
||||
// (symlinks included), a size cap, and the content must really be an SVG.
|
||||
func loadOverlayIcon(baseDir, ref string) ([]byte, error) {
|
||||
if looksLikeSVG([]byte(ref)) {
|
||||
if len(ref) > maxIconBytes {
|
||||
return nil, fmt.Errorf("icon: inline svg is %d bytes, limit is %d", len(ref), maxIconBytes)
|
||||
}
|
||||
return []byte(ref), nil
|
||||
}
|
||||
if filepath.IsAbs(ref) || strings.HasPrefix(ref, "/") || filepath.VolumeName(ref) != "" {
|
||||
return nil, fmt.Errorf("icon: absolute paths are not allowed: %q", ref)
|
||||
}
|
||||
clean := filepath.Clean(filepath.FromSlash(ref))
|
||||
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
|
||||
return nil, fmt.Errorf("icon: path escapes the overlay directory: %q", ref)
|
||||
}
|
||||
if baseDir == "" {
|
||||
baseDir = "."
|
||||
}
|
||||
full, err := resolveInsideDir(baseDir, clean)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("icon: %w", err)
|
||||
}
|
||||
info, err := os.Stat(full)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read icon: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("icon: %q is not a regular file", ref)
|
||||
}
|
||||
if info.Size() > maxIconBytes {
|
||||
return nil, fmt.Errorf("icon: %q is %d bytes, limit is %d", ref, info.Size(), maxIconBytes)
|
||||
}
|
||||
data, err := os.ReadFile(full)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read icon: %w", err)
|
||||
}
|
||||
if len(data) > maxIconBytes {
|
||||
return nil, fmt.Errorf("icon: %q is %d bytes, limit is %d", ref, len(data), maxIconBytes)
|
||||
}
|
||||
if !looksLikeSVG(data) {
|
||||
return nil, fmt.Errorf("icon: %q is not an SVG document", ref)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// resolveInsideDir joins rel onto dir and fails unless the result stays
|
||||
// inside it. Both sides are resolved through EvalSymlinks so a symlink
|
||||
// planted in the overlay directory cannot point out of it; a path that does
|
||||
// not exist is compared unresolved and left to the caller's os.Stat, which
|
||||
// reports it with a clearer message.
|
||||
func resolveInsideDir(dir, rel string) (string, error) {
|
||||
realDir, err := filepath.EvalSymlinks(dir)
|
||||
if err != nil {
|
||||
realDir = filepath.Clean(dir)
|
||||
}
|
||||
full := filepath.Join(realDir, rel)
|
||||
if resolved, err := filepath.EvalSymlinks(full); err == nil {
|
||||
full = resolved
|
||||
}
|
||||
if full != realDir && !strings.HasPrefix(full, realDir+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("path escapes the overlay directory: %q", rel)
|
||||
}
|
||||
return full, nil
|
||||
}
|
||||
|
||||
// looksLikeSVG reports whether data is an SVG document: an optional XML
|
||||
// prologue (declaration, doctype, comments, whitespace) followed by <svg.
|
||||
func looksLikeSVG(data []byte) bool {
|
||||
s := strings.TrimPrefix(string(data), "\ufeff")
|
||||
for {
|
||||
s = strings.TrimSpace(s)
|
||||
switch {
|
||||
case strings.HasPrefix(s, "<?"):
|
||||
s = skipPast(s, "?>")
|
||||
case strings.HasPrefix(s, "<!--"):
|
||||
s = skipPast(s, "-->")
|
||||
case strings.HasPrefix(s, "<!"):
|
||||
s = skipPast(s, ">")
|
||||
default:
|
||||
lower := strings.ToLower(s)
|
||||
if !strings.HasPrefix(lower, "<svg") || len(lower) == len("<svg") {
|
||||
return false
|
||||
}
|
||||
// Reject "<svgfoo": the tag must end right after the name.
|
||||
return strings.ContainsRune(" \t\r\n>/", rune(lower[len("<svg")]))
|
||||
}
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// skipPast returns what follows the first occurrence of end, or "" if the
|
||||
// token never closes.
|
||||
func skipPast(s, end string) string {
|
||||
i := strings.Index(s, end)
|
||||
if i < 0 {
|
||||
return ""
|
||||
}
|
||||
return s[i+len(end):]
|
||||
}
|
||||
|
||||
// upsertOverlayModel applies one providers.*.models entry.
|
||||
//
|
||||
// A new id creates a full entry. An id that already exists is *patched*, not
|
||||
// replaced: both config/models.json.example and the docs present `models` as
|
||||
// the way to restate a known model with corrected facts, and most fields of
|
||||
// ModelSpec cannot tell "absent" from "zero" — Reasoning is a plain bool, so
|
||||
// an entry that only fixes context_window used to silently turn reasoning
|
||||
// off and drop thinking levels, compat and input along with it. Unmarshaling
|
||||
// the operator's JSON onto a copy of the stored entry leaves every key they
|
||||
// did not write exactly as it was.
|
||||
func upsertOverlayModel(v *Vendor, raw json.RawMessage) error {
|
||||
// Decode strictly first: this is what rejects typos and wrong types, the
|
||||
// same guarantee the rest of the overlay gives. The value is used only
|
||||
// for the id, since the merge below re-reads the raw bytes.
|
||||
var spec ModelSpec
|
||||
dec := json.NewDecoder(bytesReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&spec); err != nil {
|
||||
return fmt.Errorf("model entry: %w", err)
|
||||
}
|
||||
if spec.ID == "" {
|
||||
return fmt.Errorf("model without id")
|
||||
}
|
||||
for i := range v.Models {
|
||||
if !strings.EqualFold(v.Models[i].ID, spec.ID) {
|
||||
continue
|
||||
}
|
||||
// cloneModelSpec first: the vendor's Models slice was only shallow
|
||||
// copied, so unmarshaling into the entry's slices/maps in place would
|
||||
// write through to the built-in vendor's package-level definition.
|
||||
merged := cloneModelSpec(v.Models[i])
|
||||
if err := json.Unmarshal(raw, &merged); err != nil {
|
||||
return fmt.Errorf("model %s: %w", spec.ID, err)
|
||||
}
|
||||
v.Models[i] = merged
|
||||
return nil
|
||||
}
|
||||
v.Models = append(v.Models, spec)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cloneModelSpec deep-copies the reference-typed fields of a spec.
|
||||
func cloneModelSpec(m ModelSpec) ModelSpec {
|
||||
out := m
|
||||
out.Input = append([]string(nil), m.Input...)
|
||||
out.Aliases = append([]string(nil), m.Aliases...)
|
||||
out.Compat = append(json.RawMessage(nil), m.Compat...)
|
||||
if m.ThinkingLevels != nil {
|
||||
levels := make(api.ThinkingLevelMap, len(m.ThinkingLevels))
|
||||
for k, v := range m.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
out.ThinkingLevels = levels
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func applyPatch(m *ModelSpec, p ModelSpecPatch) {
|
||||
if p.Name != "" {
|
||||
m.Name = p.Name
|
||||
}
|
||||
if p.API != "" {
|
||||
m.API = p.API
|
||||
}
|
||||
if p.Reasoning != nil {
|
||||
m.Reasoning = *p.Reasoning
|
||||
}
|
||||
if len(p.Input) > 0 {
|
||||
m.Input = p.Input
|
||||
}
|
||||
if p.ContextWindow > 0 {
|
||||
m.ContextWindow = p.ContextWindow
|
||||
}
|
||||
if p.MaxOutputTokens > 0 {
|
||||
m.MaxOutputTokens = p.MaxOutputTokens
|
||||
}
|
||||
if p.Cost != nil {
|
||||
m.Cost = p.Cost
|
||||
}
|
||||
if len(p.ThinkingLevels) > 0 {
|
||||
levels := api.ThinkingLevelMap{}
|
||||
for k, v := range m.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
for k, v := range p.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
m.ThinkingLevels = levels
|
||||
}
|
||||
if len(p.Compat) > 0 {
|
||||
m.Compat = mergeRawObjects(m.Compat, p.Compat)
|
||||
}
|
||||
if len(p.Aliases) > 0 {
|
||||
m.Aliases = append(m.Aliases, p.Aliases...)
|
||||
}
|
||||
if p.Deprecated != nil {
|
||||
m.Deprecated = *p.Deprecated
|
||||
}
|
||||
}
|
||||
|
||||
// mergeRawObjects shallow-merges two JSON objects (b wins).
|
||||
func mergeRawObjects(a, b json.RawMessage) json.RawMessage {
|
||||
merged := map[string]json.RawMessage{}
|
||||
if len(a) > 0 {
|
||||
_ = json.Unmarshal(a, &merged)
|
||||
}
|
||||
patch := map[string]json.RawMessage{}
|
||||
if len(b) > 0 {
|
||||
_ = json.Unmarshal(b, &patch)
|
||||
}
|
||||
for k, v := range patch {
|
||||
merged[k] = v
|
||||
}
|
||||
out, _ := json.Marshal(merged)
|
||||
return out
|
||||
}
|
||||
|
||||
// ModelsFile is the schema of a vendor's embedded models.json.
|
||||
type ModelsFile struct {
|
||||
Vendor string `json:"vendor"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Models []ModelSpec `json:"models"`
|
||||
}
|
||||
|
||||
// MustParseModels decodes an embedded models.json; vendors call it from
|
||||
// package init, so a malformed file fails the build's tests immediately.
|
||||
func MustParseModels(data []byte) []ModelSpec {
|
||||
var file ModelsFile
|
||||
dec := json.NewDecoder(bytesReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&file); err != nil {
|
||||
panic(fmt.Sprintf("catalog: invalid models.json: %v", err))
|
||||
}
|
||||
// The file-level source is the vendor's model documentation, and most
|
||||
// entries omit their own because that page covers them. Pushing it down
|
||||
// means every entry can answer "where is this documented" — the editor
|
||||
// links to it from the model picker.
|
||||
for i := range file.Models {
|
||||
if file.Models[i].Source == "" {
|
||||
file.Models[i].Source = file.Source
|
||||
}
|
||||
}
|
||||
return file.Models
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
package catalog
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// An overlay entry under "models" that restates an existing id must patch it.
|
||||
// The docs and config/models.json.example both present "models" as the way to
|
||||
// correct a known model, and ModelSpec cannot tell absent from zero: before
|
||||
// this, fixing max_output_tokens alone silently cleared reasoning (a plain
|
||||
// bool), the thinking levels, the compat overlay and the input modalities.
|
||||
func TestApplyOverlay_ModelsUpsertPatchesExistingEntry(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
overlay := `{"providers": {"acme": {"models": [
|
||||
{"id": "acme-pro", "max_output_tokens": 8192},
|
||||
{"id": "acme-r1", "context_window": 128000}
|
||||
]}}}`
|
||||
require.NoError(t, ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Spec.Reasoning, "omitted reasoning must not turn thinking off")
|
||||
assert.Equal(t, []string{"text", "image"}, r.Spec.Input, "omitted input survives")
|
||||
assert.Equal(t, 200000, r.Spec.ContextWindow, "omitted context_window survives")
|
||||
assert.Equal(t, 8192, r.Spec.MaxOutputTokens, "the field that was written is applied")
|
||||
assert.False(t, r.OpenAICompletions.SupportsTemperature, "omitted compat survives")
|
||||
|
||||
r, err = Resolve(Ref{Provider: "acme", Model: "acme-r1"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Spec.Reasoning)
|
||||
assert.Equal(t, 128000, r.Spec.ContextWindow)
|
||||
assert.False(t, r.ThinkingLevels.Supports(api.ReasoningOff),
|
||||
"omitted thinking_levels survive: acme-r1 still cannot be switched off")
|
||||
}
|
||||
|
||||
// Patching must not write through to the built-in definition: the vendor copy
|
||||
// made by ApplyOverlay is shallow, so the spec's slices and maps are shared
|
||||
// with the vendor package's own (package-level) models.json data.
|
||||
func TestApplyOverlay_ModelsUpsertDoesNotMutateBuiltinVendor(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
builtin, ok := Get("acme")
|
||||
require.True(t, ok)
|
||||
|
||||
overlay := `{"providers": {"acme": {"models": [{"id": "acme-pro", "input": ["audio"]}]}}}`
|
||||
require.NoError(t, ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
require.Equal(t, "acme-pro", builtin.Models[0].ID)
|
||||
assert.Equal(t, []string{"text", "image"}, builtin.Models[0].Input,
|
||||
"the built-in spec must be untouched by the overlay")
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"audio"}, r.Spec.Input, "the written field is still applied")
|
||||
}
|
||||
|
||||
func TestApplyOverlay_ModelsUpsertExplicitFalseAndNewEntries(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
overlay := `{"providers": {"acme": {"models": [
|
||||
{"id": "acme-pro", "reasoning": false},
|
||||
{"id": "acme-ultra", "context_window": 400000}
|
||||
]}}}`
|
||||
require.NoError(t, ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
r, err := Resolve(Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.Spec.Reasoning, "an explicit false still turns reasoning off")
|
||||
|
||||
r, err = Resolve(Ref{Provider: "acme", Model: "acme-ultra"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Cataloged, "an unknown id creates a full entry")
|
||||
assert.Equal(t, 400000, r.Spec.ContextWindow)
|
||||
assert.False(t, r.Spec.Reasoning)
|
||||
}
|
||||
|
||||
func TestApplyOverlay_ModelsEntryValidation(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
assert.ErrorContains(t,
|
||||
ApplyOverlay([]byte(`{"providers": {"acme": {"models": [{"id": "x", "bogus": 1}]}}}`), dir),
|
||||
"bogus", "unknown keys inside a model entry are still rejected")
|
||||
assert.ErrorContains(t,
|
||||
ApplyOverlay([]byte(`{"providers": {"acme": {"models": [{"context_window": 1}]}}}`), dir),
|
||||
"model without id")
|
||||
}
|
||||
|
||||
const testSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"></svg>`
|
||||
|
||||
func overlayWithIcon(icon string) string {
|
||||
return `{"providers": {"lab": {"icon": ` + quoteJSON(icon) + `}}}`
|
||||
}
|
||||
|
||||
// quoteJSON is enough for the paths used here (no escaping needed).
|
||||
func quoteJSON(s string) string { return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` }
|
||||
|
||||
func TestApplyOverlay_IconAcceptsInlineAndContainedFiles(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(dir, "icons"), 0o755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "icons", "lab.svg"), []byte(testSVG), 0o600))
|
||||
|
||||
require.NoError(t, ApplyOverlay([]byte(overlayWithIcon("icons/lab.svg")), dir))
|
||||
lab, ok := Get("lab")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, testSVG, string(lab.Icon))
|
||||
|
||||
require.NoError(t, ApplyOverlay([]byte(overlayWithIcon("<svg><rect/></svg>")), dir))
|
||||
lab, _ = Get("lab")
|
||||
assert.Equal(t, "<svg><rect/></svg>", string(lab.Icon))
|
||||
}
|
||||
|
||||
// The icon bytes are served as a data: URI to every viewer of the model
|
||||
// pages, so an overlay must not be able to turn the provider list into a
|
||||
// file-disclosure endpoint.
|
||||
func TestApplyOverlay_IconRejectsUncontainedPaths(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
outside := filepath.Join(t.TempDir(), "secret.svg")
|
||||
require.NoError(t, os.WriteFile(outside, []byte(testSVG), 0o600))
|
||||
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon(outside)), dir),
|
||||
"absolute paths are not allowed")
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("/etc/passwd")), dir),
|
||||
"absolute paths are not allowed")
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("../secret.svg")), dir),
|
||||
"escapes the overlay directory")
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("icons/../../secret.svg")), dir),
|
||||
"escapes the overlay directory")
|
||||
|
||||
link := filepath.Join(dir, "link.svg")
|
||||
if err := os.Symlink(outside, link); err == nil {
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("link.svg")), dir),
|
||||
"escapes the overlay directory", "a symlink out of the directory is still out of it")
|
||||
}
|
||||
|
||||
_, exists := Get("lab")
|
||||
assert.False(t, exists, "a rejected icon must not register the provider")
|
||||
}
|
||||
|
||||
func TestApplyOverlay_IconRejectsNonSVGAndOversizedFiles(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "passwd.svg"), []byte("root:x:0:0:root:/root:/bin/sh\n"), 0o600))
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("passwd.svg")), dir), "not an SVG document")
|
||||
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "png.svg"), []byte("\x89PNG\r\n\x1a\n"), 0o600))
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("png.svg")), dir), "not an SVG document")
|
||||
|
||||
big := append([]byte(`<svg xmlns="http://www.w3.org/2000/svg">`), make([]byte, maxIconBytes)...)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "big.svg"), big, 0o600))
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("big.svg")), dir), "limit is")
|
||||
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(dir, "dir.svg"), 0o755))
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("dir.svg")), dir), "not a regular file")
|
||||
|
||||
assert.ErrorContains(t, ApplyOverlay([]byte(overlayWithIcon("missing.svg")), dir), "read icon")
|
||||
}
|
||||
|
||||
func TestLooksLikeSVG(t *testing.T) {
|
||||
for _, in := range []string{
|
||||
testSVG,
|
||||
" \n<svg/>",
|
||||
"\ufeff<?xml version=\"1.0\"?>\n<!-- brand mark --><svg >x</svg>",
|
||||
"<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"x.dtd\"><svg>y</svg>",
|
||||
"<SVG></SVG>",
|
||||
} {
|
||||
assert.True(t, looksLikeSVG([]byte(in)), "want SVG: %q", in)
|
||||
}
|
||||
for _, in := range []string{
|
||||
"", " ", "<svg", "<svgx>", "not markup at all",
|
||||
"<html><svg></svg></html>", "<?xml version=\"1.0\"?>", "<!-- unterminated",
|
||||
"root:x:0:0::/root:/bin/sh",
|
||||
} {
|
||||
assert.False(t, looksLikeSVG([]byte(in)), "want not SVG: %q", in)
|
||||
}
|
||||
}
|
||||
|
||||
// The icon path is relative to the overlay file's own directory.
|
||||
func TestLoadOverlay_ResolvesIconRelativeToConfigDir(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "lab.svg"), []byte(testSVG), 0o600))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "models.json"),
|
||||
[]byte(overlayWithIcon("lab.svg")), 0o600))
|
||||
t.Setenv("MODELS_CONFIG", "")
|
||||
|
||||
require.NoError(t, LoadOverlay(dir))
|
||||
lab, ok := Get("lab")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, testSVG, string(lab.Icon))
|
||||
assert.Equal(t, []types.ModelType{types.ModelTypeKnowledgeQA}, lab.ModelTypes)
|
||||
}
|
||||
|
|
@ -0,0 +1,254 @@
|
|||
package catalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// GenericID is the catch-all vendor for any OpenAI-compatible endpoint.
|
||||
const GenericID = "generic"
|
||||
|
||||
var (
|
||||
mu sync.RWMutex
|
||||
vendors = map[string]*Vendor{}
|
||||
)
|
||||
|
||||
// Register adds a built-in vendor. Registering the same id twice replaces
|
||||
// the earlier definition (the deployment overlay relies on this).
|
||||
func Register(v *Vendor) {
|
||||
if v == nil || v.ID == "" {
|
||||
panic("catalog: vendor without id")
|
||||
}
|
||||
if v.API == "" {
|
||||
v.API = api.APIOpenAICompletions
|
||||
}
|
||||
if v.Auth == "" {
|
||||
v.Auth = AuthBearer
|
||||
}
|
||||
for i := range v.Models {
|
||||
if v.Models[i].Type == "" {
|
||||
v.Models[i].Type = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
if v.Models[i].API == "" && v.Models[i].Type == types.ModelTypeKnowledgeQA {
|
||||
v.Models[i].API = v.API
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
vendors[v.ID] = v
|
||||
}
|
||||
|
||||
// Get returns a vendor by id.
|
||||
func Get(id string) (*Vendor, bool) {
|
||||
mu.RLock()
|
||||
defer mu.RUnlock()
|
||||
v, ok := vendors[strings.ToLower(strings.TrimSpace(id))]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
// GetOrGeneric returns the vendor or the generic catch-all. When no vendor
|
||||
// package is linked into the binary (unit tests of leaf packages), a
|
||||
// built-in generic definition keeps resolution working.
|
||||
func GetOrGeneric(id string) *Vendor {
|
||||
if v, ok := Get(id); ok {
|
||||
return v
|
||||
}
|
||||
if v, ok := Get(GenericID); ok {
|
||||
return v
|
||||
}
|
||||
return fallbackGeneric
|
||||
}
|
||||
|
||||
// fallbackGeneric mirrors internal/models/vendors/generic so behaviour does
|
||||
// not depend on whether that package was imported.
|
||||
var fallbackGeneric = &Vendor{
|
||||
ID: GenericID,
|
||||
Name: "Custom (OpenAI-compatible)",
|
||||
API: api.APIOpenAICompletions,
|
||||
DefaultBaseURLs: map[types.ModelType]string{},
|
||||
ModelTypes: []types.ModelType{
|
||||
types.ModelTypeKnowledgeQA, types.ModelTypeEmbedding, types.ModelTypeRerank,
|
||||
types.ModelTypeVLLM, types.ModelTypeASR,
|
||||
},
|
||||
Auth: AuthBearer,
|
||||
Compat: VendorCompat{OpenAICompletions: OpenAICompletionsCompat{
|
||||
MaxTokensField: Ptr("max_tokens"),
|
||||
ThinkingFormat: Ptr(ThinkingFormatChatTemplateKwargs),
|
||||
}},
|
||||
}
|
||||
|
||||
// List returns every vendor ordered by Order then id.
|
||||
func List() []*Vendor {
|
||||
mu.RLock()
|
||||
defer mu.RUnlock()
|
||||
out := make([]*Vendor, 0, len(vendors))
|
||||
for _, v := range vendors {
|
||||
out = append(out, v)
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].Order != out[j].Order {
|
||||
return out[i].Order < out[j].Order
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ListByType returns vendors that support a model type.
|
||||
func ListByType(modelType types.ModelType) []*Vendor {
|
||||
all := List()
|
||||
out := make([]*Vendor, 0, len(all))
|
||||
for _, v := range all {
|
||||
if v.SupportsType(modelType) {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DetectByURL finds the vendor whose URLPatterns match a base URL. Used only
|
||||
// when a stored model row carries no provider id. Longer patterns win so
|
||||
// "api.lkeap.cloud.tencent.com" beats "tencent".
|
||||
func DetectByURL(baseURL string) string {
|
||||
if baseURL == "" {
|
||||
return GenericID
|
||||
}
|
||||
lower := strings.ToLower(baseURL)
|
||||
bestID, bestLen := GenericID, 0
|
||||
for _, v := range List() {
|
||||
for _, p := range v.URLPatterns {
|
||||
if p != "" && strings.Contains(lower, strings.ToLower(p)) && len(p) > bestLen {
|
||||
bestID, bestLen = v.ID, len(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
return bestID
|
||||
}
|
||||
|
||||
// ModelsByType returns the vendor's catalog entries for a model type,
|
||||
// hiding deprecated and pattern-only entries.
|
||||
func (v *Vendor) ModelsByType(modelType types.ModelType) []ModelSpec {
|
||||
out := make([]ModelSpec, 0)
|
||||
for _, m := range v.Models {
|
||||
if m.Deprecated || m.ID == "" {
|
||||
continue
|
||||
}
|
||||
mt := m.Type
|
||||
if mt == "" {
|
||||
mt = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
switch modelType {
|
||||
case types.ModelTypeVLLM:
|
||||
// VLM pickers list chat models that accept images.
|
||||
if mt == types.ModelTypeKnowledgeQA && m.AcceptsImages() {
|
||||
out = append(out, m)
|
||||
}
|
||||
default:
|
||||
if mt == modelType {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// FindModel looks a model name up in the vendor catalog: exact id, then
|
||||
// aliases, then glob patterns (longest literal prefix wins). Matching is
|
||||
// case-insensitive.
|
||||
func (v *Vendor) FindModel(name string) (ModelSpec, bool) {
|
||||
needle := strings.ToLower(strings.TrimSpace(name))
|
||||
if needle == "" {
|
||||
return ModelSpec{}, false
|
||||
}
|
||||
for _, m := range v.Models {
|
||||
if strings.ToLower(m.ID) == needle {
|
||||
return m, true
|
||||
}
|
||||
}
|
||||
for _, m := range v.Models {
|
||||
for _, alias := range m.Aliases {
|
||||
if strings.ToLower(alias) == needle {
|
||||
return m, true
|
||||
}
|
||||
}
|
||||
}
|
||||
var best ModelSpec
|
||||
bestScore := -1
|
||||
for _, m := range v.Models {
|
||||
if m.Match == "" {
|
||||
continue
|
||||
}
|
||||
if globMatch(strings.ToLower(m.Match), needle) {
|
||||
score := len(strings.TrimRight(strings.SplitN(m.Match, "*", 2)[0], "*"))
|
||||
if score > bestScore {
|
||||
best, bestScore = m, score
|
||||
}
|
||||
}
|
||||
}
|
||||
if bestScore >= 0 {
|
||||
return best, true
|
||||
}
|
||||
return ModelSpec{}, false
|
||||
}
|
||||
|
||||
// globMatch supports '*' wildcards only.
|
||||
func globMatch(pattern, s string) bool {
|
||||
parts := strings.Split(pattern, "*")
|
||||
if len(parts) == 1 {
|
||||
return pattern == s
|
||||
}
|
||||
if !strings.HasPrefix(s, parts[0]) {
|
||||
return false
|
||||
}
|
||||
s = s[len(parts[0]):]
|
||||
for i := 1; i < len(parts)-1; i++ {
|
||||
idx := strings.Index(s, parts[i])
|
||||
if idx < 0 {
|
||||
return false
|
||||
}
|
||||
s = s[idx+len(parts[i]):]
|
||||
}
|
||||
return strings.HasSuffix(s, parts[len(parts)-1])
|
||||
}
|
||||
|
||||
func defaultValidate(v *Vendor, cfg *Config) error {
|
||||
if cfg == nil {
|
||||
return fmt.Errorf("config is nil")
|
||||
}
|
||||
if v.RequiresAuth && v.Auth != AuthSigned && strings.TrimSpace(cfg.APIKey) == "" {
|
||||
return fmt.Errorf("API key is required for %s", v.Name)
|
||||
}
|
||||
if v.ID == GenericID && strings.TrimSpace(cfg.BaseURL) == "" {
|
||||
return fmt.Errorf("base URL is required for generic provider")
|
||||
}
|
||||
if strings.TrimSpace(cfg.ModelName) == "" {
|
||||
return fmt.Errorf("model name is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func bytesReader(b []byte) *bytes.Reader { return bytes.NewReader(b) }
|
||||
|
||||
// reset clears the registry and returns a function that puts the previous
|
||||
// contents back (tests only). The registry is process-global, so a test that
|
||||
// merely cleared it would leave every later test in the same binary — the
|
||||
// external catalog_test package included — resolving against an empty
|
||||
// catalog, which silently turns assertions about real vendors into
|
||||
// assertions about the generic fallback.
|
||||
func reset() func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
previous := vendors
|
||||
vendors = map[string]*Vendor{}
|
||||
return func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
vendors = previous
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,348 @@
|
|||
package catalog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Extra-config keys honoured by Resolve. They predate the catalog and stay
|
||||
// supported so existing model rows keep working unchanged.
|
||||
const (
|
||||
// ExtraAPI forces a protocol ("openai-responses", "anthropic-messages", ...).
|
||||
ExtraAPI = "api"
|
||||
// ExtraRemoteModelName sends a different model id on the wire.
|
||||
ExtraRemoteModelName = "remote_model_name"
|
||||
// ExtraAPIVersion is the Azure api-version query parameter.
|
||||
ExtraAPIVersion = "api_version"
|
||||
// ExtraThinkingControl is the legacy thinking encoding selector written
|
||||
// by older UIs: none | enable_thinking | thinking_type | chat_template_kwargs.
|
||||
ExtraThinkingControl = "thinking_control"
|
||||
)
|
||||
|
||||
// Ref identifies one configured model.
|
||||
type Ref struct {
|
||||
Provider string
|
||||
Model string
|
||||
BaseURL string
|
||||
ModelType types.ModelType
|
||||
Extra map[string]string
|
||||
Override *types.ModelSpecOverride
|
||||
}
|
||||
|
||||
// Resolved is the fully merged view of one model: which vendor, which
|
||||
// protocol, which settings.
|
||||
type Resolved struct {
|
||||
Vendor *Vendor
|
||||
// Spec is the effective catalog entry (synthesized when unknown).
|
||||
Spec ModelSpec
|
||||
// Cataloged reports whether the model name matched a catalog entry.
|
||||
Cataloged bool
|
||||
API api.API
|
||||
BaseURL string
|
||||
// RemoteModel is the id sent on the wire.
|
||||
RemoteModel string
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
|
||||
OpenAICompletions OpenAICompletionsSettings
|
||||
OpenAIResponses OpenAIResponsesSettings
|
||||
AnthropicMessages AnthropicMessagesSettings
|
||||
GoogleGenerativeAI GoogleGenerativeAISettings
|
||||
}
|
||||
|
||||
// Resolve merges the vendor, catalog entry, extra-config and per-row
|
||||
// overrides for a model reference. It never fails for unknown vendors or
|
||||
// models: they degrade to the generic OpenAI-compatible baseline.
|
||||
func Resolve(ref Ref) (*Resolved, error) {
|
||||
providerID := strings.ToLower(strings.TrimSpace(ref.Provider))
|
||||
if providerID == "" {
|
||||
providerID = DetectByURL(ref.BaseURL)
|
||||
}
|
||||
vendor := GetOrGeneric(providerID)
|
||||
if vendor == nil {
|
||||
return nil, fmt.Errorf("catalog: no vendors registered")
|
||||
}
|
||||
modelType := ref.ModelType
|
||||
if modelType == "" {
|
||||
modelType = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
|
||||
baseURL := strings.TrimRight(strings.TrimSpace(ref.BaseURL), "/")
|
||||
if baseURL == "" {
|
||||
baseURL = strings.TrimRight(vendor.GetDefaultURL(modelType), "/")
|
||||
}
|
||||
|
||||
spec, cataloged := vendor.FindModel(ref.Model)
|
||||
if !cataloged {
|
||||
spec = ModelSpec{ID: ref.Model, Type: types.ModelTypeKnowledgeQA}
|
||||
}
|
||||
if spec.API == "" {
|
||||
spec.API = vendor.API
|
||||
}
|
||||
if ref.Override != nil {
|
||||
applySpecOverride(&spec, ref.Override)
|
||||
}
|
||||
|
||||
resolvedAPI := spec.API
|
||||
if forced := strings.TrimSpace(ref.Extra[ExtraAPI]); forced != "" {
|
||||
resolvedAPI = api.API(forced)
|
||||
} else {
|
||||
resolvedAPI = inferAPIFromURL(baseURL, resolvedAPI)
|
||||
if vendor.PreferAPI != nil {
|
||||
if preferred := vendor.PreferAPI(baseURL, spec); preferred != "" {
|
||||
resolvedAPI = preferred
|
||||
}
|
||||
}
|
||||
}
|
||||
if !resolvedAPI.Known() {
|
||||
return nil, fmt.Errorf("catalog: unknown api %q for provider %s", resolvedAPI, vendor.ID)
|
||||
}
|
||||
|
||||
levels := api.ThinkingLevelMap{}
|
||||
for k, v := range vendor.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
for k, v := range spec.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
if ref.Override != nil {
|
||||
for k, v := range ref.Override.ThinkingLevels {
|
||||
levels[api.ReasoningEffort(k)] = v
|
||||
}
|
||||
}
|
||||
|
||||
out := &Resolved{
|
||||
Vendor: vendor,
|
||||
Spec: spec,
|
||||
Cataloged: cataloged,
|
||||
API: resolvedAPI,
|
||||
BaseURL: baseURL,
|
||||
RemoteModel: ref.Model,
|
||||
ThinkingLevels: levels,
|
||||
}
|
||||
if override := strings.TrimSpace(ref.Extra[ExtraRemoteModelName]); override != "" {
|
||||
out.RemoteModel = override
|
||||
}
|
||||
|
||||
overrideCompat := ref.Override.CompatJSON()
|
||||
|
||||
// Every protocol's settings are resolved so callers can inspect any of
|
||||
// them, but only the layers whose API matches contribute model/override
|
||||
// compat (a flat compat object is meaningless for another protocol).
|
||||
completions := DefaultOpenAICompletions()
|
||||
apply(&completions, &vendor.Compat.OpenAICompletions)
|
||||
if err := applyRawCompat(
|
||||
&completions, &OpenAICompletionsCompat{}, spec.Compat, spec.API, api.APIOpenAICompletions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&completions, &OpenAICompletionsCompat{}, overrideCompat, resolvedAPI, api.APIOpenAICompletions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
applyLegacyThinkingControl(&completions, ref.Extra[ExtraThinkingControl])
|
||||
out.OpenAICompletions = completions
|
||||
|
||||
responses := DefaultOpenAIResponses()
|
||||
apply(&responses, &vendor.Compat.OpenAIResponses)
|
||||
if err := applyRawCompat(
|
||||
&responses, &OpenAIResponsesCompat{}, spec.Compat, spec.API, api.APIOpenAIResponses,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&responses, &OpenAIResponsesCompat{}, overrideCompat, resolvedAPI, api.APIOpenAIResponses,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.OpenAIResponses = responses
|
||||
|
||||
anthropic := DefaultAnthropicMessages()
|
||||
apply(&anthropic, &vendor.Compat.AnthropicMessages)
|
||||
if err := applyRawCompat(
|
||||
&anthropic, &AnthropicMessagesCompat{}, spec.Compat, spec.API, api.APIAnthropicMessages,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&anthropic, &AnthropicMessagesCompat{}, overrideCompat, resolvedAPI, api.APIAnthropicMessages,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.AnthropicMessages = anthropic
|
||||
|
||||
google := DefaultGoogleGenerativeAI()
|
||||
apply(&google, &vendor.Compat.GoogleGenerativeAI)
|
||||
if err := applyRawCompat(
|
||||
&google, &GoogleGenerativeAICompat{}, spec.Compat, spec.API, api.APIGoogleGenerativeAI,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&google, &GoogleGenerativeAICompat{}, overrideCompat, resolvedAPI, api.APIGoogleGenerativeAI,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.GoogleGenerativeAI = google
|
||||
// An explicit legacy thinking_control is the operator saying "this row
|
||||
// does think, send the switch this way", so it outranks the catalog.
|
||||
if strings.TrimSpace(ref.Extra[ExtraThinkingControl]) == "" {
|
||||
out.silenceThinkingForNonReasoningModel()
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// silenceThinkingForNonReasoningModel drops every thinking field for a
|
||||
// catalogued model the vendor documents as non-reasoning (DeepSeek's
|
||||
// non-thinking alias, LKEAP's V3-0324 generation, plain instruct models).
|
||||
// Without this, a caller that asks for thinking — an agent whose config says
|
||||
// so, or the model debug drawer — would send a switch the model does not
|
||||
// understand, and some vendors answer 400.
|
||||
//
|
||||
// The gate deliberately applies only to catalogued entries: an unknown model
|
||||
// on a self-hosted runtime carries Reasoning=false simply because nobody
|
||||
// described it, and those deployments do rely on the thinking switch.
|
||||
func (r *Resolved) silenceThinkingForNonReasoningModel() {
|
||||
if !r.Cataloged || r.Spec.Reasoning {
|
||||
return
|
||||
}
|
||||
r.OpenAICompletions.ThinkingFormat = ThinkingFormatNone
|
||||
r.OpenAICompletions.ThinkingBudgetField = ""
|
||||
r.OpenAICompletions.SupportsReasoningEffort = false
|
||||
r.GoogleGenerativeAI.ThinkingMode = GoogleThinkingNone
|
||||
r.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
for _, level := range api.ReasoningLadder {
|
||||
r.ThinkingLevels[level] = nil
|
||||
}
|
||||
r.ThinkingLevels[api.ReasoningAuto] = nil
|
||||
}
|
||||
|
||||
// applyRawCompat decodes raw into the overlay type and applies it when the
|
||||
// layer's API matches the target protocol.
|
||||
func applyRawCompat(settings any, overlayPtr any, raw json.RawMessage, layerAPI, target api.API) error {
|
||||
if len(raw) == 0 || layerAPI != target {
|
||||
return nil
|
||||
}
|
||||
if err := decodeCompat(raw, overlayPtr); err != nil {
|
||||
return fmt.Errorf("%s compat: %w", target, err)
|
||||
}
|
||||
apply(settings, overlayPtr)
|
||||
return nil
|
||||
}
|
||||
|
||||
func applySpecOverride(spec *ModelSpec, o *types.ModelSpecOverride) {
|
||||
if o == nil {
|
||||
return
|
||||
}
|
||||
if o.API != "" {
|
||||
spec.API = api.API(o.API)
|
||||
}
|
||||
if o.Reasoning != nil {
|
||||
spec.Reasoning = *o.Reasoning
|
||||
}
|
||||
if len(o.Input) > 0 {
|
||||
spec.Input = o.Input
|
||||
}
|
||||
if o.ContextWindow > 0 {
|
||||
spec.ContextWindow = o.ContextWindow
|
||||
}
|
||||
if o.MaxOutputTokens > 0 {
|
||||
spec.MaxOutputTokens = o.MaxOutputTokens
|
||||
}
|
||||
}
|
||||
|
||||
// inferAPIFromURL applies the two URL conventions vendors use to expose a
|
||||
// second protocol on a sub-path: ".../openai" for an OpenAI-compatible
|
||||
// facade (Gemini, LongCat, Novita) and ".../anthropic" for an Anthropic
|
||||
// Messages facade (MiniMax, Zhipu, Moonshot, Volcengine coding plans).
|
||||
func inferAPIFromURL(baseURL string, current api.API) api.API {
|
||||
lower := strings.ToLower(strings.TrimRight(baseURL, "/"))
|
||||
switch {
|
||||
case strings.HasSuffix(lower, "/anthropic") || strings.HasSuffix(lower, "/anthropic/v1"):
|
||||
return api.APIAnthropicMessages
|
||||
case current == api.APIGoogleGenerativeAI &&
|
||||
(strings.HasSuffix(lower, "/openai") || strings.Contains(lower, "/openai/")):
|
||||
return api.APIOpenAICompletions
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// applyLegacyThinkingControl maps the pre-catalog thinking_control value
|
||||
// onto the new settings. Unknown non-empty values keep the historical
|
||||
// fallback (chat_template_kwargs).
|
||||
func applyLegacyThinkingControl(s *OpenAICompletionsSettings, value string) {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "":
|
||||
return
|
||||
case "none":
|
||||
s.ThinkingFormat = ThinkingFormatNone
|
||||
case "enable_thinking":
|
||||
s.ThinkingFormat = ThinkingFormatEnableThinking
|
||||
case "thinking_type":
|
||||
s.ThinkingFormat = ThinkingFormatThinkingType
|
||||
default:
|
||||
s.ThinkingFormat = ThinkingFormatChatTemplateKwargs
|
||||
}
|
||||
}
|
||||
|
||||
// Capabilities is the UI-facing summary of a resolved model.
|
||||
type Capabilities struct {
|
||||
Provider string `json:"provider"`
|
||||
API api.API `json:"api"`
|
||||
Cataloged bool `json:"cataloged"`
|
||||
Reasoning bool `json:"reasoning"`
|
||||
ThinkingLevels []api.ReasoningEffort `json:"thinking_levels"`
|
||||
ThinkingFormat string `json:"thinking_format"`
|
||||
Input []string `json:"input,omitempty"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
MaxTokensField string `json:"max_tokens_field,omitempty"`
|
||||
}
|
||||
|
||||
// Capabilities summarizes the resolved model for API responses.
|
||||
func (r *Resolved) Capabilities() Capabilities {
|
||||
if r == nil {
|
||||
return Capabilities{}
|
||||
}
|
||||
caps := Capabilities{
|
||||
Provider: r.Vendor.ID,
|
||||
API: r.API,
|
||||
Cataloged: r.Cataloged,
|
||||
Reasoning: r.Spec.Reasoning,
|
||||
Input: r.Spec.Input,
|
||||
ContextWindow: r.Spec.ContextWindow,
|
||||
MaxOutputTokens: r.Spec.MaxOutputTokens,
|
||||
}
|
||||
switch r.API {
|
||||
case api.APIOpenAICompletions:
|
||||
caps.ThinkingFormat = string(r.OpenAICompletions.ThinkingFormat)
|
||||
caps.MaxTokensField = r.OpenAICompletions.MaxTokensField
|
||||
if caps.ThinkingFormat == string(ThinkingFormatNone) {
|
||||
caps.ThinkingLevels = []api.ReasoningEffort{}
|
||||
return caps
|
||||
}
|
||||
case api.APIOpenAIResponses:
|
||||
caps.ThinkingFormat = "reasoning.effort"
|
||||
caps.MaxTokensField = "max_output_tokens"
|
||||
case api.APIAnthropicMessages:
|
||||
caps.ThinkingFormat = "thinking." + string(r.AnthropicMessages.ThinkingMode)
|
||||
caps.MaxTokensField = "max_tokens"
|
||||
case api.APIGoogleGenerativeAI:
|
||||
caps.ThinkingFormat = "thinkingConfig." + string(r.GoogleGenerativeAI.ThinkingMode)
|
||||
caps.MaxTokensField = "maxOutputTokens"
|
||||
if r.GoogleGenerativeAI.ThinkingMode == GoogleThinkingNone {
|
||||
caps.ThinkingLevels = []api.ReasoningEffort{}
|
||||
return caps
|
||||
}
|
||||
case api.APIOllama:
|
||||
caps.ThinkingFormat = "think"
|
||||
caps.MaxTokensField = "num_predict"
|
||||
}
|
||||
caps.ThinkingLevels = r.ThinkingLevels.SupportedLevels()
|
||||
return caps
|
||||
}
|
||||
|
|
@ -0,0 +1,368 @@
|
|||
// Package catalog is the model/vendor directory. It answers one question for
|
||||
// the rest of the system: "given a provider id, a model name and whatever the
|
||||
// operator configured, how exactly do we talk to this model?"
|
||||
//
|
||||
// Facts come from three layers, lowest precedence first:
|
||||
// 1. built-in vendor packages under internal/models/vendors (vendor.go +
|
||||
// models.json + icon.svg), registered through Register;
|
||||
// 2. the deployment overlay config/models.json (same schema as pi's
|
||||
// ~/.pi/agent/models.json): new vendors, base URL / key overrides,
|
||||
// per-model overrides;
|
||||
// 3. per-model overrides stored on the models table.
|
||||
//
|
||||
// Resolve merges those layers into a Resolved value that the protocol
|
||||
// packages consume verbatim. No protocol or vendor package is imported here.
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/api"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// AuthStyle names how a vendor expects credentials.
|
||||
type AuthStyle string
|
||||
|
||||
const (
|
||||
// AuthBearer sends Authorization: Bearer <key>.
|
||||
AuthBearer AuthStyle = "bearer"
|
||||
// AuthAPIKeyHeader sends api-key: <key> (Azure OpenAI).
|
||||
AuthAPIKeyHeader AuthStyle = "api-key"
|
||||
// AuthXAPIKey sends x-api-key: <key> (Anthropic).
|
||||
AuthXAPIKey AuthStyle = "x-api-key"
|
||||
// AuthGoogleAPIKey sends x-goog-api-key: <key> (Gemini native).
|
||||
AuthGoogleAPIKey AuthStyle = "x-goog-api-key"
|
||||
// AuthNone sends nothing (local deployments).
|
||||
AuthNone AuthStyle = "none"
|
||||
// AuthSigned delegates to the vendor's Signer hook (WeKnora Cloud).
|
||||
AuthSigned AuthStyle = "signed"
|
||||
)
|
||||
|
||||
// ExtraField describes one vendor-specific configuration input the model
|
||||
// editor renders dynamically (Azure api-version, LKEAP secret key, ...).
|
||||
type ExtraField struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Labels map[string]string `json:"labels,omitempty"`
|
||||
Type string `json:"type"` // "string", "number", "boolean", "select", "password"
|
||||
Required bool `json:"required"`
|
||||
Default string `json:"default,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Options []ExtraFieldOption `json:"options,omitempty"`
|
||||
// ModelTypes restricts the field to some model types; empty means all.
|
||||
ModelTypes []types.ModelType `json:"model_types,omitempty"`
|
||||
// Secret marks values that must never be echoed back to the UI.
|
||||
Secret bool `json:"secret,omitempty"`
|
||||
}
|
||||
|
||||
// CredentialLabel renames the primary credential input for one vendor.
|
||||
//
|
||||
// Most vendors take an API key and need none of this. LKEAP and Volcengine
|
||||
// authenticate their rerank API with a CAM / IAM identity pair instead, where
|
||||
// the first field is a SecretId / AccessKeyId — calling it "API Key" leads
|
||||
// operators to paste an `sk-` token that can never authenticate. The vendor
|
||||
// says what the field is called rather than the editor hardcoding a table of
|
||||
// vendor ids, which is what this whole layer exists to avoid.
|
||||
type CredentialLabel struct {
|
||||
Label string `json:"label"`
|
||||
Labels map[string]string `json:"labels,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Placeholders map[string]string `json:"placeholders,omitempty"`
|
||||
// Hint is rendered under the input, for a warning the label cannot carry.
|
||||
Hint string `json:"hint,omitempty"`
|
||||
Hints map[string]string `json:"hints,omitempty"`
|
||||
// ModelTypes restricts the override; empty means every type.
|
||||
ModelTypes []types.ModelType `json:"model_types,omitempty"`
|
||||
// Required marks the credential mandatory even where the generic label
|
||||
// calls it optional.
|
||||
Required bool `json:"required,omitempty"`
|
||||
}
|
||||
|
||||
// LocalizedLabel / LocalizedPlaceholder / LocalizedHint resolve one locale,
|
||||
// falling back to the default string.
|
||||
func (c CredentialLabel) LocalizedLabel(locale string) string {
|
||||
return localizedOr(c.Labels, locale, c.Label)
|
||||
}
|
||||
|
||||
// LocalizedPlaceholder resolves the placeholder for a locale.
|
||||
func (c CredentialLabel) LocalizedPlaceholder(locale string) string {
|
||||
return localizedOr(c.Placeholders, locale, c.Placeholder)
|
||||
}
|
||||
|
||||
// LocalizedHint resolves the hint for a locale.
|
||||
func (c CredentialLabel) LocalizedHint(locale string) string {
|
||||
return localizedOr(c.Hints, locale, c.Hint)
|
||||
}
|
||||
|
||||
func localizedOr(table map[string]string, locale, fallback string) string {
|
||||
if v, ok := table[locale]; ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// CredentialLabelFor returns the credential naming for a model type, or nil
|
||||
// when the vendor uses the generic API-key wording.
|
||||
func (v *Vendor) CredentialLabelFor(modelType types.ModelType) *CredentialLabel {
|
||||
for i := range v.CredentialLabels {
|
||||
c := &v.CredentialLabels[i]
|
||||
if len(c.ModelTypes) == 0 {
|
||||
return c
|
||||
}
|
||||
for _, mt := range c.ModelTypes {
|
||||
if mt == modelType {
|
||||
return c
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExtraFieldOption is one choice of a select field.
|
||||
type ExtraFieldOption struct {
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// ModelCost is priced per million tokens, in USD unless Currency says otherwise.
|
||||
type ModelCost struct {
|
||||
Input float64 `json:"input"`
|
||||
Output float64 `json:"output"`
|
||||
CacheRead float64 `json:"cache_read,omitempty"`
|
||||
CacheWrite float64 `json:"cache_write,omitempty"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
}
|
||||
|
||||
// ModelSpec is one entry of a vendor's models.json.
|
||||
//
|
||||
// Only ID is required. API defaults to the vendor's API; Type defaults to
|
||||
// KnowledgeQA. Compat is interpreted according to API (see compat.go).
|
||||
type ModelSpec struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
// Type is the WeKnora model type this entry describes. Chat models with
|
||||
// image input are still KnowledgeQA; the UI derives VLM eligibility from
|
||||
// Input. Embedding / Rerank / ASR entries exist for the model picker.
|
||||
Type types.ModelType `json:"type,omitempty"`
|
||||
API api.API `json:"api,omitempty"`
|
||||
// Aliases are additional ids that resolve to this entry (dated
|
||||
// snapshots, vendor-prefixed names on gateways).
|
||||
Aliases []string `json:"aliases,omitempty"`
|
||||
// Match is a case-insensitive glob ("gpt-5*", "*deepseek-r1*") that lets
|
||||
// one entry describe a family. Exact ids and aliases win over patterns;
|
||||
// among patterns the longest literal prefix wins.
|
||||
Match string `json:"match,omitempty"`
|
||||
// Reasoning reports whether the model can emit thinking at all.
|
||||
Reasoning bool `json:"reasoning"`
|
||||
// Input lists accepted modalities: text, image, audio, video.
|
||||
Input []string `json:"input,omitempty"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
Cost *ModelCost `json:"cost,omitempty"`
|
||||
// ThinkingLevels maps protocol-neutral levels to vendor values; missing
|
||||
// keys inherit the vendor map. See api.ThinkingLevelMap.
|
||||
ThinkingLevels api.ThinkingLevelMap `json:"thinking_levels,omitempty"`
|
||||
// Compat is the protocol-specific overlay for this model (flat object,
|
||||
// fields depend on API). Decoded lazily by Resolve.
|
||||
Compat json.RawMessage `json:"compat,omitempty"`
|
||||
// Dimension is the embedding vector width (embedding entries only).
|
||||
Dimension int `json:"dimension,omitempty"`
|
||||
// Deprecated hides the entry from pickers but keeps resolution working.
|
||||
Deprecated bool `json:"deprecated,omitempty"`
|
||||
// Source is the documentation URL the facts were taken from.
|
||||
Source string `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
// DisplayName returns Name or the id.
|
||||
func (m ModelSpec) DisplayName() string {
|
||||
if m.Name != "" {
|
||||
return m.Name
|
||||
}
|
||||
return m.ID
|
||||
}
|
||||
|
||||
// AcceptsImages reports whether Input lists image.
|
||||
func (m ModelSpec) AcceptsImages() bool {
|
||||
for _, in := range m.Input {
|
||||
if in == "image" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Credentials is what the operator stored for one model row.
|
||||
type Credentials struct {
|
||||
APIKey string
|
||||
AppID string
|
||||
AppSecret string
|
||||
}
|
||||
|
||||
// EndpointRequest is the input to a vendor's Endpoint hook.
|
||||
type EndpointRequest struct {
|
||||
BaseURL string
|
||||
Model string
|
||||
ModelType types.ModelType
|
||||
API api.API
|
||||
Extra map[string]string
|
||||
}
|
||||
|
||||
// Vendor is one model vendor / gateway / self-hosted runtime.
|
||||
type Vendor struct {
|
||||
// ID is the stable identifier stored in models.parameters.provider.
|
||||
ID string
|
||||
// Name is the brand name; Names carries localized variants keyed by
|
||||
// locale ("zh-CN"). Description / Descriptions likewise.
|
||||
Name string
|
||||
Names map[string]string
|
||||
Description string
|
||||
Descriptions map[string]string
|
||||
Website string
|
||||
// Icon is the brand mark as SVG bytes (served inline to the UI).
|
||||
Icon []byte
|
||||
// API is the default chat protocol; a ModelSpec may override it.
|
||||
API api.API
|
||||
// DefaultBaseURLs by model type; GetDefaultURL falls back to chat.
|
||||
DefaultBaseURLs map[types.ModelType]string
|
||||
ModelTypes []types.ModelType
|
||||
RequiresAuth bool
|
||||
Auth AuthStyle
|
||||
// AuthByAPI overrides Auth for one protocol. A vendor that exposes a
|
||||
// second protocol on a sub-path may authenticate it differently: Gemini's
|
||||
// OpenAI-compatible facade documents Authorization: Bearer while the
|
||||
// native generateContent API takes x-goog-api-key. Protocols absent from
|
||||
// the map use Auth.
|
||||
AuthByAPI map[api.API]AuthStyle
|
||||
// URLPatterns are substrings of a base URL that identify this vendor
|
||||
// when the operator left provider empty (legacy rows).
|
||||
URLPatterns []string
|
||||
ExtraFields []ExtraField
|
||||
// CredentialLabels rename the primary credential input per model type.
|
||||
CredentialLabels []CredentialLabel
|
||||
// Compat holds vendor-level protocol defaults.
|
||||
Compat VendorCompat
|
||||
// ThinkingLevels is the vendor-level level map.
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
// Models is the built-in catalog (from models.json).
|
||||
Models []ModelSpec
|
||||
// Order sorts the vendor list in the UI (lower first).
|
||||
Order int
|
||||
|
||||
// Endpoint, when set, computes the request URL instead of the protocol
|
||||
// default (BaseURL + protocol path). Returning "" falls back.
|
||||
Endpoint func(req EndpointRequest) (url string, query map[string]string)
|
||||
// PreferAPI, when set, may switch the protocol for a base URL / model
|
||||
// pair after URL inference ran (OpenAI uses Responses on its own host
|
||||
// and Chat Completions on relays). Returning "" keeps the current choice.
|
||||
PreferAPI func(baseURL string, spec ModelSpec) api.API
|
||||
// Signer, when set (AuthSigned), builds the request signer from the
|
||||
// stored credentials.
|
||||
Signer func(creds Credentials) api.AuthFunc
|
||||
// Validate checks a configuration before it is saved or used. Nil means
|
||||
// the default check (key required when RequiresAuth; model name required).
|
||||
Validate func(cfg *Config) error
|
||||
// Headers are static headers sent on every request (vendor betas).
|
||||
Headers map[string]string
|
||||
// DefaultAPIKey is a deployment-level key from config/models.json used
|
||||
// when the model row stores none.
|
||||
DefaultAPIKey string
|
||||
}
|
||||
|
||||
// Config is the operator-supplied configuration of one model row.
|
||||
type Config struct {
|
||||
Provider string
|
||||
BaseURL string
|
||||
APIKey string
|
||||
ModelName string
|
||||
ModelID string
|
||||
ModelType types.ModelType
|
||||
Extra map[string]string
|
||||
}
|
||||
|
||||
// GetDefaultURL returns the default base URL for a model type, falling back
|
||||
// to the chat URL.
|
||||
func (v *Vendor) GetDefaultURL(modelType types.ModelType) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
if url, ok := v.DefaultBaseURLs[modelType]; ok {
|
||||
return url
|
||||
}
|
||||
if url, ok := v.DefaultBaseURLs[types.ModelTypeKnowledgeQA]; ok {
|
||||
return url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SupportsType reports whether the vendor lists the model type.
|
||||
func (v *Vendor) SupportsType(modelType types.ModelType) bool {
|
||||
for _, t := range v.ModelTypes {
|
||||
if t == modelType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LocalizedName returns the name for a locale, falling back to Name.
|
||||
func (v *Vendor) LocalizedName(locale string) string {
|
||||
if n, ok := v.Names[locale]; ok && n != "" {
|
||||
return n
|
||||
}
|
||||
return v.Name
|
||||
}
|
||||
|
||||
// LocalizedDescription returns the description for a locale.
|
||||
func (v *Vendor) LocalizedDescription(locale string) string {
|
||||
if d, ok := v.Descriptions[locale]; ok && d != "" {
|
||||
return d
|
||||
}
|
||||
return v.Description
|
||||
}
|
||||
|
||||
// AuthStyleFor returns the auth style this vendor uses for one protocol,
|
||||
// falling back to the vendor-wide Auth.
|
||||
func (v *Vendor) AuthStyleFor(protocol api.API) AuthStyle {
|
||||
if style, ok := v.AuthByAPI[protocol]; ok && style != "" {
|
||||
return style
|
||||
}
|
||||
return v.Auth
|
||||
}
|
||||
|
||||
// AuthFunc builds the request authenticator for the stored credentials. The
|
||||
// protocol matters because a vendor that serves a second protocol on a
|
||||
// sub-path may authenticate it differently (see Vendor.AuthByAPI).
|
||||
func (v *Vendor) AuthFunc(protocol api.API, creds Credentials) api.AuthFunc {
|
||||
switch v.AuthStyleFor(protocol) {
|
||||
case AuthAPIKeyHeader:
|
||||
return api.HeaderAuth("api-key", creds.APIKey)
|
||||
case AuthXAPIKey:
|
||||
return api.HeaderAuth("x-api-key", creds.APIKey)
|
||||
case AuthGoogleAPIKey:
|
||||
return api.HeaderAuth("x-goog-api-key", creds.APIKey)
|
||||
case AuthNone:
|
||||
return api.NoAuth()
|
||||
case AuthSigned:
|
||||
if v.Signer != nil {
|
||||
return v.Signer(creds)
|
||||
}
|
||||
return api.NoAuth()
|
||||
default:
|
||||
return api.BearerAuth(creds.APIKey)
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateConfig runs the vendor's validation.
|
||||
func (v *Vendor) ValidateConfig(cfg *Config) error {
|
||||
if v.Validate != nil {
|
||||
return v.Validate(cfg)
|
||||
}
|
||||
return defaultValidate(v, cfg)
|
||||
}
|
||||
|
||||
// IconContentType is the media type of vendor icons served inline.
|
||||
const IconContentType = "image/svg+xml"
|
||||
|
||||
// Ptr returns a pointer to v; vendor packages use it to fill overlay structs.
|
||||
func Ptr[T any](v T) *T { return &v }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue