🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import type { ModelPerformance, ModelUsage, TracePayload } from '@lobechat/types';
import type { ClientOptions } from 'openai';
import type { LobeBedrockAIParams } from '../providers/bedrock';
import type { LobeCloudflareParams } from '../providers/cloudflare';
import { LobeOpenAI } from '../providers/openai';
import { providerRuntimeMap } from '../runtimeMap';
import type {
ASROptions,
ASRPayload,
ChatCompletionErrorPayload,
ChatMethodOptions,
ChatStreamPayload,
DecisionOptions,
DecisionPayload,
DecisionQuestions,
DecisionResponse,
EmbeddingsOptions,
EmbeddingsPayload,
GenerateObjectOptions,
GenerateObjectPayload,
ModelRequestOptions,
OnFinishData,
PullModelParams,
RouteAttemptIdentity,
TextToSpeechOptions,
TextToSpeechPayload,
UsageReportContext,
} from '../types';
import { AgentRuntimeErrorType } from '../types/error';
import type {
AuthenticatedImageRuntime,
CreateImageMethodOptions,
CreateImagePayload,
} from '../types/image';
import type {
CreateMusicOptions,
CreateMusicPayload,
CreateMusicResult,
MusicPollingRoute,
PollMusicStatusOptions,
} from '../types/music';
import type {
CreateVideoMethodOptions,
CreateVideoPayload,
CreateVideoResponse,
HandleCreateVideoWebhookPayload,
VideoPollingRoute,
} from '../types/video';
import { AgentRuntimeError } from '../utils/createError';
import { getModelType } from '../utils/getModelPricing';
import { createTimingHelpers, getDurationMs } from '../utils/timing';
import { createVideoWithCompletionMode } from '../utils/videoCompletionMode';
import type { LobeRuntimeAI } from './BaseAI';
import { emulateDecision } from './decision/emulate';
const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');
/** Keeps one provider body out of the tracing row's way while staying diagnosable. */
const MAX_TRACED_ERROR_DETAIL = 4000;
/**
* Describes a failed generation for the tracing row.
*
* A provider either rethrows its own error (`.message` carries the body) or throws the
* normalized `ChatCompletionErrorPayload`, which has no `.message` at all — the body sits under
* `.error`. Reading only `.message` therefore drops exactly the cases the error refinement
* normalized, leaving a tracing row that names a bucket (`UpstreamHttpError`) and nothing else.
*/
export const describeGenerateObjectError = (error: {
error?: unknown;
message?: string;
}): string | undefined => {
if (typeof error?.message === 'string' && error.message.length > 0) return error.message;
const body = error?.error;
if (body === undefined || body === null) return undefined;
if (typeof body === 'string') return body.slice(0, MAX_TRACED_ERROR_DETAIL) || undefined;
try {
return JSON.stringify(body).slice(0, MAX_TRACED_ERROR_DETAIL);
} catch {
// Circular or otherwise unserializable payloads still beat recording nothing.
return String(body).slice(0, MAX_TRACED_ERROR_DETAIL);
}
};
const getLobeHubTimingMetadata = (options?: {
metadata?: Record<string, unknown>;
}): Record<string, unknown> | undefined =>
options?.metadata?.provider === 'lobehub' ? options.metadata : undefined;
const getRuntimeProviderId = (runtime: LobeRuntimeAI) =>
'id' in runtime && typeof runtime.id === 'string' ? runtime.id : 'unknown';
const buildGenerateObjectSpeed = (startedAt: number, usage: ModelUsage): ModelPerformance => {
const latency = Math.max(Date.now() - startedAt, 0);
const totalOutputTokens = usage.totalOutputTokens ?? usage.outputTextTokens ?? 0;
const tps =
latency > 0 && totalOutputTokens > 0 ? totalOutputTokens / (latency / 1000) : undefined;
return {
duration: latency,
latency,
tps,
ttft: 0,
};
};
export interface AgentChatOptions {
enableTrace?: boolean;
provider: string;
trace?: TracePayload;
}
export interface ModelRuntimeHooks {
/**
* Runs before the LLM call. Throw to abort (e.g., budget exceeded).
*/
beforeChat?: (payload: ChatStreamPayload, options?: ChatMethodOptions) => Promise<void>;
beforeCreateImage?: (
payload: CreateImagePayload,
options?: CreateImageMethodOptions,
) => Promise<void>;
beforeCreateVideo?: (
payload: CreateVideoPayload,
options?: CreateVideoMethodOptions,
) => Promise<void>;
beforeDecide?: (payload: DecisionPayload, options?: DecisionOptions) => Promise<void>;
beforeEmbeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<void>;
beforeGenerateObject?: (
payload: GenerateObjectPayload,
options?: GenerateObjectOptions,
) => Promise<void>;
beforeTextToSpeech?: (
payload: TextToSpeechPayload,
options?: TextToSpeechOptions,
) => Promise<void>;
beforeTranscribe?: (payload: ASRPayload, options?: ASROptions) => Promise<void>;
/**
* Called when chat() throws. Handle side effects (sanitize, log, DB record).
* The error is re-thrown after the hook completes — callers still handle response formatting.
*/
onChatError?: (
error: ChatCompletionErrorPayload,
context: { options?: ChatMethodOptions; payload: ChatStreamPayload },
) => void | Promise<void>;
/**
* Called after the stream completes. ModelRuntime handles merging into onFinal internally.
* Hook consumers only need to implement the callback — no need to deal with option merging.
*/
onChatFinal?: (
data: OnFinishData,
context: { options?: ChatMethodOptions; payload: ChatStreamPayload },
) => void | Promise<void>;
/**
* Called when a chat stream fails after `chat()` has already returned its response: an
* in-band provider `error` event, or a body read failure such as every routed fallback
* failing mid-stream. `onChatError` never sees these. Same side-effect contract (sanitize,
* log, record, release held reservations).
*
* `onChatFinal` may or may not have run first: a committed attempt delivers it before the
* error surfaces, but a routed fallback whose earlier attempts were discarded and whose last
* attempt failed to start delivers none. Releases here must therefore be no-ops once
* `onChatFinal` has charged the request.
*/
onChatStreamError?: (
error: unknown,
context: { options?: ChatMethodOptions; payload: ChatStreamPayload },
) => void | Promise<void>;
onDecideError?: (
error: ChatCompletionErrorPayload,
context: { options?: DecisionOptions; payload: DecisionPayload },
) => void | Promise<void>;
/**
* Fires once after a successful decision, including when some answers are refusals.
* `usage` is undefined when the provider reports none, so consumers can still settle or
* release anything taken in `beforeDecide`.
*/
onDecideFinal?: (
data: {
latencyMs: number;
/** USD charge reported by the upstream provider. Server-side only, like chat's. */
providerReportedCost?: number;
response: DecisionResponse;
usage?: ModelUsage;
},
context: { options?: DecisionOptions; payload: DecisionPayload },
) => void | Promise<void>;
onEmbeddingsError?: (
error: ChatCompletionErrorPayload,
context: { options?: EmbeddingsOptions; payload: EmbeddingsPayload },
) => void | Promise<void>;
onEmbeddingsFinal?: (
data: { latencyMs?: number; routeAttempt?: RouteAttemptIdentity; usage?: ModelUsage },
context: { options?: EmbeddingsOptions; payload: EmbeddingsPayload },
) => void | Promise<void>;
/**
* Always fires after `generateObject` returns or throws — success or failure.
* Use this for full-lifecycle observability (per-call tracing, prompt analytics).
* Unlike `onGenerateObjectFinal`, this fires regardless of whether the runtime
* surfaces a `usage` callback, so the gap of "succeeded but no usage" is covered.
*
* Hook failures are swallowed and logged — they must not interfere with the response.
*/
onGenerateObjectComplete?: (
data: {
error?: { code?: string; message?: string; stack?: string };
latencyMs: number;
output?: unknown;
success: boolean;
usage?: ModelUsage;
},
context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
) => void | Promise<void>;
onGenerateObjectError?: (
error: ChatCompletionErrorPayload,
context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
) => void | Promise<void>;
onGenerateObjectFinal?: (
data: { routeAttempt?: RouteAttemptIdentity; speed?: ModelPerformance; usage?: ModelUsage },
context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
) => void | Promise<void>;
onTextToSpeechError?: (
error: ChatCompletionErrorPayload,
context: { options?: TextToSpeechOptions; payload: TextToSpeechPayload },
) => void | Promise<void>;
/**
* Fires once after a successful synthesis. `usage` is undefined when the provider
* reports none, so consumers can still settle or release anything taken in
* `beforeTextToSpeech`.
*/
onTextToSpeechFinal?: (
data: { latencyMs: number; routeAttempt?: RouteAttemptIdentity; usage?: ModelUsage },
context: { options?: TextToSpeechOptions; payload: TextToSpeechPayload },
) => void | Promise<void>;
onTranscribeError?: (
error: ChatCompletionErrorPayload,
context: { options?: ASROptions; payload: ASRPayload },
) => void | Promise<void>;
/**
* Fires once after a successful transcription. `usage` is undefined when the
* provider reports none (e.g. duration-billed models), so consumers can still
* settle or release anything taken in `beforeTranscribe`.
*/
onTranscribeFinal?: (
data: { latencyMs: number; routeAttempt?: RouteAttemptIdentity; usage?: ModelUsage },
context: { options?: ASROptions; payload: ASRPayload },
) => void | Promise<void>;
}
export class ModelRuntime {
private _hooks?: ModelRuntimeHooks;
private _runtime: LobeRuntimeAI;
constructor(runtime: LobeRuntimeAI, hooks?: ModelRuntimeHooks) {
this._runtime = runtime;
this._hooks = hooks;
}
/**
* Initiates a chat session with the agent.
*
* @param payload - The payload containing the chat stream data.
* @param options - Optional chat competition options.
* @returns A Promise that resolves to the chat response.
*
* @example - Use without trace
* ```ts
* const agentRuntime = await initializeWithClientStore({ provider, payload });
* const data = payload as ChatStreamPayload;
* return await agentRuntime.chat(data);
* ```
*
* @example - Use Langfuse trace
* ```ts
* // ============ 1. init chat model ============ //
* const agentRuntime = await initAgentRuntimeWithUserPayload(provider, jwtPayload);
* // ============ 2. create chat completion ============ //
* const data = {
* // your trace options here
* } as ChatStreamPayload;
* const tracePayload = getTracePayload(req);
* return await agentRuntime.chat(data, createTraceOptions(data, {
* provider,
* trace: tracePayload,
* }));
* ```
*/
async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {
const metadata = getLobeHubTimingMetadata(options);
const startedAt = Date.now();
if (metadata) {
timing(
'ModelRuntime.chat start model=%s trigger=%s traceId=%s',
payload.model,
metadata.trigger,
metadata.traceId,
);
}
if (typeof this._runtime.chat !== 'function') {
throw AgentRuntimeError.chat({
error: new Error('Chat is not supported by this provider'),
errorType: AgentRuntimeErrorType.ProviderBizError,
provider: payload.provider || 'unknown',
});
}
try {
const hooksStartedAt = Date.now();
// Messages carry the plan between the context engine and server. Keep it off
// vendor payloads, including when a hosted route retries another provider.
const plan = payload.messages?.find(
(message) => message.toolActivationPlan,
)?.toolActivationPlan;
if (plan) {
payload = {
...payload,
messages: payload.messages.map((message) => {
if (!message.toolActivationPlan) return message;
const { toolActivationPlan: _plan, ...rest } = message;
return rest;
}),
};
options = { ...options, toolActivationPlan: plan };
}
const finalOptions = await this.applyHooks(payload, options);
if (metadata) {
timing(
'ModelRuntime.chat hooks done model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(hooksStartedAt),
metadata.traceId,
);
}
const runtimeStartedAt = Date.now();
const response = await this._runtime.chat(payload, finalOptions);
if (metadata) {
timing(
'ModelRuntime.chat runtime done model=%s durationMs=%d totalMs=%d traceId=%s',
payload.model,
getDurationMs(runtimeStartedAt),
getDurationMs(startedAt),
metadata.traceId,
);
}
return response;
} catch (error) {
if (metadata) {
timing(
'ModelRuntime.chat error model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(startedAt),
metadata.traceId,
);
}
if (this._hooks?.onChatError) {
const errorHookStartedAt = Date.now();
await this._hooks.onChatError(error as ChatCompletionErrorPayload, { options, payload });
if (metadata) {
timing(
'ModelRuntime.chat onChatError done model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(errorHookStartedAt),
metadata.traceId,
);
}
}
throw error;
}
}
/**
* Report a chat stream failure that surfaced after `chat()` returned, for callers that consume
* the response. Hook failures are logged so they never replace the stream error itself.
*/
async handleChatStreamError(
error: unknown,
context: { options?: ChatMethodOptions; payload: ChatStreamPayload },
) {
try {
await this._hooks?.onChatStreamError?.(error, context);
} catch (hookError) {
console.error('[ModelRuntime] onChatStreamError hook failed:', hookError);
}
}
/**
* Apply lifecycle hooks: beforeChat (budget check) + onChatFinal (cost tracking callback injection).
*/
private async applyHooks(
payload: ChatStreamPayload,
options?: ChatMethodOptions,
): Promise<ChatMethodOptions | undefined> {
const hookOptions = this._hooks?.beforeChat && !options ? {} : options;
const metadata = getLobeHubTimingMetadata(options);
const beforeChatStartedAt = Date.now();
if (metadata) {
timing(
'ModelRuntime.beforeChat start model=%s trigger=%s traceId=%s',
payload.model,
metadata.trigger,
metadata.traceId,
);
}
try {
await this._hooks?.beforeChat?.(payload, hookOptions);
} catch (error) {
if (metadata) {
timing(
'ModelRuntime.beforeChat error model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(beforeChatStartedAt),
metadata.traceId,
);
}
throw error;
}
if (metadata) {
timing(
'ModelRuntime.beforeChat done model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(beforeChatStartedAt),
metadata.traceId,
);
}
if (!this._hooks?.onChatFinal) return hookOptions;
const hookFn = this._hooks.onChatFinal;
const existingOnFinal = hookOptions?.callback?.onFinal;
return {
...hookOptions,
callback: {
...hookOptions?.callback,
async onFinal(data) {
const finalStartedAt = Date.now();
if (metadata) {
timing(
'ModelRuntime.onChatFinal start model=%s traceId=%s',
payload.model,
metadata.traceId,
);
}
await existingOnFinal?.(data);
try {
await hookFn(data, { options, payload });
if (metadata) {
timing(
'ModelRuntime.onChatFinal done model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(finalStartedAt),
metadata.traceId,
);
}
} catch (e) {
if (metadata) {
timing(
'ModelRuntime.onChatFinal error model=%s durationMs=%d traceId=%s',
payload.model,
getDurationMs(finalStartedAt),
metadata.traceId,
);
}
// Hook failures (billing, tracing) must not interfere with response completion
console.error('[ModelRuntime] onChatFinal hook error:', e);
}
},
},
};
}
async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
const startedAt = Date.now();
let usageCapture: ModelUsage | undefined;
const fireComplete = async (data: {
error?: { code?: string; message?: string; stack?: string };
output?: unknown;
success: boolean;
}) => {
if (!this._hooks?.onGenerateObjectComplete) return;
try {
await this._hooks.onGenerateObjectComplete(
{
error: data.error,
latencyMs: Date.now() - startedAt,
output: data.output,
success: data.success,
usage: usageCapture,
},
{ options, payload },
);
} catch (e) {
// Hook failures must not affect the caller — log and move on.
console.error('[ModelRuntime] onGenerateObjectComplete hook error:', e);
}
};
try {
const hookOptions = this._hooks?.beforeGenerateObject && !options ? {} : options;
await this._hooks?.beforeGenerateObject?.(payload, hookOptions);
const runtimeStartedAt = Date.now();
const needsUsageCapture =
this._hooks?.onGenerateObjectFinal || this._hooks?.onGenerateObjectComplete;
const finalOptions = needsUsageCapture
? {
...hookOptions,
onUsage: async (usage: ModelUsage, context?: UsageReportContext) => {
usageCapture = usage;
const speed = buildGenerateObjectSpeed(runtimeStartedAt, usage);
await hookOptions?.onUsage?.(usage, context);
try {
await this._hooks?.onGenerateObjectFinal?.(
{ routeAttempt: context?.routeAttempt, speed, usage },
{ options, payload },
);
} catch (e) {
// Hook failures (billing, tracing) must not interfere with response completion
console.error('[ModelRuntime] onGenerateObjectFinal hook error:', e);
}
},
}
: hookOptions;
const output = await this._runtime.generateObject!(payload, finalOptions);
await fireComplete({ output, success: true });
return output;
} catch (error) {
if (this._hooks?.onGenerateObjectError) {
await this._hooks.onGenerateObjectError(error as ChatCompletionErrorPayload, {
options,
payload,
});
}
// Providers either throw the structured ChatCompletionErrorPayload
// (has `errorType`) or rethrow the underlying error verbatim — AI SDK
// `AI_*Error` subclasses, Node Errors with `.code`, etc. Try the most
// descriptive identifier first so the tracing row gets a usable code
// instead of falling through to `unknown`.
const err = error as Error & { code?: string; error?: unknown; errorType?: string };
const code = err?.errorType ?? err?.code ?? err?.name ?? err?.constructor?.name;
await fireComplete({
error: { code, message: describeGenerateObjectError(err), stack: err?.stack },
success: false,
});
throw error;
}
}
async createImage(payload: CreateImagePayload, options?: CreateImageMethodOptions) {
const finalOptions = this._hooks?.beforeCreateImage && !options ? {} : options;
await this._hooks?.beforeCreateImage?.(payload, finalOptions);
return this._runtime.createImage?.(payload, finalOptions);
}
async createVideo(
payload: CreateVideoPayload,
options?: CreateVideoMethodOptions,
): Promise<CreateVideoResponse | undefined> {
const finalOptions = this._hooks?.beforeCreateVideo && !options ? {} : options;
await this._hooks?.beforeCreateVideo?.(payload, finalOptions);
if (!this._runtime.createVideo) return;
return createVideoWithCompletionMode(this._runtime, payload, finalOptions);
}
/**
* Generate music with the provider runtime. Returns `undefined` when the provider has no
* music support. Asynchronous providers return a `pending` result with a task id unless
* `options.waitForCompletion` is set; poll it with {@link handlePollMusicStatus}.
*/
async createMusic(
payload: CreateMusicPayload,
options?: CreateMusicOptions,
): Promise<CreateMusicResult | undefined> {
return this._runtime.createMusic?.(payload, options);
}
async handlePollMusicStatus(
inferenceId: string,
model?: string,
route?: MusicPollingRoute,
options?: PollMusicStatusOptions,
) {
return this._runtime.handlePollMusicStatus?.(inferenceId, model, route, options);
}
async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
return this._runtime.handleCreateVideoWebhook?.(payload);
}
async handlePollVideoStatus(inferenceId: string, model?: string, route?: VideoPollingRoute) {
return this._runtime.handlePollVideoStatus?.(inferenceId, model, route);
}
/**
* Verify the provider key without a chat model. `undefined` when the runtime has no
* credential check, so callers can fall back to a chat check.
*/
async checkCredentials() {
return this._runtime.checkCredentials?.();
}
async models() {
return this._runtime.models?.();
}
async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions) {
try {
const hookOptions = this._hooks?.beforeEmbeddings && !options ? {} : options;
await this._hooks?.beforeEmbeddings?.(payload, hookOptions);
const startTime = Date.now();
let usage: ModelUsage | undefined;
let routeAttempt: UsageReportContext['routeAttempt'];
const finalOptions = this._hooks?.onEmbeddingsFinal
? {
...hookOptions,
onUsage: async (reported: ModelUsage, context?: UsageReportContext) => {
usage = reported;
routeAttempt = context?.routeAttempt;
await hookOptions?.onUsage?.(reported, context);
},
}
: hookOptions;
const result = await this._runtime.embeddings?.(payload, finalOptions);
if (this._hooks?.onEmbeddingsFinal) {
try {
await this._hooks.onEmbeddingsFinal(
{ latencyMs: Date.now() - startTime, routeAttempt, usage },
{ options, payload },
);
} catch (e) {
console.error('[ModelRuntime] onEmbeddingsFinal hook error:', e);
}
}
return result;
} catch (error) {
if (this._hooks?.onEmbeddingsError) {
await this._hooks.onEmbeddingsError(error as ChatCompletionErrorPayload, {
options,
payload,
});
}
throw error;
}
}
async textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {
try {
const hookOptions = this._hooks?.beforeTextToSpeech && !options ? {} : options;
await this._hooks?.beforeTextToSpeech?.(payload, hookOptions);
const startTime = Date.now();
let usage: ModelUsage | undefined;
let routeAttempt: RouteAttemptIdentity | undefined;
const finalOptions = this._hooks?.onTextToSpeechFinal
? {
...hookOptions,
onUsage: async (reported: ModelUsage, context?: UsageReportContext) => {
usage = reported;
routeAttempt = context?.routeAttempt;
await hookOptions?.onUsage?.(reported, context);
},
}
: hookOptions;
const result = await this._runtime.textToSpeech?.(payload, finalOptions);
if (this._hooks?.onTextToSpeechFinal) {
try {
await this._hooks.onTextToSpeechFinal(
{ latencyMs: Date.now() - startTime, routeAttempt, usage },
{ options, payload },
);
} catch (e) {
console.error('[ModelRuntime] onTextToSpeechFinal hook error:', e);
}
}
return result;
} catch (error) {
if (this._hooks?.onTextToSpeechError) {
await this._hooks.onTextToSpeechError(error as ChatCompletionErrorPayload, {
options,
payload,
});
}
throw error;
}
}
async transcribe(payload: ASRPayload, options?: ASROptions) {
try {
const hookOptions = this._hooks?.beforeTranscribe && !options ? {} : options;
await this._hooks?.beforeTranscribe?.(payload, hookOptions);
const startTime = Date.now();
let usage: ModelUsage | undefined;
let routeAttempt: RouteAttemptIdentity | undefined;
const finalOptions = this._hooks?.onTranscribeFinal
? {
...hookOptions,
onUsage: async (reported: ModelUsage, context?: UsageReportContext) => {
usage = reported;
routeAttempt = context?.routeAttempt;
await hookOptions?.onUsage?.(reported, context);
},
}
: hookOptions;
const result = await this._runtime.transcribe?.(payload, finalOptions);
if (this._hooks?.onTranscribeFinal) {
try {
await this._hooks.onTranscribeFinal(
{ latencyMs: Date.now() - startTime, routeAttempt, usage },
{ options, payload },
);
} catch (e) {
console.error('[ModelRuntime] onTranscribeFinal hook error:', e);
}
}
return result;
} catch (error) {
if (this._hooks?.onTranscribeError) {
await this._hooks.onTranscribeError(error as ChatCompletionErrorPayload, {
options,
payload,
});
}
throw error;
}
}
/**
* Answer typed questions about one state. A model-bank `type: 'decision'` model on a provider
* with native `decide` answers natively; any other model is emulated through `generateObject`.
* `response.providerMetadata.lobehub.decisionMode` says which path served the call.
*/
async decide<Q extends DecisionQuestions>(
payload: DecisionPayload<Q>,
options?: DecisionOptions,
): Promise<DecisionResponse<Q>> {
const runtime = this._runtime;
const provider = getRuntimeProviderId(runtime);
// A failed model-bank lookup only loses the routing hint: treat the model as unlisted.
const isDecisionModel =
!!runtime.decide &&
(await getModelType(payload.model, provider, options?.pricingContext).catch(
() => undefined,
)) === 'decision';
// Unlike the optional-chained passthroughs above, an unsupported provider must not
// resolve to `undefined`: callers branch on the answers and would read it as a result.
// Thrown before the hooks run, so there is nothing for `onDecideError` to release.
if (!isDecisionModel && !runtime.generateObject) {
throw AgentRuntimeError.chat({
error: new Error('Decision models are not supported by this provider'),
errorType: AgentRuntimeErrorType.CapabilityNotSupported,
provider,
});
}
const decide = (decideOptions?: DecisionOptions) =>
isDecisionModel
? runtime.decide!(payload, decideOptions)
: emulateDecision(payload, decideOptions, {
generateObject: (objectPayload, objectOptions) =>
runtime.generateObject!(objectPayload, objectOptions),
provider,
});
try {
const hookOptions = this._hooks?.beforeDecide && !options ? {} : options;
await this._hooks?.beforeDecide?.(payload, hookOptions);
const startTime = Date.now();
let usage: ModelUsage | undefined;
let providerReportedCost: number | undefined;
const raw = await decide({
...hookOptions,
onProviderReportedCost: async (cost: number) => {
providerReportedCost = cost;
await hookOptions?.onProviderReportedCost?.(cost);
},
onUsage: async (reported: ModelUsage) => {
usage = reported;
await hookOptions?.onUsage?.(reported);
},
});
const response = {
...raw,
providerMetadata: {
...raw.providerMetadata,
lobehub: {
...raw.providerMetadata?.lobehub,
decisionMode: isDecisionModel ? 'native' : 'emulated',
},
},
...((raw.usage ?? usage) && { usage: raw.usage ?? usage }),
} as DecisionResponse<Q>;
if (this._hooks?.onDecideFinal) {
try {
await this._hooks.onDecideFinal(
{ latencyMs: Date.now() - startTime, providerReportedCost, response, usage },
{ options, payload },
);
} catch (e) {
console.error('[ModelRuntime] onDecideFinal hook error:', e);
}
}
return response;
} catch (error) {
if (this._hooks?.onDecideError) {
await this._hooks.onDecideError(error as ChatCompletionErrorPayload, {
options,
payload,
});
}
throw error;
}
}
async pullModel(params: PullModelParams, options?: ModelRequestOptions) {
return this._runtime.pullModel?.(params, options);
}
/**
* Get authentication headers if runtime supports it
*/
getAuthHeaders(): Record<string, string> | undefined {
return (this._runtime as AuthenticatedImageRuntime).getAuthHeaders?.();
}
/**
* @description Initialize the runtime with the provider and the options
* @param provider choose a model provider
* @param params options of the choosed provider
* @param hooks optional hooks for lifecycle interception (billing, etc.)
* @returns the runtime instance
* Try to initialize the runtime with the provider and the options.
* @example
* ```ts
* const runtime = await AgentRuntime.initializeWithProviderOptions(provider, options)
* ```
* **Note**: If you try to get a AgentRuntime instance from client or server,
* you should use the methods to get the runtime instance at first.
* - `src/app/api/chat/agentRuntime.ts: initAgentRuntimeWithUserPayload` on server
* - `src/services/chat.ts: initializeWithClientStore` on client
*/
static initializeWithProvider(
provider: string,
params: Partial<
ClientOptions &
LobeBedrockAIParams &
LobeCloudflareParams & {
apiKey?: string;
baseURL?: string;
userId?: string;
workspaceId?: string;
}
>,
hooks?: ModelRuntimeHooks,
) {
return new ModelRuntime(ModelRuntime.createProviderRuntime(provider, params), hooks);
}
/**
* Construct the bare provider implementation without wrapping it in a
* ModelRuntime, so callers can decorate it (e.g. the server's SSRF guard)
* before attaching hooks.
*/
static createProviderRuntime(
provider: string,
params: Parameters<typeof ModelRuntime.initializeWithProvider>[1],
): LobeRuntimeAI {
// runtime map does not include every provider id (e.g. vertex), so index loosely
const runtimeMap: Partial<Record<string, new (params: any) => LobeRuntimeAI>> =
providerRuntimeMap;
const providerAI = runtimeMap[provider] ?? LobeOpenAI;
return new providerAI(params);
}
}