/** * LLM Prompt Generator * * Auto-generates LLM system prompts from CommandSchema[]. Given a set of * domain schemas, produces a structured markdown prompt that teaches LLMs * to output valid LSE bracket syntax and/or LLM-simplified JSON. * * The generated prompt includes: * - Protocol overview (LSE syntax summary) * - Value type reference * - Per-command documentation with role descriptions * - Synthetic examples in both formats * - Output format specification * - Error recovery instructions */ import type { CommandSchema, RoleSpec } from '../schema/command-schema'; import type { SemanticJSON, SemanticJSONValue } from '../ir/types'; import { renderExplicit } from '../ir/explicit-renderer'; import { createCommandNode } from '../core/types'; import type { PromptGeneratorConfig, GeneratedPrompt, PromptSection, PromptMetadata, } from './types'; // ============================================================================= // Public API // ============================================================================= /** * Generate an LLM system prompt from domain command schemas. * * @example * ```typescript * import { generatePrompt } from '@lokascript/framework'; * import { allSchemas } from '@lokascript/domains/flow'; * * const prompt = generatePrompt({ * domain: 'flow', * description: 'Reactive data flow pipelines', * schemas: allSchemas, * }); * * console.log(prompt.text); // Full markdown system prompt * ``` */ export function generatePrompt(config: PromptGeneratorConfig): GeneratedPrompt { const outputFormat = config.outputFormat ?? 'both'; const examplesPerCommand = config.examplesPerCommand ?? 2; const sections: PromptSection[] = [ buildProtocolSection(), buildValueTypeSection(), buildCommandsSection(config.schemas, outputFormat, examplesPerCommand), buildOutputFormatSection(outputFormat), buildErrorRecoverySection(), ]; // Apply token budget if specified let finalSections = sections; if (config.maxTokens && config.maxTokens > 0) { finalSections = truncateToTokenBudget(sections, config.maxTokens); } const text = finalSections.map(s => `## ${s.title}\n\n${s.content}`).join('\n\n---\n\n'); const totalRoles = config.schemas.reduce((sum, s) => sum + s.roles.length, 0); const approximateTokens = estimateTokens(text); const metadata: PromptMetadata = { domain: config.domain, commandCount: config.schemas.length, roleCount: totalRoles, approximateTokens, }; return { text, sections: finalSections, metadata }; } /** * Generate synthetic LSE examples from a single command schema. * Used by both the prompt generator and training data synthesizer. */ export function generateExamples( schema: CommandSchema, count: number = 2 ): Array<{ explicit: string; json: SemanticJSON }> { const combos = generateRoleCombinations(schema); const examples: Array<{ explicit: string; json: SemanticJSON }> = []; for (let i = 0; i < Math.min(count, combos.length); i++) { const combo = combos[i]; const roles = new Map(); for (const role of combo) { const sample = sampleValue(role); roles.set(role.role, sample); } // Build SemanticNode for rendering to bracket syntax const nodeRoles = new Map< string, { type: string; value: string | number | boolean; raw?: string; dataType?: string; selectorKind?: string; } >(); for (const [roleName, sample] of roles) { nodeRoles.set(roleName, toSemanticValue(sample)); } const node = createCommandNode(schema.action, nodeRoles as never); const explicit = renderExplicit(node); // Build JSON format const jsonRoles: Record = {}; for (const [roleName, sample] of roles) { jsonRoles[roleName] = sample as SemanticJSONValue; } const json: SemanticJSON = { action: schema.action, roles: jsonRoles }; examples.push({ explicit, json }); } return examples; } /** * Generate a condensed LSE protocol reference (for MCP resources). */ export function generateProtocolReference(): string { const protocol = buildProtocolSection(); const valueTypes = buildValueTypeSection(); return `# LokaScript Explicit Syntax (LSE) Quick Reference\n\n${protocol.content}\n\n${valueTypes.content}`; } // ============================================================================= // Section Builders // ============================================================================= function buildProtocolSection(): PromptSection { const content = `LokaScript Explicit Syntax (LSE) is a bracket-based format for imperative commands. ### Syntax \`\`\` [command role1:value1 role2:value2 +flag1 ~flag2] \`\`\` - **Command**: The first token inside brackets (lowercased) - **Role pair**: \`name:value\` — a named semantic role with a typed value (no space around colon) - **Enabled flag**: \`+name\` — boolean attribute present - **Disabled flag**: \`~name\` — boolean attribute negated - **Nested body**: \`body:[command ...]\` — a bracket command inside a role value ### Rules 1. Commands are always lowercased 2. Role names preserve their original case 3. No spaces around the colon in role:value pairs 4. Strings with spaces must be quoted: \`patient:"hello world"\` 5. Selectors start with \`#\`, \`.\`, \`[\`, \`@\`, or \`*\` 6. A selector containing a space, a combinator (\`>\` \`+\` \`~\`), or a comma must use a selector literal: \`patient: