π€― 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
β¨ feat(cli): add lh gen json for structured output (#21413)
Arvin Xu22ee92d32151
diff --git a/.agents/skills/cli/references/generate.md b/.agents/skills/cli/references/generate.mdindex c7fd1610470..7b9956f3429 100644--- a/.agents/skills/cli/references/generate.md+++ b/.agents/skills/cli/references/generate.md@@ -60,6 +60,36 @@ cat README.md | lh gen text "summarize this" --pipe---+## `lh generate json <prompt>` / `lh gen json <prompt>`++Generate a JSON object with structured output.++**Source**: `apps/cli/src/commands/generate/json.ts`++```bash+lh gen json <prompt> [-m <model>] [-p <provider>] [-s <prompt>] [--schema <json|path>] [--schema-name <name>] [--strict] [--pipe]+```++| Option | Description | Default |+| --------------------------- | -------------------------------------------------- | -------------------- |+| `-m, --model <model>` | Model ID | `openai/gpt-4o-mini` |+| `-p, --provider <provider>` | Provider name | - |+| `-s, --system <prompt>` | System prompt | - |+| `--schema <json\|path>` | JSON Schema, inline or from a file (required) | - |+| `--schema-name <name>` | Schema name sent to the model | `response` |+| `--strict` | Require the model to adhere strictly to the schema | `false` |+| `--pipe` | Read additional context from stdin | `false` |++The command calls the `aiChat.outputJSON` mutation rather than `/webapi/chat`, so the server owns+provider-specific handling (`json_schema` support, the tool-calling fallback, Responses API routing), and+prints the parsed object pretty-printed. It is a single request: `--stream`, `--temperature` and+`--max-tokens` are not accepted options, and passing them fails as an unknown option. A reply the server+cannot parse into the schema exits with code 1. The server keeps only `type`, `properties`, `required`,+`additionalProperties` and `$defs`; schemas using other root keywords (`allOf`, `minProperties`, ...) are+rejected up front.++---+## `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.tsindex dec2a34caaf..d1ee731320b 100644--- a/apps/cli/src/commands/generate.test.ts+++ b/apps/cli/src/commands/generate.test.ts@@ -10,6 +10,9 @@ import { registerGenerateCommand } from './generate';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {+ aiChat: {+ outputJSON: { mutate: vi.fn() },+ },asr: {transcribe: { mutate: vi.fn() },},@@ -333,6 +336,224 @@ describe('generate command', () => {});});+ describe('json', () => {+ it('should send the schema to aiChat.outputJSON', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ mockTrpcClient.aiChat.outputJSON.mutate.mockResolvedValue({+ data: { name: 'Maya' },+ tracingId: 'trace-1',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Invent a person',+ '--schema',+ '{"properties":{"name":{"type":"string"}},"required":["name"],"type":"object"}',+ '--schema-name',+ 'person',+ ]);++ expect(mockTrpcClient.aiChat.outputJSON.mutate).toHaveBeenCalledWith({+ messages: [{ content: 'Invent a person', role: 'user' }],+ model: 'gpt-4o-mini',+ provider: 'openai',+ schema: {+ name: 'person',+ schema: { properties: { name: { type: 'string' } }, required: ['name'], type: 'object' },+ },+ });+ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify({ name: 'Maya' }, null, 2));+ // Structured output never touches the chat endpoint+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('should require --schema', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'generate', 'json', 'Return JSON']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('`--schema` is required'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.aiChat.outputJSON.mutate).not.toHaveBeenCalled();+ });++ it('should keep slashes in the model id when --provider is given', async () => {+ mockTrpcClient.aiChat.outputJSON.mutate.mockResolvedValue({ data: { ok: true } });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Hi',+ '--provider',+ 'siliconcloud',+ '--model',+ 'Qwen/Qwen3.6-27B',+ '--schema',+ '{"type":"object","properties":{}}',+ ]);++ expect(mockTrpcClient.aiChat.outputJSON.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'Qwen/Qwen3.6-27B', provider: 'siliconcloud' }),+ );+ });++ it('should reject schema keywords the server drops', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Hi',+ '--schema',+ '{"type":"object","properties":{},"minProperties":1}',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('minProperties'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.aiChat.outputJSON.mutate).not.toHaveBeenCalled();+ });++ it('should mark the schema strict when --strict is passed', async () => {+ mockTrpcClient.aiChat.outputJSON.mutate.mockResolvedValue({ data: { age: 29 } });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Give me an age',+ '--schema',+ '{"properties":{"age":{"type":"number"}},"type":"object"}',+ '--strict',+ ]);++ expect(mockTrpcClient.aiChat.outputJSON.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ schema: {+ name: 'response',+ schema: { properties: { age: { type: 'number' } }, type: 'object' },+ strict: true,+ },+ }),+ );+ });++ it('should read the schema from a file when --schema is a path', async () => {+ const schemaPath = path.join(os.tmpdir(), `lh-gen-schema-${process.pid}.json`);+ await fsWriteFile(+ schemaPath,+ JSON.stringify({ properties: { age: { type: 'number' } }, type: 'object' }),+ );+ mockTrpcClient.aiChat.outputJSON.mutate.mockResolvedValue({ data: { age: 29 } });++ try {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Give me an age',+ '--schema',+ schemaPath,+ ]);+ } finally {+ await fsRm(schemaPath, { force: true });+ }++ expect(mockTrpcClient.aiChat.outputJSON.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ schema: {+ name: 'response',+ schema: { properties: { age: { type: 'number' } }, type: 'object' },+ },+ }),+ );+ });++ it('should reject an unreadable schema file', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Hi',+ '--schema',+ './no-such-schema.json',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Cannot read schema file'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.aiChat.outputJSON.mutate).not.toHaveBeenCalled();+ });++ it('should reject a schema that is not an object schema', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Hi',+ '--schema',+ '{"type":"array","properties":{}}',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('object schema'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.aiChat.outputJSON.mutate).not.toHaveBeenCalled();+ });++ it('should fail when the endpoint returns no parsed data', async () => {+ mockTrpcClient.aiChat.outputJSON.mutate.mockResolvedValue({+ data: undefined,+ tracingId: 'trace-1',+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Hi',+ '--schema',+ '{"type":"object","properties":{}}',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not valid JSON'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should report a failed request', async () => {+ mockTrpcClient.aiChat.outputJSON.mutate.mockRejectedValue(new Error('provider down'));++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'generate',+ 'json',+ 'Hi',+ '--schema',+ '{"type":"object","properties":{}}',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('provider down'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+ });+describe('image', () => {it('should create image generation', async () => {mockTrpcClient.generationTopic.createTopic.mutate.mockResolvedValue('topic-1');diff --git a/apps/cli/src/commands/generate/index.ts b/apps/cli/src/commands/generate/index.tsindex b97c39c0546..0fa3da89288 100644--- a/apps/cli/src/commands/generate/index.ts+++ b/apps/cli/src/commands/generate/index.ts@@ -5,6 +5,7 @@ import { getTrpcClient } from '../../api/client';import { confirm, outputJson, printTable, timeAgo, truncate } from '../../utils/format';import { registerAsrCommand } from './asr';import { registerImageCommand } from './image';+import { registerJsonCommand } from './json';import { registerTextCommand } from './text';import { registerTtsCommand } from './tts';import { registerVideoCommand } from './video';@@ -71,6 +72,7 @@ export function registerGenerateCommand(program: Command) {.description('Generate content (text, image, video, speech)');registerTextCommand(generate);+ registerJsonCommand(generate);registerImageCommand(generate);registerVideoCommand(generate);registerTtsCommand(generate);@@ -201,7 +203,9 @@ export function registerGenerateCommand(program: Command) {console.log(`${pc.red('β')} Timed out after ${options.timeout}s. Task still ${result.status}.`,);- console.log(pc.dim(`Run "lh gen status ${generationId} ${asyncTaskId}" to check later.`));+ console.log(+ pc.dim(`Run "lh gen status ${generationId} ${asyncTaskId}" to check later.`),+ );process.exit(1);}diff --git a/apps/cli/src/commands/generate/json.ts b/apps/cli/src/commands/generate/json.tsnew file mode 100644index 00000000000..7904dff5f65--- /dev/null+++ b/apps/cli/src/commands/generate/json.ts@@ -0,0 +1,198 @@+import { readFile } from 'node:fs/promises';++import type { StructureOutputParams } from '@lobechat/types';+import type { Command } from 'commander';++import { getTrpcClient } from '../../api/client';+import { log } from '../../utils/logger';++type StructuredSchema = NonNullable<StructureOutputParams['schema']>;++/**+ * Root keywords the server keeps (`StructureSchema` in `@lobechat/types`). It+ * drops everything else, so a schema relying on `allOf` or `minProperties`+ * would be silently weakened.+ */+const SUPPORTED_SCHEMA_KEYS = new Set([+ '$defs',+ '$schema',+ 'additionalProperties',+ 'description',+ 'properties',+ 'required',+ 'title',+ 'type',+]);++export function registerJsonCommand(parent: Command) {+ parent+ .command('json <prompt>')+ .description('Generate a JSON object with an LLM (structured output, single completion)')+ .option('-m, --model <model>', 'Model ID (provider/model format)', 'openai/gpt-4o-mini')+ .option('-p, --provider <provider>', 'Provider name (derived from model if omitted)')+ .option('-s, --system <prompt>', 'System prompt')+ .option(+ '--schema <schema>',+ 'JSON Schema for the reply β inline JSON or a path to a .json file (required)',+ )+ .option('--schema-name <name>', 'Schema name sent to the model', 'response')+ .option('--strict', 'Require the model to adhere strictly to the schema')+ .option('--pipe', 'Pipe mode: read additional context from stdin')+ .action(+ async (+ prompt: string,+ options: {+ model: string;+ pipe?: boolean;+ provider?: string;+ schema?: string;+ schemaName?: string;+ strict?: boolean;+ system?: string;+ },+ ) => {+ // `-m provider/model` only splits off a provider when `-p` is absent; with an+ // explicit provider the model ID keeps its own slashes (Qwen/Qwen3.6-27B).+ 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 resolved = await resolveSchema(options);+ if ('error' in resolved) {+ log.error(resolved.error);+ process.exit(1);+ return;+ }++ // Read additional input from stdin if --pipe+ let fullPrompt = prompt;+ 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) {+ fullPrompt = `${prompt}\n\n${stdinContent}`;+ }+ }++ const messages: Array<{ content: string; role: string }> = [];+ if (options.system) {+ messages.push({ content: options.system, role: 'system' });+ }+ messages.push({ content: fullPrompt, role: 'user' });++ // Structured output runs through the `aiChat.outputJSON` mutation rather+ // than `/webapi/chat`: the server owns the provider-specific handling+ // (`json_schema` support, the tool-calling fallback, Responses API+ // routing) and hands back the parsed object.+ const client = await getTrpcClient();++ let result: { data?: unknown };+ try {+ result = await client.aiChat.outputJSON.mutate({+ messages,+ model,+ provider,+ schema: resolved.value,+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log.error(`JSON generation failed: ${message}`);+ process.exit(1);+ return;+ }++ // Schema mode resolves an unparsable reply (prose, truncated JSON) to+ // `undefined` instead of throwing, so a missing payload is a failure.+ if (result.data === undefined) {+ log.error('The model reply was not valid JSON for the given schema.');+ process.exit(1);+ return;+ }++ console.log(JSON.stringify(result.data, null, 2));+ },+ );+}++/**+ * Build the schema sent to the server. `--schema` is required: the endpoint has+ * no schema-less mode, and a permissive object schema would break the strict+ * paths (Responses API models force `strict: true`).+ */+async function resolveSchema(options: {+ schema?: string;+ schemaName?: string;+ strict?: boolean;+}): Promise<{ error: string } | { value: StructuredSchema }> {+ if (!options.schema) {+ return { error: '`--schema` is required: pass a JSON Schema inline or as a .json file.' };+ }++ const parsed = await readSchema(options.schema);+ if ('error' in parsed) return parsed;++ return {+ value: {+ name: options.schemaName || 'response',+ schema: parsed.value,+ ...(options.strict ? { strict: true } : {}),+ },+ };+}++/** `--schema` accepts inline JSON, a `.json` path, or an `@`-prefixed path. */+async function readSchema(+ raw: string,+): Promise<{ error: string } | { value: StructuredSchema['schema'] }> {+ 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 schema file "${filePath}". Pass inline JSON or a readable path.`,+ };+ }+ }++ let value: unknown;+ try {+ value = JSON.parse(text);+ } catch {+ return { error: 'The value passed to --schema is not valid JSON.' };+ }++ if (!isObjectSchema(value)) {+ return { error: 'The schema must be an object schema with a `properties` object.' };+ }++ const unsupported = Object.keys(value).filter((key) => !SUPPORTED_SCHEMA_KEYS.has(key));++ if (unsupported.length > 0) {+ return {+ error: `The schema uses keywords the server drops: ${unsupported.join(', ')}. Supported root keywords: ${[...SUPPORTED_SCHEMA_KEYS].join(', ')}.`,+ };+ }++ return { value };+}++function isObjectSchema(value: unknown): value is StructuredSchema['schema'] {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;++ const candidate = value as Record<string, unknown>;++ return (+ candidate.type === 'object' &&+ typeof candidate.properties === 'object' &&+ candidate.properties !== null &&+ !Array.isArray(candidate.properties)+ );+}diff --git a/packages/builtin-skills/src/lobehub/references/generate.ts b/packages/builtin-skills/src/lobehub/references/generate.tsindex 32a7ace49b4..42513a626a4 100644--- a/packages/builtin-skills/src/lobehub/references/generate.ts+++ b/packages/builtin-skills/src/lobehub/references/generate.ts@@ -5,6 +5,7 @@ Generate text, images, videos, and audio. Alias: \`lh generate\`.## Subcommands- \`lh gen text <prompt> [-m <model>] [-p <provider>] [--temperature <t>]\` - Generate text+- \`lh gen json <prompt> [-m <model>] [-p <provider>] [--schema <json|file>] [--schema-name <name>] [--strict]\` - Generate a JSON object (structured output)- \`lh gen image <prompt> [-m <model>] [-n <count>] [--width <w>] [--height <h>]\` - Generate image- \`lh gen video <prompt> -m <model> -p <provider> [--aspect-ratio <r>] [--duration <d>] [--resolution <res>]\` - Generate video- \`lh gen tts <text> [-m <model>] [-p <provider>] [-o <output>] [--voice <v>] [--speed <s>]\` - Text-to-speech using the selected provider's saved configuration@@ -13,6 +14,24 @@ Generate text, images, videos, and audio. Alias: \`lh generate\`.- \`lh gen download <generationId> <asyncTaskId> [-o <output>]\` - Wait and download result- \`lh gen list\` - List generation topics+## Structured Output++\`lh gen json\` returns a parsed JSON object instead of text. \`--schema\` is required β the server needs a+schema, so pass one inline or as a file.++\`\`\`bash+# Inline schema+lh gen json "Extract the person" --schema '{"properties":{"name":{"type":"string"}},"required":["name"],"type":"object"}'++# Schema from a file, named and strictly enforced+lh gen json "Extract the person" --schema ./person.json --schema-name person --strict+\`\`\`++- The command prints the pretty-printed object; a reply the server cannot parse into the schema exits with code 1+- The server keeps only \`type\`, \`properties\`, \`required\`, \`additionalProperties\` and \`$defs\`, so schemas using \`allOf\`, \`minProperties\` or \`patternProperties\` are rejected+- It is a single request: \`--stream\`, \`--temperature\` and \`--max-tokens\` are not accepted options+- Use \`lh gen text\` when you want prose+## Tips- Image/video generation is async; use \`status\` or \`download\` to get results