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.

✨ feat(cli): add lh gen decide for decision models (#21835)

Arvin Xu6529cd5d1633
diff --git a/.agents/skills/cli/references/generate.md b/.agents/skills/cli/references/generate.md
index 7b9956f3429..31363462374 100644
--- a/.agents/skills/cli/references/generate.md
+++ b/.agents/skills/cli/references/generate.md
@@ -9,6 +9,8 @@ Generate text, images, videos, speech, and transcriptions.
```
lh generate (alias: gen)
β”œβ”€β”€ text <prompt> # Text generation
+β”œβ”€β”€ json <prompt> # Structured output (JSON Schema)
+β”œβ”€β”€ decide [state] # Decision model: typed questions β†’ probabilities
β”œβ”€β”€ image <prompt> # Image generation
β”œβ”€β”€ video <prompt> # Video generation
β”œβ”€β”€ tts <text> # Text-to-speech
@@ -90,6 +92,39 @@ rejected up front.
---
+## `lh generate decide [state]` / `lh gen decide [state]`
+
+Ask a decision model (e.g. Jev) typed questions about one state. Each answer comes back as a probability,
+not generated text: `boolean` β†’ `probability`, `choice` β†’ the picked option with `probabilities`, `score`
+β†’ a rubric level.
+
+**Source**: `apps/cli/src/commands/generate/decide.ts`
+
+```bash
+lh gen decide [state] -m <model> -q <json|path> [-p <provider>] [--state-file <path>] [--pipe]
+```
+
+```bash
+lh gen decide "Newest message: is the queue mode ready?" -m lobehub/jev-1.14.0 \
+ -q '{"addressed":{"type":"boolean","instructions":"Is the message directed at the assistant?"}}'
+```
+
+| Option | Description | Default |
+| ------------------------------ | ----------------------------------------------------------------------- | ------- |
+| `-m, --model <model>` | Decision model ID, `provider/model` (required) | - |
+| `-p, --provider <provider>` | Provider name | - |
+| `-q, --questions <json\|path>` | Question name β†’ `{type, instructions, criteria}`, inline or from a file | - |
+| `--state-file <path>` | Read the state from a file instead of the argument | - |
+| `--pipe` | Read the state (or more of it) from stdin | `false` |
+
+Question shapes mirror `DecisionQuestion` in `@lobechat/model-runtime`: `boolean` takes optional
+`criteria: {true, false}`, `choice` takes `criteria: {option: guidance | null}`, `score` takes
+`criteria: [level0, level1, ...]`. The command calls the `aiChat.decide` mutation, the same
+`runtime.decide` path bot wake and channel routing use, so a prompt can be replayed on the production
+model. A provider without a decision endpoint fails with `CapabilityNotSupported` and exit code 1.
+
+---
+
## `lh generate image <prompt>` / `lh gen image <prompt>`
Generate images from text prompt. This is an async operation β€” the command submits the task and returns a generation ID + async task ID for tracking.
diff --git a/apps/cli/src/commands/generate.test.ts b/apps/cli/src/commands/generate.test.ts
index d1ee731320b..f96de4d3592 100644
--- a/apps/cli/src/commands/generate.test.ts
+++ b/apps/cli/src/commands/generate.test.ts
@@ -11,6 +11,7 @@ import { registerGenerateCommand } from './generate';
const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
aiChat: {
+ decide: { mutate: vi.fn() },
outputJSON: { mutate: vi.fn() },
},
asr: {
@@ -336,6 +337,153 @@ describe('generate command', () => {
});
});
+ describe('decide', () => {
+ const questions = {
+ helpful: {
+ criteria: { false: 'Chatter.', true: 'An open question.' },
+ instructions: 'Would stepping in help?',
+ type: 'boolean',
+ },
+ };
+
+ it('should send the questions and state to aiChat.decide', async () => {
+ const response = {
+ answers: { helpful: { probability: 0.7, type: 'boolean' } },
+ model: 'jev',
+ };
+ mockTrpcClient.aiChat.decide.mutate.mockResolvedValue({ data: response, tracingId: 't' });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'decide',
+ 'Newest message: is it ready?',
+ '--model',
+ 'lobehub/jev-1.14.0',
+ '--questions',
+ JSON.stringify(questions),
+ ]);
+
+ expect(mockTrpcClient.aiChat.decide.mutate).toHaveBeenCalledWith({
+ metadata: { trigger: 'cli' },
+ model: 'jev-1.14.0',
+ provider: 'lobehub',
+ questions,
+ state: 'Newest message: is it ready?',
+ });
+ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(response, null, 2));
+ });
+
+ it('should read questions and state from files', async () => {
+ mockTrpcClient.aiChat.decide.mutate.mockResolvedValue({ data: { answers: {} } });
+ const dir = os.tmpdir();
+ const questionsPath = path.join(dir, `lh-gen-decide-q-${process.pid}.json`);
+ const statePath = path.join(dir, `lh-gen-decide-s-${process.pid}.txt`);
+ await fsWriteFile(questionsPath, JSON.stringify(questions));
+ await fsWriteFile(statePath, 'state from file');
+
+ try {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'decide',
+ '-m',
+ 'lobehub/jev-1.14.0',
+ '-q',
+ questionsPath,
+ '--state-file',
+ statePath,
+ ]);
+
+ expect(mockTrpcClient.aiChat.decide.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ questions, state: 'state from file' }),
+ );
+ } finally {
+ await fsRm(questionsPath, { force: true });
+ await fsRm(statePath, { force: true });
+ }
+ });
+
+ it('should require --model', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'decide',
+ 'state',
+ '--questions',
+ JSON.stringify(questions),
+ ]);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('`--model` is required'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.aiChat.decide.mutate).not.toHaveBeenCalled();
+ });
+
+ it('should reject a question without a known type', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'decide',
+ 'state',
+ '-m',
+ 'lobehub/jev-1.14.0',
+ '--questions',
+ '{"ok":{"instructions":"Is it ok?","type":"yesno"}}',
+ ]);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Question "ok" needs a type'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.aiChat.decide.mutate).not.toHaveBeenCalled();
+ });
+
+ it('should require a state', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'decide',
+ '-m',
+ 'lobehub/jev-1.14.0',
+ '--questions',
+ JSON.stringify(questions),
+ ]);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No state'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('should report a server error and exit', async () => {
+ mockTrpcClient.aiChat.decide.mutate.mockRejectedValue(
+ new Error('Decision models are not supported by this provider'),
+ );
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'decide',
+ 'state',
+ '-m',
+ 'openai/gpt-4o',
+ '--questions',
+ JSON.stringify(questions),
+ ]);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Decision failed'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+ });
+
describe('json', () => {
it('should send the schema to aiChat.outputJSON', async () => {
const fetchMock = vi.fn();
diff --git a/apps/cli/src/commands/generate/decide.ts b/apps/cli/src/commands/generate/decide.ts
new file mode 100644
index 00000000000..36e8b8f11f9
--- /dev/null
+++ b/apps/cli/src/commands/generate/decide.ts
@@ -0,0 +1,177 @@
+import { readFile } from 'node:fs/promises';
+
+import type { Command } from 'commander';
+
+import type { TrpcClient } from '../../api/client';
+import { getTrpcClient } from '../../api/client';
+import { log } from '../../utils/logger';
+
+type DecideInput = Parameters<TrpcClient['aiChat']['decide']['mutate']>[0];
+
+const QUESTION_TYPES = new Set(['boolean', 'choice', 'score']);
+
+export function registerDecideCommand(parent: Command) {
+ parent
+ .command('decide [state]')
+ .description(
+ 'Ask a decision model typed questions about one state (answers come back as probabilities)',
+ )
+ .option(
+ '-m, --model <model>',
+ 'Decision model ID (provider/model format), e.g. lobehub/jev-1.14.0 (required)',
+ )
+ .option('-p, --provider <provider>', 'Provider name (derived from model if omitted)')
+ .option(
+ '-q, --questions <questions>',
+ 'Question name β†’ question, as inline JSON or a path to a .json file (required). ' +
+ 'Each question is {"type":"boolean"|"choice"|"score","instructions":...,"criteria":...}',
+ )
+ .option('--state-file <path>', 'Read the state from a file instead of the argument')
+ .option('--pipe', 'Pipe mode: read the state (or more of it) from stdin')
+ .action(
+ async (
+ stateArg: string | undefined,
+ options: {
+ model?: string;
+ pipe?: boolean;
+ provider?: string;
+ questions?: string;
+ stateFile?: string;
+ },
+ ) => {
+ if (!options.model) {
+ log.error('`--model` is required: pass a decision model, e.g. lobehub/jev-1.14.0.');
+ process.exit(1);
+ return;
+ }
+
+ // `-m provider/model` only splits off a provider when `-p` is absent, as in `gen json`.
+ const [head, ...tail] = options.model.split('/');
+ const providerFromModel = !options.provider && tail.length > 0;
+ const provider = options.provider || (providerFromModel ? head : 'openai');
+ const model = providerFromModel ? tail.join('/') : options.model;
+
+ const questions = await readQuestions(options.questions);
+ if ('error' in questions) {
+ log.error(questions.error);
+ process.exit(1);
+ return;
+ }
+
+ const state = await readState(stateArg, options);
+ if ('error' in state) {
+ log.error(state.error);
+ process.exit(1);
+ return;
+ }
+
+ const client = await getTrpcClient();
+
+ let result: { data: unknown };
+ try {
+ result = await client.aiChat.decide.mutate({
+ metadata: { trigger: 'cli' },
+ model,
+ provider,
+ // Shape checked loosely here; the server validates every question.
+ questions: questions.value as DecideInput['questions'],
+ state: state.value,
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.error(`Decision failed: ${message}`);
+ process.exit(1);
+ return;
+ }
+
+ console.log(JSON.stringify(result.data, null, 2));
+ },
+ );
+}
+
+/** Inline JSON (starts with `{`), a `.json` path, or an `@`-prefixed path. */
+async function readJsonArg(
+ raw: string,
+ flag: string,
+): Promise<{ error: string } | { value: unknown }> {
+ const trimmed = raw.trim();
+ let text = trimmed;
+
+ if (!trimmed.startsWith('{')) {
+ const filePath = trimmed.startsWith('@') ? trimmed.slice(1) : trimmed;
+ try {
+ text = await readFile(filePath, 'utf8');
+ } catch {
+ return {
+ error: `Cannot read ${flag} file "${filePath}". Pass inline JSON or a readable path.`,
+ };
+ }
+ }
+
+ try {
+ return { value: JSON.parse(text) };
+ } catch {
+ return { error: `The value passed to ${flag} is not valid JSON.` };
+ }
+}
+
+async function readQuestions(
+ raw: string | undefined,
+): Promise<{ error: string } | { value: Record<string, unknown> }> {
+ if (!raw) {
+ return { error: '`--questions` is required: pass the questions inline or as a .json file.' };
+ }
+
+ const parsed = await readJsonArg(raw, '--questions');
+ if ('error' in parsed) return parsed;
+
+ const { value } = parsed;
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ return { error: '`--questions` must be an object of question name β†’ question.' };
+ }
+
+ const entries = Object.entries(value as Record<string, unknown>);
+ if (entries.length === 0) return { error: '`--questions` needs at least one question.' };
+
+ for (const [name, question] of entries) {
+ const type = (question as { type?: unknown } | null)?.type;
+ if (typeof type !== 'string' || !QUESTION_TYPES.has(type)) {
+ return {
+ error: `Question "${name}" needs a type of ${[...QUESTION_TYPES].join(', ')}.`,
+ };
+ }
+ if ((question as { instructions?: unknown }).instructions === undefined) {
+ return { error: `Question "${name}" needs instructions.` };
+ }
+ }
+
+ return { value: value as Record<string, unknown> };
+}
+
+async function readState(
+ stateArg: string | undefined,
+ options: { pipe?: boolean; stateFile?: string },
+): Promise<{ error: string } | { value: string }> {
+ let state = stateArg ?? '';
+
+ if (options.stateFile) {
+ try {
+ state = await readFile(options.stateFile, 'utf8');
+ } catch {
+ return { error: `Cannot read state file "${options.stateFile}".` };
+ }
+ }
+
+ if (options.pipe) {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
+ const stdinContent = Buffer.concat(chunks).toString('utf8').trim();
+ if (stdinContent) state = state ? `${state}\n\n${stdinContent}` : stdinContent;
+ }
+
+ if (!state.trim()) {
+ return { error: 'No state: pass it as an argument, with --state-file, or with --pipe.' };
+ }
+
+ return { value: state };
+}
diff --git a/apps/cli/src/commands/generate/index.ts b/apps/cli/src/commands/generate/index.ts
index 0fa3da89288..ed139a2f284 100644
--- a/apps/cli/src/commands/generate/index.ts
+++ b/apps/cli/src/commands/generate/index.ts
@@ -4,6 +4,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../../utils/format';
import { registerAsrCommand } from './asr';
+import { registerDecideCommand } from './decide';
import { registerImageCommand } from './image';
import { registerJsonCommand } from './json';
import { registerTextCommand } from './text';
@@ -73,6 +74,7 @@ export function registerGenerateCommand(program: Command) {
registerTextCommand(generate);
registerJsonCommand(generate);
+ registerDecideCommand(generate);
registerImageCommand(generate);
registerVideoCommand(generate);
registerTtsCommand(generate);
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.decide.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.decide.test.ts
new file mode 100644
index 00000000000..29f05d457e5
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.decide.test.ts
@@ -0,0 +1,93 @@
+// @vitest-environment node
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it, vi } from 'vitest';
+
+import { aiChatRouter } from '../aiChat';
+
+vi.mock('@/database/models/agent');
+vi.mock('@/database/models/message');
+vi.mock('@/database/models/thread');
+vi.mock('@/database/repositories/topic');
+vi.mock('@/server/services/aiChat');
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(),
+}));
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+const mockCtx = { userId: 'u1' };
+
+describe('aiChatRouter.decide', () => {
+ const questions = {
+ helpful: {
+ criteria: { false: 'Chatter.', true: 'An open question.' },
+ instructions: 'Would stepping in help?',
+ type: 'boolean' as const,
+ },
+ };
+
+ it('asks the decision model from the server and returns its answers', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const response = {
+ answers: { helpful: { probability: 0.82, type: 'boolean' } },
+ model: 'jev-1.14.0',
+ };
+ const mockDecide = vi.fn().mockResolvedValue(response);
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ decide: mockDecide } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+ const result = await caller.decide({
+ metadata: { trigger: 'cli' },
+ model: 'jev-1.14.0',
+ provider: 'lobehub',
+ questions,
+ state: 'Newest message: is the queue mode ready?',
+ });
+
+ expect(initModelRuntimeFromDB).toHaveBeenCalledWith({}, 'u1', 'lobehub', undefined);
+ expect(mockDecide).toHaveBeenCalledWith(
+ { model: 'jev-1.14.0', questions, state: 'Newest message: is the queue mode ready?' },
+ {
+ metadata: { trigger: 'cli' },
+ signal: undefined,
+ tracing: { tracingId: expect.stringMatching(/^[0-9a-f-]{36}$/) },
+ },
+ );
+ expect(result.data).toEqual(response);
+ expect(result.tracingId).toMatch(/^[0-9a-f-]{36}$/);
+ });
+
+ it('rejects a request without questions before calling the model', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ vi.mocked(initModelRuntimeFromDB).mockClear();
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ await expect(
+ caller.decide({ model: 'jev-1.14.0', provider: 'lobehub', questions: {}, state: 'x' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(initModelRuntimeFromDB).not.toHaveBeenCalled();
+ });
+
+ it('maps a provider without decision support to a client error', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const mockDecide = vi.fn().mockRejectedValue({
+ error: { message: 'Decision models are not supported by this provider' },
+ errorType: AgentRuntimeErrorType.CapabilityNotSupported,
+ });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ decide: mockDecide } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ try {
+ await caller.decide({ model: 'gpt-4o', provider: 'openai', questions, state: 'x' });
+ throw new Error('Expected decide to throw');
+ } catch (error) {
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error).toMatchObject({ message: AgentRuntimeErrorType.CapabilityNotSupported });
+ expect((error as TRPCError).code).not.toBe('INTERNAL_SERVER_ERROR');
+ }
+ });
+});
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index 0d346fc30e2..762fd0bd722 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -1,9 +1,15 @@
import { randomUUID } from 'node:crypto';
import { TRACING_SCENARIOS } from '@lobechat/const';
+import type { DecisionPayload, DecisionQuestions } from '@lobechat/model-runtime';
import { getErrorCodeSpec, StructuredOutputError } from '@lobechat/model-runtime';
import type { CreateMessageParams, SendMessageServerResponse } from '@lobechat/types';
-import { AiSendMessageServerSchema, RequestTrigger, StructureOutputSchema } from '@lobechat/types';
+import {
+ AiSendMessageServerSchema,
+ DecisionOutputSchema,
+ RequestTrigger,
+ StructureOutputSchema,
+} from '@lobechat/types';
import { createTimingHelpers, createTimingRequestId } from '@lobechat/utils';
import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
@@ -147,6 +153,44 @@ const aiChatProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
const aiChatWriteProcedure = aiChatProcedure.use(withScopedPermission('message:create'));
export const aiChatRouter = router({
+ /**
+ * Asks a decision model (e.g. `lobehub/jev-1.14.0`) typed questions about one state and returns
+ * its answers with probabilities: `lh generate decide`. The same `runtime.decide` call bot wake
+ * and channel routing make, so a prompt can be replayed on the model production uses.
+ */
+ decide: aiChatWriteProcedure.input(DecisionOutputSchema).mutation(async ({ input, ctx }) => {
+ log('decide called with provider: %s, model: %s', input.provider, input.model);
+
+ const tracingId = input.tracing?.tracingId ?? randomUUID();
+
+ try {
+ const data = await ctx.aiGenerationService.decide(
+ {
+ model: input.model,
+ provider: input.provider,
+ // Validated by `DecisionOutputSchema`, which mirrors the runtime's decision types.
+ questions: input.questions as DecisionQuestions,
+ state: input.state as DecisionPayload['state'],
+ },
+ {
+ metadata: {
+ trigger: RequestTrigger.Chat,
+ ...input.metadata,
+ userAgent: ctx.userAgent,
+ },
+ tracing: { ...input.tracing, tracingId },
+ },
+ );
+
+ return { data, tracingId };
+ } catch (error) {
+ const runtimeTRPCError = createRuntimeTRPCError(error);
+ if (runtimeTRPCError) throw runtimeTRPCError;
+
+ throw error;
+ }
+ }),
+
outputJSON: aiChatWriteProcedure.input(StructureOutputSchema).mutation(async ({ input, ctx }) => {
log('outputJSON called with provider: %s, model: %s', input.provider, input.model);
log('messages count: %d', input.messages.length);
diff --git a/apps/server/src/services/aiGeneration/index.test.ts b/apps/server/src/services/aiGeneration/index.test.ts
index dd5c5dd354a..046e53dff70 100644
--- a/apps/server/src/services/aiGeneration/index.test.ts
+++ b/apps/server/src/services/aiGeneration/index.test.ts
@@ -150,3 +150,39 @@ describe('AiGenerationService.generateObject with a device-only provider', () =>
).rejects.toMatchObject({ error: { reason: 'no_executor' } });
});
});
+
+describe('AiGenerationService.decide', () => {
+ const decide = vi.fn();
+ const initSpy = vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB');
+
+ beforeEach(() => {
+ decide.mockReset();
+ initSpy.mockReset();
+ resolveProviderRelay.mockReset();
+ initSpy.mockResolvedValue({ decide } as any);
+ });
+
+ it('calls the decision model from the server, never through the device relay', async () => {
+ const response = { answers: { ok: { probability: 0.9, type: 'boolean' } }, model: 'jev' };
+ decide.mockResolvedValue(response);
+ const questions = { ok: { instructions: 'Is it ok?', type: 'boolean' as const } };
+
+ const ai = new AiGenerationService({} as any, 'user-1', 'ws-1');
+ const result = await ai.decide(
+ { model: 'jev-1.14.0', provider: 'lobehub', questions, state: 'state' },
+ { metadata: { trigger: RequestTrigger.Cli }, tracing: { scenario: 'replay' } },
+ );
+
+ expect(resolveProviderRelay).not.toHaveBeenCalled();
+ expect(initSpy).toHaveBeenCalledWith({}, 'user-1', 'lobehub', 'ws-1');
+ expect(decide).toHaveBeenCalledWith(
+ { model: 'jev-1.14.0', questions, state: 'state' },
+ {
+ metadata: { trigger: RequestTrigger.Cli },
+ signal: undefined,
+ tracing: { scenario: 'replay' },
+ },
+ );
+ expect(result).toBe(response);
+ });
+});
diff --git a/apps/server/src/services/aiGeneration/index.ts b/apps/server/src/services/aiGeneration/index.ts
index 9892f286cd0..7bfbda03f4e 100644
--- a/apps/server/src/services/aiGeneration/index.ts
+++ b/apps/server/src/services/aiGeneration/index.ts
@@ -1,5 +1,8 @@
import type {
ChatCompletionTool,
+ DecisionPayload,
+ DecisionQuestions,
+ DecisionResponse,
GenerateObjectPayload,
GenerateObjectSchema,
} from '@lobechat/model-runtime';
@@ -7,6 +10,7 @@ import type { 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'];
@@ -17,6 +21,12 @@ export interface AiGenerationObjectInput {
tools?: ChatCompletionTool[];
}
+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`
@@ -83,4 +93,27 @@ export class AiGenerationService {
{ metadata: options.metadata, signal: options.signal, tracing: options.tracing },
)) as T;
}
+
+ /**
+ * Asks a decision model typed questions about one state and returns its probabilities.
+ *
+ * Always called from the server: decision endpoints are hosted APIs, and the device relay
+ * {@link generateObject} may use has no decision call. A provider without a decision endpoint
+ * 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 },
+ );
+ }
}
diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.ts
index 1bba6204407..b6a5e783cf4 100644
--- a/packages/types/src/aiChat.ts
+++ b/packages/types/src/aiChat.ts
@@ -277,6 +277,51 @@ export const StructureOutputSchema = z.object({
tracing: z.object({ tracingId: z.string().uuid().optional() }).catchall(z.unknown()).optional(),
});
+/** Plain text or structured JSON, as a decision model accepts for `state`, `instructions` and criteria. */
+const DecisionContentSchema = z.union([
+ z.string(),
+ z.array(z.unknown()),
+ z.record(z.string(), z.unknown()),
+]);
+
+/** One typed question for a decision model; mirrors `DecisionQuestion` in `@lobechat/model-runtime`. */
+export const DecisionQuestionSchema = z.discriminatedUnion('type', [
+ z.object({
+ criteria: z.object({ false: DecisionContentSchema, true: DecisionContentSchema }).optional(),
+ instructions: DecisionContentSchema,
+ type: z.literal('boolean'),
+ }),
+ z.object({
+ criteria: z.record(z.string(), DecisionContentSchema.nullable()),
+ instructions: DecisionContentSchema,
+ type: z.literal('choice'),
+ }),
+ z.object({
+ criteria: z.array(DecisionContentSchema).min(1),
+ instructions: DecisionContentSchema,
+ type: z.literal('score'),
+ }),
+]);
+
+export const DecisionOutputSchema = z.object({
+ /** Free-form context forwarded to non-tracing hooks (e.g. billing), as on `outputJSON`. */
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ model: z.string(),
+ provider: z.string(),
+ /** Question name β†’ question. The names come back as the keys of `answers`. */
+ questions: z
+ .record(z.string(), DecisionQuestionSchema)
+ .refine((questions) => Object.keys(questions).length > 0, {
+ message: 'A decision request needs at least one question',
+ }),
+ /** The content every question is evaluated against. */
+ state: DecisionContentSchema,
+ /** Structured tracing config, validated like `StructureOutputSchema.tracing`. */
+ tracing: z.object({ tracingId: z.string().uuid().optional() }).catchall(z.unknown()).optional(),
+});
+
+export type DecisionOutputParams = z.infer<typeof DecisionOutputSchema>;
+
interface IStructureSchema {
description?: string;
name: string;