Skip to content

Commit 38776a8

Browse files
author
linyuan.yang
committed
model service
1 parent 1c1f5b7 commit 38776a8

10 files changed

Lines changed: 245 additions & 180 deletions

File tree

‎packages/scorpio.ai/src/Core/utils.ts‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ export function formatError(error: unknown, withStack = false): string {
6464
const e = error as any;
6565
if (!e) return String(error);
6666

67-
const status = e.status ?? e.response?.status ?? e.cause?.status;
67+
const status = e.status ?? e.status_code ?? e.response?.status ?? e.cause?.status ?? e.cause?.status_code;
68+
const statusText = firstText(e.statusText, e.response?.statusText, e.cause?.statusText);
6869
const name = e.name && e.name !== 'Error' ? e.name : undefined;
6970

7071
// 候选错误体来源(按优先级)
@@ -73,6 +74,8 @@ export function formatError(error: unknown, withStack = false): string {
7374
e.response?.data, // axios
7475
e.response?.body, // 部分封装
7576
e.body, // fetch 裸响应体
77+
e.errorDetails, // Gemini SDK
78+
e.details, // 常见 provider 详情字段
7679
e.cause?.error,
7780
e.cause?.response?.data,
7881
];
@@ -86,12 +89,32 @@ export function formatError(error: unknown, withStack = false): string {
8689
// SDK 的 error.message 有时已含详情;只有当它不只是无信息量文本(裸状态码 / "no body" 等)时才采用
8790
const rawMsg = typeof e.message === 'string' ? e.message.trim() : '';
8891
const msg = rawMsg && !isUninformative(rawMsg) ? rawMsg : undefined;
92+
const code = firstText(e.code, e.error?.code, e.response?.data?.code, e.cause?.code);
93+
const type = firstText(e.type, e.error?.type, e.response?.data?.type, e.cause?.type);
94+
const param = firstText(e.param, e.error?.param, e.response?.data?.param);
95+
const requestId = firstText(
96+
e.requestID,
97+
e.request_id,
98+
e.error?.requestID,
99+
e.error?.request_id,
100+
getHeader(e.headers, 'x-request-id'),
101+
getHeader(e.headers, 'request-id'),
102+
getHeader(e.response?.headers, 'x-request-id'),
103+
getHeader(e.response?.headers, 'request-id'),
104+
);
105+
const headersText = describeHeaders(e.headers ?? e.response?.headers);
89106

90107
const parts = [
91108
name,
92109
status ? `status=${status}` : undefined,
110+
statusText ? `statusText=${statusText}` : undefined,
93111
msg,
94112
bodyText ? `body=${bodyText}` : undefined,
113+
code ? `code=${code}` : undefined,
114+
type ? `type=${type}` : undefined,
115+
param ? `param=${param}` : undefined,
116+
requestId ? `requestId=${requestId}` : undefined,
117+
headersText ? `headers=${headersText}` : undefined,
95118
].filter(Boolean);
96119

97120
let text = parts.length ? parts.join(' ') : String(error);
@@ -117,6 +140,8 @@ function isUninformative(text: string): boolean {
117140
const t = text.trim().toLowerCase();
118141
if (!t) return true;
119142
if (/^\d+$/.test(t)) return true; // 纯状态码,如 "400"
143+
if (/^(?:\d+\s+)?status code\s*\(no body\)$/.test(t)) return true;
144+
if (/^\(no status code or body\)$/.test(t)) return true;
120145
return /^(no body|no response|no content|bad request|error|failed|failure|none|null|undefined|\[object object\]|\{\})$/.test(t);
121146
}
122147

@@ -127,16 +152,63 @@ function describeErrorBody(body: any, full = false): string | undefined {
127152
if (typeof body === 'string') {
128153
text = body.trim() || undefined;
129154
} else if (typeof body === 'object') {
130-
// 常见形状:{ error: { message, type } } 或 { message } 或 { error: "..." }
155+
// 常见及兼容接口形状:{ error: { message, type } } / { message } / { msg } / { detail }
131156
const inner = body.error ?? body;
132-
const msg = typeof inner === 'string' ? inner : inner?.message;
157+
const msg = typeof inner === 'string'
158+
? inner
159+
: firstText(inner?.message, inner?.msg, inner?.detail, inner?.error_description, inner?.data?.message);
133160
const type = typeof inner === 'object' ? inner?.type : undefined;
134-
text = [type, msg].filter(Boolean).join(': ') || JSON.stringify(body);
161+
const code = typeof inner === 'object' ? inner?.code : undefined;
162+
// 日志场景保留完整 provider JSON;用户展示场景只取关键摘要,避免把大响应落进消息历史。
163+
text = full
164+
? safeStringify(body)
165+
: [type, code, msg].filter(Boolean).join(': ') || safeStringify(body);
135166
}
136167
if (!text || isUninformative(text)) return undefined;
137168
return full ? text : truncate(text, 800);
138169
}
139170

171+
function firstText(...values: any[]): string | undefined {
172+
for (const value of values) {
173+
if (value == null || value === '') continue;
174+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);
175+
}
176+
return undefined;
177+
}
178+
179+
function getHeader(headers: any, name: string): string | undefined {
180+
if (!headers) return undefined;
181+
try {
182+
if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
183+
const value = headers[name] ?? headers[name.toLowerCase()];
184+
return Array.isArray(value) ? value.join(', ') : firstText(value);
185+
} catch {
186+
return undefined;
187+
}
188+
}
189+
190+
/** 响应头常含 request id / 网关诊断信息;排除 cookie 和认证字段后写入日志。 */
191+
function describeHeaders(headers: any): string | undefined {
192+
if (!headers) return undefined;
193+
try {
194+
const entries: [string, string][] = typeof headers.entries === 'function'
195+
? [...headers.entries()]
196+
: Object.entries(headers).map(([key, value]) => [key, Array.isArray(value) ? value.join(', ') : String(value)]);
197+
const safeEntries = entries.filter(([key]) => !/^(set-cookie|cookie|authorization|proxy-authorization)$/i.test(key));
198+
return safeEntries.length ? safeStringify(Object.fromEntries(safeEntries)) : undefined;
199+
} catch {
200+
return undefined;
201+
}
202+
}
203+
204+
function safeStringify(value: unknown): string {
205+
try {
206+
return JSON.stringify(value);
207+
} catch {
208+
return String(value);
209+
}
210+
}
211+
140212
/**
141213
* 把 error 对象的所有自有属性(含 SDK 常用的非枚举字段,如 status / error / code / response)
142214
* 序列化成 JSON。作为 formatError 抓不到错误体时的兜底,确保能看到原始错误结构。
@@ -158,6 +230,8 @@ function dumpErrorObject(error: unknown): string {
158230
seen.add(val);
159231
if (val instanceof Error) {
160232
out[k] = { name: val.name, message: val.message, ...dumpOwn(val) };
233+
} else if (typeof Headers !== 'undefined' && val instanceof Headers) {
234+
out[k] = Object.fromEntries(val.entries());
161235
} else {
162236
try { out[k] = JSON.parse(JSON.stringify(val)); }
163237
catch { out[k] = dumpOwn(val); }

‎packages/scorpio.ai/src/Model/AnthropicModelService.ts‎

Lines changed: 10 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import { ChatAnthropic } from "@langchain/anthropic";
22
import { createFunctionCallingParser } from "@langchain/core/language_models/structured_output";
33
import { AIMessageChunk, BaseMessage, SystemMessage } from "@langchain/core/messages";
44
import { toJsonSchema } from "@langchain/core/utils/json_schema";
5-
import { IModelService } from "./IModelService";
6-
import type { ModelInvokeOptions, StructuredInvokeOptions } from "./IModelService";
5+
import { ModelServiceBase } from "./ModelServiceBase";
6+
import type { StructuredInvokeOptions } from "./IModelService";
77
import { ModelConfig } from "./types";
88
import { type ChatMessage } from "../Saver/IAgentSaverService";
9-
import { toChatMessage, toBaseMessages } from "../Saver/messageConverter";
9+
import { toBaseMessages } from "../Saver/messageConverter";
1010
import { getInvokeConfig, StructuredOutputMethod, toStructuredInput } from "./structuredOutput";
1111

1212
const enum CachePosition {
@@ -18,19 +18,18 @@ const enum CachePosition {
1818
* Anthropic 模型服务实现
1919
* 封装 @langchain/anthropic 的 ChatAnthropic(Claude 系列)
2020
*/
21-
export class AnthropicModelService implements IModelService {
22-
private model?: ChatAnthropic;
23-
private boundModel?: any;
21+
export class AnthropicModelService extends ModelServiceBase<ChatAnthropic> {
2422
private cacheControl?: { type: "ephemeral" };
2523

26-
constructor(public readonly config: ModelConfig) {
24+
constructor(config: ModelConfig) {
25+
super(config);
2726
if (config.anthropic?.promptCaching) {
2827
this.cacheControl = { type: "ephemeral" };
2928
}
3029
}
3130

32-
initialize(): void {
33-
this.model = new ChatAnthropic({
31+
protected createModel(): ChatAnthropic {
32+
return new ChatAnthropic({
3433
anthropicApiKey: this.config.apiKey,
3534
anthropicApiUrl: this.config.baseURL,
3635
model: this.config.model,
@@ -40,18 +39,8 @@ export class AnthropicModelService implements IModelService {
4039
});
4140
}
4241

43-
async dispose(): Promise<void> {
44-
this.model = undefined;
45-
this.boundModel = undefined;
46-
}
47-
48-
async invoke(prompt: string | ChatMessage[], options?: ModelInvokeOptions): Promise<ChatMessage> {
49-
const m = this.boundModel ?? this.model!;
50-
const input = typeof prompt === 'string' ? prompt : this.applyCache(toBaseMessages(prompt));
51-
const result = await m.invoke(input, {
52-
...(options?.signal && { signal: options.signal }),
53-
});
54-
return toChatMessage(result);
42+
protected override prepareInput(input: string | ChatMessage[]): string | BaseMessage[] {
43+
return typeof input === 'string' ? input : this.applyCache(toBaseMessages(input));
5544
}
5645

5746
bindTools(tools: any[]): void {
@@ -131,23 +120,6 @@ export class AnthropicModelService implements IModelService {
131120
return type === 'enabled' || type === 'adaptive';
132121
}
133122

134-
async stream(messages: string | ChatMessage[], options?: ModelInvokeOptions): Promise<AsyncIterable<ChatMessage>> {
135-
const m = this.boundModel ?? this.model!;
136-
const input = typeof messages === 'string' ? messages : this.applyCache(toBaseMessages(messages));
137-
const lcStream = await m.stream(input, {
138-
...(options?.signal && { signal: options.signal }),
139-
});
140-
return (async function* () {
141-
let accumulated: AIMessageChunk | undefined;
142-
for await (const chunk of lcStream) {
143-
accumulated = accumulated
144-
? accumulated.concat(chunk as AIMessageChunk)
145-
: (chunk as AIMessageChunk);
146-
yield toChatMessage(accumulated);
147-
}
148-
})();
149-
}
150-
151123
private applyCache(messages: BaseMessage[]): BaseMessage[] {
152124
if (!this.cacheControl || messages.length === 0) return messages;
153125

‎packages/scorpio.ai/src/Model/GeminiModelService.ts‎

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,15 @@
11
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
2-
import { IModelService } from "./IModelService";
2+
import { ModelServiceBase } from "./ModelServiceBase";
33
import type { ModelInvokeOptions, StructuredInvokeOptions } from "./IModelService";
4-
import { ModelConfig } from "./types";
54
import { type ChatMessage } from "../Saver/IAgentSaverService";
6-
import { toChatMessage, toBaseMessages } from "../Saver/messageConverter";
75
import { getInvokeConfig, StructuredOutputMethod, toStructuredInput } from "./structuredOutput";
86

97
/**
108
* Google Gemini 模型服务实现
119
* 封装 @langchain/google-genai 的 ChatGoogleGenerativeAI
1210
*/
13-
export class GeminiModelService implements IModelService {
14-
private model?: ChatGoogleGenerativeAI;
15-
private boundModel?: any;
16-
17-
constructor(public readonly config: ModelConfig) {}
18-
19-
initialize(): void {
11+
export class GeminiModelService extends ModelServiceBase<ChatGoogleGenerativeAI> {
12+
protected createModel(): ChatGoogleGenerativeAI {
2013
const opts: Record<string, any> = {
2114
apiKey: this.config.apiKey,
2215
baseUrl: this.config.baseURL,
@@ -25,23 +18,7 @@ export class GeminiModelService implements IModelService {
2518
};
2619
if (this.config.temperature != null) opts.temperature = this.config.temperature;
2720
if (this.config.maxTokens != null) opts.maxOutputTokens = this.config.maxTokens;
28-
this.model = new ChatGoogleGenerativeAI(opts as any);
29-
}
30-
31-
async dispose(): Promise<void> {
32-
this.model = undefined;
33-
this.boundModel = undefined;
34-
}
35-
36-
async invoke(prompt: string | ChatMessage[], options?: ModelInvokeOptions): Promise<ChatMessage> {
37-
const m = this.boundModel ?? this.model!;
38-
const input = typeof prompt === 'string' ? prompt : toBaseMessages(prompt);
39-
const result = await m.invoke(input, options?.signal ? { signal: options.signal } : undefined);
40-
return toChatMessage(result);
41-
}
42-
43-
bindTools(tools: any[]): void {
44-
this.boundModel = this.model!.bindTools(tools);
21+
return new ChatGoogleGenerativeAI(opts as any);
4522
}
4623

4724
async invokeStructured<T = any>(schema: any, prompt: string | ChatMessage[], options?: StructuredInvokeOptions): Promise<T> {
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { AIMessageChunk, type BaseMessage } from "@langchain/core/messages";
2+
import { type BaseChatModel } from "@langchain/core/language_models/chat_models";
3+
import { type StructuredToolInterface } from "@langchain/core/tools";
4+
import { type ChatMessage } from "../Saver/IAgentSaverService";
5+
import { toChatMessage, toBaseMessages } from "../Saver/messageConverter";
6+
import { ModelConfig } from "./types";
7+
import { type IModelService, type ModelInvokeOptions, type StructuredInvokeOptions } from "./IModelService";
8+
9+
/**
10+
* LangChain ChatModel 的公共实现基类。
11+
*
12+
* 统一模型生命周期、消息转换、默认工具绑定和流式 chunk 累积;provider 特有的
13+
* 初始化参数、结构化输出和兼容逻辑留在子类。
14+
*/
15+
export abstract class ModelServiceBase<TModel extends BaseChatModel = BaseChatModel> implements IModelService {
16+
protected model?: TModel;
17+
protected boundModel?: any;
18+
19+
constructor(public readonly config: ModelConfig) {}
20+
21+
protected abstract createModel(): TModel;
22+
23+
initialize(): void {
24+
this.model = this.createModel();
25+
}
26+
27+
async dispose(): Promise<void> {
28+
this.model = undefined;
29+
this.boundModel = undefined;
30+
}
31+
32+
protected prepareInput(input: string | ChatMessage[]): string | BaseMessage[] {
33+
return typeof input === "string" ? input : toBaseMessages(input);
34+
}
35+
36+
protected get activeModel(): any {
37+
if (!this.model) throw new Error(`${this.constructor.name} is not initialized`);
38+
return this.boundModel ?? this.model;
39+
}
40+
41+
async invoke(prompt: string | ChatMessage[], options?: ModelInvokeOptions): Promise<ChatMessage> {
42+
const result = await this.activeModel.invoke(
43+
this.prepareInput(prompt),
44+
options?.signal ? { signal: options.signal } : undefined,
45+
);
46+
return toChatMessage(result);
47+
}
48+
49+
bindTools(tools: StructuredToolInterface[]): void {
50+
if (!this.model) throw new Error(`${this.constructor.name} is not initialized`);
51+
if (!this.model.bindTools) throw new Error(`${this.constructor.name} does not support tools`);
52+
this.boundModel = this.model.bindTools(tools);
53+
}
54+
55+
abstract invokeStructured<T = any>(
56+
schema: any,
57+
prompt: string | ChatMessage[],
58+
options?: StructuredInvokeOptions,
59+
): Promise<T>;
60+
61+
async stream(messages: string | ChatMessage[], options?: ModelInvokeOptions): Promise<AsyncIterable<ChatMessage>> {
62+
const lcStream = await this.activeModel.stream(
63+
this.prepareInput(messages),
64+
options?.signal ? { signal: options.signal } : undefined,
65+
);
66+
return (async function* () {
67+
let accumulated: AIMessageChunk | undefined;
68+
for await (const chunk of lcStream) {
69+
accumulated = accumulated ? accumulated.concat(chunk) : (chunk as AIMessageChunk);
70+
yield toChatMessage(accumulated!);
71+
}
72+
})();
73+
}
74+
}

0 commit comments

Comments
 (0)