version: 2
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* 传输层唯一出口 —— Phase 1 / Phase 2 的接缝。
|
||||
*
|
||||
* ── 这里放什么 ───────────────────────────────────────────────────────────
|
||||
* 凡是**换阶段就会变**的东西,全部收敛在本文件:
|
||||
* - 端点解析 `normalizeBaseUrl`
|
||||
* - 凭据来源 `buildHeaders`
|
||||
* - 请求体构造 `createRequestPayload`
|
||||
* - 请求生命周期 `sendChatRequest`(客户端超时 + AbortController 接线)
|
||||
* - 状态码释义 `mapHttpError`(HTTP 语义属于传输层,不是 UI 层)
|
||||
*
|
||||
* ── 这里不放什么 ─────────────────────────────────────────────────────────
|
||||
* - **SSE 解析**:`handleStreamResponse` / `handleNormalResponse` 留在
|
||||
* `services/chat.ts`。它们是 Phase 1/2/3 共用的正确实现,**不要动**。
|
||||
* - **任何 UI**:本文件不 import element-plus。传输层只抛错,
|
||||
* 「要不要弹窗、弹什么」由调用方(`services/chat.ts`)决定。
|
||||
*
|
||||
* ── Phase 2 改这里 ───────────────────────────────────────────────────────
|
||||
* 1. 端点:`http://127.0.0.1:3100/v1/chat/completions` → 同源 `/Api/aiChat`
|
||||
* 2. 凭据:`Authorization: Bearer sk-xxx` → **整个删掉**,改由服务端会话承担
|
||||
* 3. `config.apiKey` 字段随之从 `types` 里退役
|
||||
*
|
||||
* 改完这三处,其余文件一行都不用动 —— 这就是抽这一层的全部意义。
|
||||
*
|
||||
* ── 工具调用(tool calling)────────────────────────────────────────────
|
||||
* 工具**定义**是随请求体携带的**纯数据**(`ToolDefinition` / `ToolOptions`),
|
||||
* 就定义在本文件 —— 传输层只负责把它们原样写进请求体,**不知道也不关心
|
||||
* 某个工具是干什么的**。工具的**执行**(模型返回 tool_call 之后怎么响应)
|
||||
* 属于编排层(`services/agent-loop.ts`),不是这一层的事。
|
||||
*
|
||||
* ⚠️ 不得 import `../bridge`(`AGENTS.md §4.2`:JS 桥与传输层必须解耦,
|
||||
* 否则从 CEF 迁到 TEdgeBrowser / WebView2 时页面代码要跟着改)。
|
||||
* 工具**定义**是数据,工具**执行**不是本层的事 —— 两者都别从 bridge 拿。
|
||||
*/
|
||||
|
||||
import type { AppConfig, OpenAIMessage } from '../types'
|
||||
|
||||
/**
|
||||
* 客户端超时。
|
||||
*
|
||||
* 原值 60000(1 分钟) 偏短:策略代码输出经常超过 1 分钟,会被客户端主动 abort,
|
||||
* 表现为「话说一半就停了」。nginx 侧是 proxy_read_timeout 600s,
|
||||
* 这里留足余量但仍低于它,避免客户端比服务端先放弃。
|
||||
*/
|
||||
export const REQUEST_TIMEOUT = 300000
|
||||
|
||||
/**
|
||||
* 工具定义。**形状与 OpenAI 兼容接口一致**,但这里自己定义而不 import
|
||||
* —— 传输层不得依赖 `bridge/`(`AGENTS.md §4.2`)。
|
||||
*/
|
||||
export interface ToolDefinition {
|
||||
type: 'function'
|
||||
function: {
|
||||
name: string
|
||||
description: string
|
||||
/** JSON Schema 形状的对象 */
|
||||
parameters: Record<string, unknown>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具选择策略。
|
||||
* - `auto` 模型自己决定调不调
|
||||
* - `required` **强制**调一次(实测 agnes 支持,且它对每个请求都强制 ⇒ 慎用)
|
||||
* - `{ type:'function', function:{ name } }` 指定某一个
|
||||
*/
|
||||
export type ToolChoice = 'auto' | 'required' | { type: 'function'; function: { name: string } }
|
||||
|
||||
/** 一次请求携带的工具与选择策略。`undefined` = 本次请求不带工具。 */
|
||||
export interface ToolOptions {
|
||||
tools?: ToolDefinition[]
|
||||
toolChoice?: ToolChoice
|
||||
}
|
||||
|
||||
/**
|
||||
* 传输层错误。**不弹窗**,只携带足够调用方决定提示策略的信息。
|
||||
*
|
||||
* `kind` 是提示策略的唯一依据:
|
||||
* - `abort` 用户主动中断 —— 静默,由调用方走「已停止」分支
|
||||
* - `network` 跨域 / 连不上 —— 必须提示,否则用户只看到「没反应」
|
||||
* - `http` 服务端返回了非 2xx —— 必须提示,message 已译成人话
|
||||
* - `unknown` 兜底
|
||||
*/
|
||||
export type TransportErrorKind = 'abort' | 'network' | 'http' | 'unknown'
|
||||
|
||||
export class ChatTransportError extends Error {
|
||||
readonly kind: TransportErrorKind
|
||||
/** 仅 `kind === 'http'` 时有值 */
|
||||
readonly status: number | undefined
|
||||
|
||||
constructor(kind: TransportErrorKind, message: string, status?: number) {
|
||||
super(message)
|
||||
this.name = 'ChatTransportError'
|
||||
this.kind = kind
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
/** Phase 1:凭据由调用方(注入的 DEFAULT_CONFIG)提供。Phase 2:这里整个删掉。 */
|
||||
function buildHeaders(apiKey: string): HeadersInit {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeBaseUrl(baseUrl: string): string {
|
||||
const normalized = baseUrl.trim().replace(/\/+$/, '')
|
||||
if (/\/chat\/completions$/i.test(normalized)) {
|
||||
return normalized
|
||||
}
|
||||
|
||||
const apiBase = /\/v\d+$/i.test(normalized) ? normalized : `${normalized}/v1`
|
||||
return `${apiBase}/chat/completions`
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取 one-api 当前令牌可用的模型列表(GET /v1/models,OpenAI 兼容格式)。
|
||||
* 返回模型名数组(按服务端返回顺序)。失败时返回空数组(静默降级,
|
||||
* 调用方看到空数组知道拉取失败,不会阻塞主流程)。
|
||||
*/
|
||||
export async function fetchAvailableModels(config: AppConfig): Promise<string[]> {
|
||||
try {
|
||||
// normalizeBaseUrl 返回 ".../chat/completions" —— /v1/models 需要的是 base 段
|
||||
// 截掉 /chat/completions 后拼上 /models
|
||||
const base = normalizeBaseUrl(config.baseUrl).replace(/\/chat\/completions$/i, '')
|
||||
const url = `${base}/models`
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: buildHeaders(config.apiKey),
|
||||
})
|
||||
if (!response.ok) return []
|
||||
const data = (await response.json()) as { data?: Array<{ id: string }> }
|
||||
return Array.isArray(data?.data) ? data.data.map((m) => m.id) : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function mapHttpError(status: number, text: string): string {
|
||||
if (status === 400) return text || '请求参数错误,请检查模型参数配置'
|
||||
if (status === 401) return '鉴权失败,请检查 API Key 是否正确'
|
||||
if (status === 403) return '当前密钥无访问权限,请检查接口授权'
|
||||
if (status === 404) return '接口地址错误,请检查 BaseURL 是否正确'
|
||||
if (status === 408) return '请求超时,请稍后重试'
|
||||
if (status === 429) return '请求超限,请稍后重试'
|
||||
if (status >= 500) return '服务端异常,请检查模型服务状态'
|
||||
return text || `请求失败,状态码:${status}`
|
||||
}
|
||||
|
||||
async function parseErrorResponse(response: Response): Promise<string> {
|
||||
try {
|
||||
const contentType = response.headers.get('content-type') || ''
|
||||
if (contentType.includes('application/json')) {
|
||||
const data = (await response.json()) as { error?: { message?: string }; message?: string }
|
||||
return data?.error?.message || data?.message || ''
|
||||
}
|
||||
|
||||
return (await response.text()).slice(0, 300)
|
||||
} catch (_error) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function createRequestPayload(config: AppConfig, messages: OpenAIMessage[], toolOptions?: ToolOptions) {
|
||||
const payload: Record<string, unknown> = {
|
||||
// model 为空 ⇒ 省略该字段(正常流程下 model 不会为空,store 的 effectiveConfig 会用拉取到的第一个模型填充)
|
||||
...(config.model ? { model: config.model } : {}),
|
||||
messages,
|
||||
temperature: Number(config.temperature),
|
||||
max_tokens: Number(config.maxTokens),
|
||||
stream: config.stream,
|
||||
}
|
||||
|
||||
// ⚠️ 只在真的带了工具时才写这两个字段。
|
||||
// 写 `tools: []` 会被部分网关当成「有工具但没有可选」,行为与「不带工具」不同。
|
||||
if (toolOptions?.tools?.length) {
|
||||
payload.tools = toolOptions.tools
|
||||
if (toolOptions.toolChoice) {
|
||||
payload.tool_choice = toolOptions.toolChoice
|
||||
}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出请求,成功即把 `Response` 原样交出去。
|
||||
*
|
||||
* **非 2xx 在这里就抛掉**,返回的 `Response` 必定是 ok 的 —— 这样调用方的
|
||||
* 解析分支不必再判一次状态码。
|
||||
*
|
||||
* 超时与「用户主动停止」共用一个 `AbortController`:外部 `signal` 只触发 abort,
|
||||
* 谁触发的无所谓,统一由 `toTransportError` 按 `AbortError` 译成 `kind: 'abort'`。
|
||||
*/
|
||||
export async function sendChatRequest(
|
||||
config: AppConfig,
|
||||
messages: OpenAIMessage[],
|
||||
signal?: AbortSignal,
|
||||
toolOptions?: ToolOptions,
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timeoutId = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT)
|
||||
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', () => controller.abort(), { once: true })
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(normalizeBaseUrl(config.baseUrl), {
|
||||
method: 'POST',
|
||||
headers: buildHeaders(config.apiKey),
|
||||
body: JSON.stringify(createRequestPayload(config, messages, toolOptions)),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await parseErrorResponse(response)
|
||||
throw new ChatTransportError('http', mapHttpError(response.status, errorText), response.status)
|
||||
}
|
||||
|
||||
return response
|
||||
} catch (error: unknown) {
|
||||
throw toTransportError(error)
|
||||
} finally {
|
||||
window.clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
|
||||
function toTransportError(error: unknown): ChatTransportError {
|
||||
// 非 2xx 已经是 ChatTransportError,原样上抛,别把状态码信息洗掉
|
||||
if (error instanceof ChatTransportError) return error
|
||||
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
return new ChatTransportError('abort', '请求已停止')
|
||||
}
|
||||
|
||||
if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
|
||||
return new ChatTransportError('network', '网络异常、跨域受限或接口地址错误,请检查 BaseURL')
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ChatTransportError('unknown', error.message || '请求失败')
|
||||
}
|
||||
|
||||
return new ChatTransportError('unknown', '请求失败,请稍后重试')
|
||||
}
|
||||
Reference in New Issue
Block a user