Skip to content

🀯 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.

6.4 KB
Raw Blame
import type {
  ChatCompletionTool,
  ChatStreamPayload,
  DecisionPayload,
  DecisionQuestions,
  DecisionResponse,
  GenerateObjectPayload,
  GenerateObjectSchema,
  OnFinishData,
} from '@lobechat/model-runtime';
import type { ModelUsage, OpenAIChatMessage, RequestTrigger } from '@lobechat/types';

import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';

export interface AiGenerationObjectInput {
  messages: OpenAIChatMessage[] | GenerateObjectPayload['messages'];
  model: string;
  provider: string;
  schema?: GenerateObjectSchema;
  thinking?: GenerateObjectPayload['thinking'];
  tools?: ChatCompletionTool[];
}

export interface AiGenerationTextInput {
  maxTokens?: number;
  messages: OpenAIChatMessage[];
  model: string;
  provider: string;
  temperature?: number;
}

export interface AiGenerationTextResult {
  finishReason?: string;
  /** The model's reasoning, kept apart from `text` (reasoning models only). */
  reasoning?: string;
  text: string;
  usage?: ModelUsage;
}

export interface AiGenerationDecisionInput<
  Q extends DecisionQuestions = DecisionQuestions,
> extends DecisionPayload<Q> {
  provider: string;
}

export interface AiGenerationObjectOptions {
  /**
   * Context forwarded to non-tracing hooks (billing, routing). Use `tracing`
   * instead for `llm_generation_tracing` config.
   *
   * `trigger` is required: it is the feature recorded on spend / route-attempt
   * logs, and a missing one leaves the usage unattributed. It names the feature
   * (e.g. `task`), not the prompt β€” the prompt goes in `tracing.scenario`.
   */
  metadata: Record<string, unknown> & { trigger: RequestTrigger };
  signal?: AbortSignal;
  /**
   * Structured tracing config (scenario / promptVersion / schemaName /
   * agentId / topicId / inputHint / ...). Forwarded to the
   * `llm_generation_tracing` hook. Strongly typed by `TracingOptions` from
   * `@lobechat/llm-generation-tracing` at call sites.
   */
  tracing?: Record<string, unknown>;
}

/**
 * Thin wrapper around `initModelRuntimeForRequest` + `ModelRuntime.generateObject`.
 *
 * Almost every server-side caller that produces structured output goes through
 * the same two-step dance: resolve the user's provider config from the DB,
 * then call generateObject with caller-specific metadata. This service exists
 * so those call sites don't repeat the init wiring, and so adding a future
 * cross-cutting concern (default metadata, retries, observability defaults)
 * has one place to land.
 *
 * Construct one per request β€” `db` and `userId` come from the request context.
 *
 * A provider only the user's device reaches (Ollama, LM Studio, a private base
 * URL; `agent_llm_relay` on) is relayed to the browser tab that sent the
 * request; with no such tab β€” a bot, a workflow, deferred work β€” the call
 * fails at once with `ClientLlmExecutorUnavailable` (`no_executor`).
 */
export class AiGenerationService {
  private readonly db: LobeChatDatabase;
  private readonly userId: string;
  private readonly workspaceId?: string;

  constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
  }

  async generateObject<T = unknown>(
    input: AiGenerationObjectInput,
    options: AiGenerationObjectOptions,
  ): Promise<T> {
    const runtime = await initModelRuntimeForRequest(this.db, this.userId, input.provider, {
      workspaceId: this.workspaceId,
    });
    return (await runtime.generateObject(
      {
        messages: input.messages as GenerateObjectPayload['messages'],
        model: input.model,
        schema: input.schema,
        thinking: input.thinking,
        tools: input.tools,
      },
      { metadata: options.metadata, signal: options.signal, tracing: options.tracing },
    )) as T;
  }

  /**
   * One plain-text completion: the answer text, with any reasoning, usage and
   * finish reason reported separately (nothing is spliced into `text`).
   *
   * Runs on the server only, like {@link decide}: the stream is consumed here
   * and `onFinal` carries the assembled result, so providers that only stream
   * behave the same as those that do not.
   */
  async generateText(
    input: AiGenerationTextInput,
    options: AiGenerationObjectOptions,
  ): Promise<AiGenerationTextResult> {
    const runtime = await initModelRuntimeFromDB(
      this.db,
      this.userId,
      input.provider,
      this.workspaceId,
    );
    const payload: ChatStreamPayload = {
      max_tokens: input.maxTokens,
      messages: input.messages as ChatStreamPayload['messages'],
      model: input.model,
      stream: true,
      temperature: input.temperature ?? 1,
    };

    let final: OnFinishData | undefined;
    let streamError: unknown;
    const response = await runtime.chat(payload, {
      callback: {
        onError: (error) => {
          streamError = error;
        },
        onFinal: (data) => {
          final = data;
        },
      },
      metadata: options.metadata,
      signal: options.signal,
    });
    // Drain the stream so the callbacks (and billing / tracing hooks) run.
    await response.body?.pipeTo(new WritableStream());

    if (streamError ?? final?.error) throw streamError ?? final!.error;
    if (!final) throw new Error('The model stream ended without a final result');

    return {
      finishReason: final.finishReason,
      reasoning: final.thinking || final.reasoning?.content || undefined,
      text: final.text,
      usage: final.usage,
    };
  }

  /**
   * Asks typed questions about one state (`ModelRuntime.decide`): natively for decision models,
   * emulated through `generateObject` for chat models.
   *
   * Always called from the server: the device relay {@link generateObject} may use has no
   * decision call. A provider with neither rejects with `CapabilityNotSupported`.
   */
  async decide<Q extends DecisionQuestions>(
    input: AiGenerationDecisionInput<Q>,
    options: AiGenerationObjectOptions,
  ): Promise<DecisionResponse<Q>> {
    const runtime = await initModelRuntimeFromDB(
      this.db,
      this.userId,
      input.provider,
      this.workspaceId,
    );
    return runtime.decide(
      { model: input.model, questions: input.questions, state: input.state },
      { metadata: options.metadata, signal: options.signal, tracing: options.tracing },
    );
  }
}