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.

7.5 KB
Raw Blame
import type { RuntimeProcessorResult } from '@lobechat/agent-signal';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
import { DEFAULT_MINI_SYSTEM_AGENT_ITEM, TRACING_SCENARIOS } from '@lobechat/const';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
import {
  AGENT_SIGNAL_FEEDBACK_SATISFACTION_JSON_SCHEMA,
  AGENT_SIGNAL_FEEDBACK_SATISFACTION_PROMPT_VERSION,
  chainAgentSignalAnalyzeIntentFeedbackSatisfaction,
} from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { z } from 'zod';

import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';

import type { AgentSignalBudgetDecision } from '../../budget';
import { classifySatisfaction, transitionToSignals } from '../../processors';
import { defineSourceHandler } from '../../runtime/middleware';
import type { ClassifierDiagnosticsService, SatisfactionClassifierService } from '../../services';
import type { AgentSignalFeedbackSatisfactionStagePayload } from '../types';

const log = debug('lobe-server:agent-signal:feedback-satisfaction:agent');

const FeedbackEvidenceSchema = z.object({
  cue: z.string(),
  excerpt: z.string(),
});

const FeedbackSatisfactionStagePayloadSchema = z.object({
  confidence: z.number().min(0).max(1),
  evidence: z.array(FeedbackEvidenceSchema),
  reason: z.string(),
  result: z.enum(['neutral', 'not_satisfied', 'satisfied']),
});

/**
 * One normalized satisfaction-judge input.
 */
export interface JudgeFeedbackSatisfactionParams {
  message: string;
  serializedContext?: string;
}

/**
 * Minimal interface for one satisfaction-judge agent.
 */
export interface FeedbackSatisfactionJudge {
  /**
   * Judges one feedback message for overall satisfaction only.
   *
   * Use when:
   * - One normalized feedback message needs a stage-local satisfaction result
   *
   * Expects:
   * - `message` is the raw feedback text
   * - `serializedContext` is the optional serialized execution context for the same event
   *
   * Returns:
   * - One semantic satisfaction result with confidence, evidence, and reason
   */
  judgeSatisfaction: (
    params: JudgeFeedbackSatisfactionParams,
  ) => Promise<AgentSignalFeedbackSatisfactionStagePayload>;
}

/**
 * Model configuration for the default satisfaction judge agent.
 */
export interface FeedbackSatisfactionJudgeAgentModelConfig {
  model: string;
  provider: string;
}

/**
 * Options for constructing the feedback satisfaction source handler.
 */
export interface CreateFeedbackSatisfactionJudgePolicyOptions {
  /**
   * Per-user daily cap checked before each classifier call.
   *
   * @default No cap. The server orchestrator wires the Redis-backed daily budget.
   */
  classifierBudget?: () => Promise<AgentSignalBudgetDecision>;
  /** Optional diagnostics sink for malformed structured classifier output. */
  classifierDiagnostics?: ClassifierDiagnosticsService;
  db?: LobeChatDatabase;
  judge?: FeedbackSatisfactionJudge;
  model?: string;
  provider?: string;
  userId?: string;
  workspaceId?: string;
}

/**
 * Model-backed satisfaction judge for Agent Signal feedback analysis.
 *
 * Use when:
 * - The satisfaction stage should rely on one structured model decision
 * - The caller needs stage-local output without domain routing or action planning
 *
 * Expects:
 * - `db` and `userId` point at the same user context as the surrounding Agent Signal runtime
 *
 * Returns:
 * - One validated satisfaction result parsed from structured model output
 */
export class FeedbackSatisfactionJudgeAgentService implements FeedbackSatisfactionJudge {
  private readonly db: LobeChatDatabase;
  private readonly modelConfig: FeedbackSatisfactionJudgeAgentModelConfig;
  private readonly userId: string;
  private readonly workspaceId?: string;

  constructor(
    db: LobeChatDatabase,
    userId: string,
    modelConfig: Partial<FeedbackSatisfactionJudgeAgentModelConfig> = {},
    workspaceId?: string,
  ) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
    this.modelConfig = {
      model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,
      provider: modelConfig.provider ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
    };
  }

  /**
   * Judges one feedback message for overall satisfaction only.
   *
   * Use when:
   * - Agent Signal needs semantic satisfaction analysis before domain routing
   *
   * Expects:
   * - The payload contains only the feedback message and serialized context
   *
   * Returns:
   * - One validated semantic satisfaction result
   */
  async judgeSatisfaction(
    params: JudgeFeedbackSatisfactionParams,
  ): Promise<AgentSignalFeedbackSatisfactionStagePayload> {
    const payload = chainAgentSignalAnalyzeIntentFeedbackSatisfaction(params);
    const modelRuntime = await initModelRuntimeFromDB(
      this.db,
      this.userId,
      this.modelConfig.provider,
      this.workspaceId,
    );

    log(
      'judgeSatisfaction model=%s provider=%s',
      this.modelConfig.model,
      this.modelConfig.provider,
    );

    const result = await modelRuntime.generateObject(
      {
        messages: payload.messages,
        model: this.modelConfig.model,
        schema: AGENT_SIGNAL_FEEDBACK_SATISFACTION_JSON_SCHEMA,
      },
      {
        metadata: { trigger: RequestTrigger.AgentSignal },
        tracing: {
          promptVersion: AGENT_SIGNAL_FEEDBACK_SATISFACTION_PROMPT_VERSION,
          scenario: TRACING_SCENARIOS.SignalFeedbackSatisfaction,
          schemaName: AGENT_SIGNAL_FEEDBACK_SATISFACTION_JSON_SCHEMA.name,
        } satisfies TracingOptions,
      },
    );

    return FeedbackSatisfactionStagePayloadSchema.parse(result);
  }
}

const resolveJudge = (
  options: CreateFeedbackSatisfactionJudgePolicyOptions = {},
): FeedbackSatisfactionJudge => {
  if (options.judge) {
    return options.judge;
  }

  if (!options.db || !options.userId) {
    throw new TypeError(
      'Feedback satisfaction judge requires either an injected judge or both db and userId.',
    );
  }

  return new FeedbackSatisfactionJudgeAgentService(
    options.db,
    options.userId,
    {
      model: options.model,
      provider: options.provider,
    },
    options.workspaceId,
  );
};

/**
 * Creates the source handler for the feedback satisfaction judge.
 *
 * Triggering workflow:
 *
 * `agent.user.message`
 *   -> {@link createFeedbackSatisfactionJudgeProcessor}
 *     -> `signal.feedback.satisfaction`
 *
 * Upstream:
 * - `agent.user.message`
 *
 * Downstream:
 * - configured {@link FeedbackSatisfactionJudge}
 */
export const createFeedbackSatisfactionJudgeProcessor = (
  options: CreateFeedbackSatisfactionJudgePolicyOptions = {},
) => {
  const judge = resolveJudge(options);

  return defineSourceHandler(
    AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
    `${AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage}:feedback-satisfaction-judge`,
    async (source, ctx): Promise<RuntimeProcessorResult | void> => {
      const classifier: SatisfactionClassifierService = {
        async classify(input) {
          const payload = await judge.judgeSatisfaction(input);

          return FeedbackSatisfactionStagePayloadSchema.parse(payload);
        },
      };
      const result = await classifySatisfaction(source, ctx, {
        diagnostics: options.classifierDiagnostics,
        satisfactionBudget: options.classifierBudget,
        satisfactionClassifier: classifier,
      });

      if (result.type === 'continue') {
        return transitionToSignals(result.value).result;
      }

      return result.result;
    },
  );
};