@deepagents/text2sql 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1121 -453
- package/dist/index.js.map +4 -4
- package/dist/lib/adapters/mysql/column-stats.mysql.grounding.d.ts +14 -0
- package/dist/lib/adapters/mysql/column-stats.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/column-values.mysql.grounding.d.ts +22 -0
- package/dist/lib/adapters/mysql/column-values.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/constraint.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/constraint.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/index.d.ts +44 -0
- package/dist/lib/adapters/mysql/index.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/index.js +1597 -0
- package/dist/lib/adapters/mysql/index.js.map +7 -0
- package/dist/lib/adapters/mysql/indexes.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/indexes.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/info.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/info.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/mysql.d.ts +33 -0
- package/dist/lib/adapters/mysql/mysql.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/row-count.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/row-count.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/table.mysql.grounding.d.ts +21 -0
- package/dist/lib/adapters/mysql/table.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/view.mysql.grounding.d.ts +18 -0
- package/dist/lib/adapters/mysql/view.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/agents/bi.agent.d.ts +14 -0
- package/dist/lib/agents/bi.agent.d.ts.map +1 -0
- package/dist/lib/agents/chat1.agent.d.ts.map +1 -1
- package/dist/lib/agents/chat2.agent.d.ts.map +1 -1
- package/dist/lib/agents/developer.agent.d.ts +31 -0
- package/dist/lib/agents/developer.agent.d.ts.map +1 -0
- package/dist/lib/agents/question.agent.d.ts +1 -1
- package/dist/lib/agents/question.agent.d.ts.map +1 -1
- package/dist/lib/agents/sql.agent.d.ts +14 -32
- package/dist/lib/agents/sql.agent.d.ts.map +1 -1
- package/dist/lib/agents/text2sql.agent.d.ts.map +1 -1
- package/dist/lib/checkpoint.d.ts.map +1 -1
- package/dist/lib/sql.d.ts +42 -0
- package/dist/lib/sql.d.ts.map +1 -1
- package/dist/lib/synthesis/extractors/sql-extractor.d.ts.map +1 -1
- package/dist/lib/synthesis/index.js +267 -164
- package/dist/lib/synthesis/index.js.map +3 -3
- package/dist/lib/synthesis/synthesizers/breadth-evolver.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/styles.d.ts +2 -2
- package/dist/lib/synthesis/synthesizers/styles.d.ts.map +1 -1
- package/dist/lib/teach/teachings.d.ts.map +1 -1
- package/package.json +9 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/synthesis/types.ts", "../../../src/lib/synthesis/decorators/filtered-producer.ts", "../../../src/lib/synthesis/decorators/deduplicated-producer.ts", "../../../src/lib/synthesis/decorators/validated-producer.ts", "../../../src/lib/synthesis/extractors/message-extractor.ts", "../../../src/lib/synthesis/extractors/base-contextual-extractor.ts", "../../../src/lib/synthesis/extractors/sql-extractor.ts", "../../../src/lib/synthesis/extractors/full-context-extractor.ts", "../../../src/lib/synthesis/extractors/windowed-context-extractor.ts", "../../../src/lib/synthesis/extractors/segmented-context-extractor.ts", "../../../src/lib/synthesis/extractors/last-query-extractor.ts", "../../../src/lib/synthesis/synthesizers/schema-synthesizer.ts", "../../../src/lib/agents/question.agent.ts", "../../../src/lib/agents/sql.agent.ts", "../../../src/lib/teach/xml.ts", "../../../src/lib/teach/teachables.ts", "../../../src/lib/synthesis/synthesizers/breadth-evolver.ts", "../../../src/lib/synthesis/synthesizers/styles.ts", "../../../src/lib/synthesis/synthesizers/depth-evolver.ts", "../../../src/lib/synthesis/synthesizers/persona-generator.ts", "../../../src/lib/agents/teachables.agent.ts", "../../../src/lib/synthesis/synthesizers/teachings-generator.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * A question/SQL pair extracted or synthesized for training data.\n */\nexport interface ExtractedPair {\n question: string;\n sql: string;\n context?: string[];\n success: boolean;\n}\n\n/**\n * Interface for all pair producers (extractors and synthesizers).\n * Implementations encapsulate their specific inputs and logic.\n */\nexport abstract class PairProducer<T extends ExtractedPair = ExtractedPair> {\n /**\n * Produce question/SQL pairs.\n */\n abstract produce(): AsyncGenerator<T[], void, unknown>;\n\n protected from(producer: PairProducer<ExtractedPair> | ExtractedPair[]) {\n return Array.isArray(producer)\n ? (async function* (pairs: ExtractedPair[]) {\n yield pairs;\n })(producer)\n : producer.produce();\n }\n\n public toPairs(): Promise<T[]> {\n return toPairs(this);\n }\n}\n\n/**\n * Entry point for producing pairs from any source.\n */\nexport async function toPairs<T extends ExtractedPair>(\n producer: PairProducer<T>,\n): Promise<T[]> {\n const pairs: T[] = [];\n for await (const chunk of producer.produce()) {\n pairs.push(...chunk);\n }\n return pairs;\n}\n", "import { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface FilteredProducerOptions {\n successOnly?: boolean;\n tables?: string[];\n filter?: (pair: ExtractedPair) => boolean;\n}\n\n/**\n * FilteredProducer - Filter pairs from another producer.\n *\n * Wraps another PairProducer and filters the output based on criteria.\n */\nexport class FilteredProducer extends PairProducer {\n /**\n * @param producer - Source producer to filter\n * @param options - Filter configuration\n */\n constructor(\n private producer: PairProducer,\n private options: FilteredProducerOptions = {},\n ) {\n super();\n }\n\n /**\n * Produces pairs filtered by success status, table usage, and custom predicates.\n * @returns Pairs matching all configured filter criteria\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n for await (const chunk of this.producer.produce()) {\n const filtered = chunk.filter((pair) => {\n if (this.options.successOnly !== false && !pair.success) {\n return false;\n }\n\n if (this.options.tables?.length) {\n const sqlLower = pair.sql.toLowerCase();\n const hasTable = this.options.tables.some((t) =>\n sqlLower.includes(t.toLowerCase()),\n );\n if (!hasTable) return false;\n }\n\n if (this.options.filter && !this.options.filter(pair)) {\n return false;\n }\n\n return true;\n });\n\n if (filtered.length) {\n yield filtered;\n }\n }\n }\n}\n", "import { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface DeduplicatedProducerOptions {\n strategy?: 'exact' | 'sql-only' | 'question-only';\n}\n\n/**\n * DeduplicatedProducer - Remove duplicate pairs from another producer.\n *\n * Wraps another PairProducer and removes duplicates based on\n * exact match or semantic similarity.\n */\nexport class DeduplicatedProducer extends PairProducer {\n /**\n * @param producer - Source producer to deduplicate\n * @param options - Deduplication configuration\n */\n constructor(\n private producer: PairProducer,\n private options: DeduplicatedProducerOptions = {},\n ) {\n super();\n }\n\n /**\n * Produces pairs with duplicates removed based on the configured strategy.\n * @returns Unique pairs after deduplication\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const { strategy = 'exact' } = this.options;\n const seen = new Set<string>();\n\n for await (const chunk of this.producer.produce()) {\n const unique: ExtractedPair[] = [];\n\n for (const pair of chunk) {\n let key: string;\n\n switch (strategy) {\n case 'sql-only':\n key = this.normalizeSQL(pair.sql);\n break;\n case 'question-only':\n key = pair.question.toLowerCase().trim();\n break;\n case 'exact':\n default:\n key = `${pair.question.toLowerCase().trim()}|||${this.normalizeSQL(pair.sql)}`;\n }\n\n if (!seen.has(key)) {\n seen.add(key);\n unique.push(pair);\n }\n }\n\n if (unique.length) {\n yield unique;\n }\n }\n }\n\n private normalizeSQL(sql: string): string {\n return sql.toLowerCase().replace(/\\s+/g, ' ').trim();\n }\n}\n", "import type { Adapter } from '../../adapters/adapter.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface ValidatedProducerOptions {\n execute?: boolean;\n removeInvalid?: boolean;\n}\n\nexport interface ValidatedPair extends ExtractedPair {\n rowCount?: number;\n error?: string;\n}\n/**\n * ValidatedProducer - Validate SQL from another producer.\n *\n * Wraps another PairProducer and validates each SQL query,\n * optionally executing to attach results.\n */\nexport class ValidatedProducer extends PairProducer<ValidatedPair> {\n /**\n * @param producer - Source producer to validate\n * @param adapter - Database adapter for SQL validation\n * @param options - Validation configuration\n */\n constructor(\n private producer: PairProducer,\n private adapter: Adapter,\n private options: ValidatedProducerOptions = {},\n ) {\n super();\n }\n\n /**\n * Produces pairs with SQL validation applied, optionally executing queries.\n * @returns Validated pairs with error/rowCount metadata attached\n */\n async *produce(): AsyncGenerator<ValidatedPair[]> {\n for await (const chunk of this.producer.produce()) {\n const validated: ValidatedPair[] = [];\n\n for (const pair of chunk) {\n const error = await this.adapter.validate(pair.sql);\n\n if (error) {\n if (!this.options.removeInvalid) {\n validated.push({\n ...pair,\n success: false,\n error,\n });\n }\n continue;\n }\n\n let rowCount: number | undefined;\n if (this.options.execute) {\n try {\n const result = await this.adapter.execute(pair.sql);\n rowCount = Array.isArray(result) ? result.length : undefined;\n } catch {\n // no op\n }\n }\n\n validated.push({\n ...pair,\n success: true,\n rowCount,\n });\n }\n\n if (validated.length) {\n yield validated;\n }\n }\n }\n}\n", "import {\n type UIMessage,\n getToolOrDynamicToolName,\n isToolOrDynamicToolUIPart,\n} from 'ai';\n\nimport { type ExtractedPair, PairProducer } from '../types.ts';\nimport {\n type DbQueryInput,\n getMessageText,\n} from './base-contextual-extractor.ts';\n\nexport interface MessageExtractorOptions {\n includeFailures?: boolean;\n toolName?: string;\n}\n/**\n * MessageExtractor - Extract pairs from chat history by parsing tool calls.\n *\n * Deterministic extraction: parses db_query tool calls and pairs them\n * with the preceding user message.\n */\nexport class MessageExtractor extends PairProducer {\n /**\n * @param messages - Chat history to extract pairs from\n * @param options - Extraction configuration\n */\n constructor(\n private messages: UIMessage[],\n private options: MessageExtractorOptions = {},\n ) {\n super();\n }\n\n /**\n * Extracts question-SQL pairs by parsing tool calls and pairing with user messages.\n * @returns Pairs extracted from db_query tool invocations\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const { includeFailures = false, toolName = 'db_query' } = this.options;\n let lastUserMessage: UIMessage | null = null;\n\n for (const message of this.messages) {\n if (message.role === 'user') {\n lastUserMessage = message;\n continue;\n }\n\n if (message.role === 'assistant' && lastUserMessage) {\n for (const part of message.parts) {\n if (!isToolOrDynamicToolUIPart(part)) {\n continue;\n }\n\n if (getToolOrDynamicToolName(part) !== toolName) {\n continue;\n }\n\n // Handle both static and dynamic tool part shapes\n const toolInput = ('input' in part ? part.input : undefined) as\n | DbQueryInput\n | undefined;\n if (!toolInput?.sql) {\n continue;\n }\n\n const success = part.state === 'output-available';\n const failed = part.state === 'output-error';\n\n if (failed && !includeFailures) {\n continue;\n }\n\n // Skip incomplete tool calls (streaming or pending)\n if (!success && !failed) {\n continue;\n }\n\n const question = getMessageText(lastUserMessage);\n if (!question) {\n continue;\n }\n\n yield [\n {\n question,\n sql: toolInput.sql,\n success,\n },\n ];\n }\n }\n }\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport {\n type UIMessage,\n getToolOrDynamicToolName,\n isTextUIPart,\n isToolOrDynamicToolUIPart,\n} from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface DbQueryInput {\n sql: string;\n reasoning?: string;\n}\n\nexport interface SqlWithContext {\n sql: string;\n success: boolean;\n conversationContext: string[];\n}\n\nexport interface BaseContextualExtractorOptions {\n includeFailures?: boolean;\n toolName?: string;\n}\nexport const contextResolverAgent = agent<\n { question: string },\n { conversation: string; sql: string; introspection?: string }\n>({\n name: 'context_resolver',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n question: z\n .string()\n .describe(\n 'A standalone natural language question that the SQL query answers',\n ),\n }),\n prompt: (state) => dedent`\n <identity>\n You are an expert at understanding conversational context and generating clear,\n standalone questions from multi-turn conversations.\n </identity>\n\n ${state?.introspection ? `<schema>\\n${state.introspection}\\n</schema>` : ''}\n\n <conversation>\n ${state?.conversation}\n </conversation>\n\n <sql>\n ${state?.sql}\n </sql>\n\n <task>\n Given the conversation above and the SQL query that was executed,\n generate a single, standalone natural language question that:\n 1. Fully captures the user's intent without needing prior context\n 2. Uses natural business language (not SQL terminology)\n 3. Could be asked by someone who hasn't seen the conversation\n 4. Accurately represents what the SQL query answers\n </task>\n\n <examples>\n Conversation: \"Show me customers\" \u2192 \"Filter to NY\" \u2192 \"Sort by revenue\"\n SQL: SELECT * FROM customers WHERE region = 'NY' ORDER BY revenue DESC\n Question: \"Show me customers in the NY region sorted by revenue\"\n\n Conversation: \"What were sales last month?\" \u2192 \"Break it down by category\"\n SQL: SELECT category, SUM(amount) FROM sales WHERE date >= '2024-11-01' GROUP BY category\n Question: \"What were sales by category for last month?\"\n </examples>\n `,\n});\n\nexport function getMessageText(message: UIMessage): string {\n const textParts = message.parts.filter(isTextUIPart).map((part) => part.text);\n return textParts.join(' ').trim();\n}\n\nexport function formatConversation(messages: string[]): string {\n return messages.map((msg, i) => `[${i + 1}] ${msg}`).join('\\n');\n}\n\n/**\n * Abstract base class for contextual extractors using Template Pattern.\n *\n * The `produce()` method defines the algorithm skeleton:\n * 1. Iterate through messages\n * 2. Call `onUserMessage()` hook for user messages\n * 3. Extract SQL from assistant messages using `getContextSnapshot()` hook\n * 4. Resolve questions using LLM\n *\n * Subclasses implement the hooks to customize context management.\n */\nexport abstract class BaseContextualExtractor extends PairProducer {\n protected context: string[] = [];\n protected results: SqlWithContext[] = [];\n\n constructor(\n protected messages: UIMessage[],\n protected adapter: Adapter,\n protected options: BaseContextualExtractorOptions = {},\n ) {\n super();\n }\n\n /**\n * Template method - defines the extraction algorithm skeleton.\n * Subclasses customize behavior via hooks, not by overriding this method.\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n // Reset state for each produce() invocation to prevent race conditions\n // if produce() is called multiple times concurrently\n this.context = [];\n this.results = [];\n\n const { includeFailures = false, toolName = 'db_query' } = this.options;\n\n // Step 1: Extract SQLs with context (calls hooks)\n await this.extractSqlsWithContext(toolName, includeFailures);\n\n if (this.results.length === 0) {\n return;\n }\n\n // Step 2: Get introspection for schema context\n const introspection = await this.adapter.introspect();\n\n // Step 3: Resolve each SQL's context into a standalone question\n yield* this.resolveQuestions(introspection);\n }\n\n /**\n * Core extraction loop - iterates through messages and calls hooks.\n */\n private async extractSqlsWithContext(\n toolName: string,\n includeFailures: boolean,\n ): Promise<void> {\n for (const message of this.messages) {\n if (message.role === 'user') {\n const text = getMessageText(message);\n if (text) {\n await this.onUserMessage(text);\n }\n continue;\n }\n\n if (message.role === 'assistant') {\n await this.extractFromAssistant(message, toolName, includeFailures);\n }\n }\n }\n\n /**\n * Extract SQL from assistant message parts.\n */\n private async extractFromAssistant(\n message: UIMessage,\n toolName: string,\n includeFailures: boolean,\n ): Promise<void> {\n for (const part of message.parts) {\n if (!isToolOrDynamicToolUIPart(part)) {\n continue;\n }\n\n if (getToolOrDynamicToolName(part) !== toolName) {\n continue;\n }\n\n // Use 'input' property (not 'args') to match useChat structure\n const toolInput = ('input' in part ? part.input : undefined) as\n | DbQueryInput\n | undefined;\n if (!toolInput?.sql) {\n continue;\n }\n\n const success = part.state === 'output-available';\n const failed = part.state === 'output-error';\n\n if (failed && !includeFailures) {\n continue;\n }\n\n // Skip if still streaming or not yet executed\n if (!success && !failed) {\n continue;\n }\n\n const snapshot = this.getContextSnapshot();\n // Skip if no context available\n if (snapshot.length === 0) {\n continue;\n }\n\n this.results.push({\n sql: toolInput.sql,\n success,\n conversationContext: snapshot,\n });\n }\n\n // Add assistant text responses to context (for multi-turn understanding)\n const assistantText = getMessageText(message);\n if (assistantText) {\n this.context.push(`Assistant: ${assistantText}`);\n }\n }\n\n /**\n * Resolve extracted SQL contexts into standalone questions using LLM.\n */\n protected async *resolveQuestions(\n introspection: string,\n ): AsyncGenerator<ExtractedPair[]> {\n for (const item of this.results) {\n const { experimental_output } = await generate(\n contextResolverAgent,\n [user('Generate a standalone question for this SQL query.')],\n {\n conversation: formatConversation(item.conversationContext),\n sql: item.sql,\n introspection,\n },\n );\n\n yield [\n {\n question: experimental_output.question,\n sql: item.sql,\n context: item.conversationContext,\n success: item.success,\n },\n ];\n }\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // HOOKS - Subclasses override these to customize context management\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Hook called when a user message is encountered.\n * Subclasses implement this to decide how to update context.\n */\n protected abstract onUserMessage(text: string): Promise<void>;\n\n /**\n * Hook called when extracting SQL to get the current context snapshot.\n * Subclasses implement this to decide what context to include.\n */\n protected abstract getContextSnapshot(): string[];\n}\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface SqlExtractorOptions {\n validateSql?: boolean;\n skipInvalid?: boolean;\n}\n\nconst sqlToQuestionAgent = agent<\n { question: string },\n { sql: string; introspection: string }\n>({\n name: 'sql_to_question',\n model: groq('llama-3.3-70b-versatile'),\n output: z.object({\n question: z\n .string()\n .describe('A natural language question that the SQL query answers'),\n }),\n prompt: (state) => dedent`\n <identity>\n You are an expert at understanding SQL queries and generating clear,\n natural language questions that describe what the query retrieves.\n </identity>\n\n <schema>\n ${state?.introspection}\n </schema>\n\n <sql>\n ${state?.sql}\n </sql>\n\n <task>\n Given the database schema and the SQL query above, generate a single\n natural language question that:\n 1. Accurately describes what information the query retrieves\n 2. Uses natural business language (not SQL terminology)\n 3. Could be asked by a non-technical user\n 4. Is concise but complete\n </task>\n\n <examples>\n SQL: SELECT COUNT(*) FROM customers WHERE region = 'NY'\n Question: \"How many customers do we have in New York?\"\n\n SQL: SELECT product_name, SUM(quantity) as total FROM orders GROUP BY product_name ORDER BY total DESC LIMIT 10\n Question: \"What are our top 10 products by quantity sold?\"\n\n SQL: SELECT c.name, COUNT(o.id) FROM customers c LEFT JOIN orders o ON c.id = o.customer_id GROUP BY c.id HAVING COUNT(o.id) = 0\n Question: \"Which customers have never placed an order?\"\n </examples>\n `,\n});\n/**\n * SqlExtractor - Generate questions for existing SQL queries.\n *\n * Given a list of SQL queries, uses an LLM to generate the natural\n * language questions they answer.\n */\nexport class SqlExtractor extends PairProducer {\n #sqls: string[];\n #adapter: Adapter;\n #options: SqlExtractorOptions;\n\n /**\n * @param sql - SQL query or queries to generate questions for\n * @param adapter - Database adapter for validation and schema introspection\n * @param options - Extraction configuration\n */\n constructor(\n sql: string[] | string,\n adapter: Adapter,\n options: SqlExtractorOptions = {},\n ) {\n super();\n this.#sqls = Array.isArray(sql) ? sql : [sql];\n this.#adapter = adapter;\n this.#options = options;\n }\n\n /**\n * Generates natural language questions for each SQL query using an LLM.\n * @returns Pairs with generated questions and original SQL\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const { validateSql = true, skipInvalid = false } = this.#options;\n const introspection = await this.#adapter.introspect();\n\n for (const sql of this.#sqls) {\n let isValid = true;\n if (validateSql) {\n const error = await this.#adapter.validate(sql);\n isValid = error === undefined || error === null;\n\n if (!isValid && skipInvalid) {\n continue;\n }\n }\n\n const { experimental_output } = await generate(\n sqlToQuestionAgent,\n [user('Generate a natural language question for this SQL query.')],\n {\n sql,\n introspection,\n },\n );\n\n yield [\n {\n question: experimental_output.question,\n sql,\n success: isValid,\n },\n ];\n }\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n} from './base-contextual-extractor.ts';\n\nexport type FullContextExtractorOptions = BaseContextualExtractorOptions;\n\n/**\n * Extracts SQL pairs with full conversation context.\n *\n * @example\n * ```typescript\n * const extractor = new FullContextExtractor(messages, adapter);\n * const pairs = await extractor.produce();\n * ```\n */\nexport class FullContextExtractor extends BaseContextualExtractor {\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: FullContextExtractorOptions = {},\n ) {\n super(messages, adapter, options);\n }\n\n /**\n * Add user message to context (keeps all messages).\n */\n protected async onUserMessage(text: string): Promise<void> {\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return all context accumulated so far.\n */\n protected getContextSnapshot(): string[] {\n return [...this.context];\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n} from './base-contextual-extractor.ts';\n\nexport interface WindowedContextExtractorOptions\n extends BaseContextualExtractorOptions {\n windowSize: number;\n}\n\n/**\n * Extracts SQL pairs with a sliding window of conversation context.\n *\n * @example\n * ```typescript\n * const extractor = new WindowedContextExtractor(messages, adapter, {\n * windowSize: 5,\n * });\n * const pairs = await extractor.produce();\n * ```\n */\nexport class WindowedContextExtractor extends BaseContextualExtractor {\n private windowSize: number;\n\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: WindowedContextExtractorOptions,\n ) {\n super(messages, adapter, options);\n this.windowSize = options.windowSize;\n }\n\n /**\n * Add user message to context (keeps all, windowing happens on snapshot).\n */\n protected async onUserMessage(text: string): Promise<void> {\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return only the last N messages based on window size.\n */\n protected getContextSnapshot(): string[] {\n if (this.context.length <= this.windowSize) {\n return [...this.context];\n }\n return this.context.slice(-this.windowSize);\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport type { UIMessage } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n contextResolverAgent,\n formatConversation,\n} from './base-contextual-extractor.ts';\n\nexport type SegmentedContextExtractorOptions = BaseContextualExtractorOptions;\n\n/** Agent that detects if a new message represents a topic change */\nconst topicChangeAgent = agent<\n { isTopicChange: boolean; reason: string },\n { context: string; newMessage: string }\n>({\n name: 'topic_change_detector',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n isTopicChange: z\n .boolean()\n .describe('Whether the new message represents a topic change'),\n reason: z.string().describe('Brief explanation for the decision'),\n }),\n prompt: (state) => dedent`\n <identity>\n You are an expert at understanding conversational flow and detecting topic changes.\n </identity>\n\n <conversation_context>\n ${state?.context || '(no prior context)'}\n </conversation_context>\n\n <new_message>\n ${state?.newMessage}\n </new_message>\n\n <task>\n Determine if the new message represents a significant topic change from the\n prior conversation context. A topic change occurs when:\n 1. The user asks about a completely different entity/table/domain\n 2. The user starts a new analytical question unrelated to prior discussion\n 3. There's a clear shift in what data or metrics are being discussed\n\n NOT a topic change:\n - Follow-up questions refining the same query (\"filter by...\", \"sort by...\")\n - Questions about the same entities with different conditions\n - Requests for more details on the same topic\n </task>\n\n <examples>\n Context: \"Show me customers in NY\" \u2192 \"Sort by revenue\"\n New: \"Filter to those with orders over $1000\"\n Decision: NOT a topic change (still refining customer query)\n\n Context: \"Show me customers in NY\" \u2192 \"Sort by revenue\"\n New: \"What were our total sales last quarter?\"\n Decision: Topic change (shifted from customers to sales metrics)\n\n Context: \"List all products\"\n New: \"How many orders did we have last month?\"\n Decision: Topic change (products \u2192 orders/sales)\n </examples>\n `,\n});\n\n/**\n * Extracts SQL pairs with topic-aware context segmentation.\n *\n * When a topic change is detected:\n * 1. The triggering message is resolved to standalone form using LLM\n * 2. Context is reset\n * 3. The resolved message becomes the start of the new context\n *\n * @example\n * ```typescript\n * const extractor = new SegmentedContextExtractor(messages, adapter);\n * const pairs = await extractor.produce();\n * ```\n */\nexport class SegmentedContextExtractor extends BaseContextualExtractor {\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: SegmentedContextExtractorOptions = {},\n ) {\n super(messages, adapter, options);\n }\n\n /**\n * Handle user message with topic change detection.\n * If topic changes, resolve the message to standalone form before resetting.\n *\n * Note: We capture context snapshot before async LLM calls to prevent race conditions\n * where context might be modified during the async operation.\n */\n protected async onUserMessage(text: string): Promise<void> {\n // Check for topic change if we have enough context\n if (this.context.length >= 2) {\n // Capture snapshot BEFORE async calls to prevent race conditions\n const contextSnapshot = [...this.context];\n const isTopicChange = await this.detectTopicChange(text, contextSnapshot);\n if (isTopicChange) {\n // Resolve the triggering message BEFORE resetting context\n const resolved = await this.resolveToStandalone(text, contextSnapshot);\n this.context = [`User: ${resolved}`];\n return;\n }\n }\n\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return all context in current topic segment.\n */\n protected getContextSnapshot(): string[] {\n return [...this.context];\n }\n\n /**\n * Detect if a new message represents a topic change using LLM.\n * @param newMessage - The new user message to check\n * @param contextSnapshot - Snapshot of context captured before this async call\n */\n private async detectTopicChange(\n newMessage: string,\n contextSnapshot: string[],\n ): Promise<boolean> {\n const { experimental_output } = await generate(\n topicChangeAgent,\n [user('Determine if this is a topic change.')],\n {\n context: formatConversation(contextSnapshot),\n newMessage,\n },\n );\n\n return experimental_output.isTopicChange;\n }\n\n /**\n * Resolve a context-dependent message into a standalone question.\n * Called when topic change is detected to preserve the meaning of\n * the triggering message before context is reset.\n * @param text - The user message to resolve\n * @param contextSnapshot - Snapshot of context captured before this async call\n */\n private async resolveToStandalone(\n text: string,\n contextSnapshot: string[],\n ): Promise<string> {\n const { experimental_output } = await generate(\n contextResolverAgent,\n [user('Generate a standalone question for this message.')],\n {\n conversation: formatConversation([...contextSnapshot, `User: ${text}`]),\n sql: '', // No SQL yet, just resolving the question\n },\n );\n\n return experimental_output.question;\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport { generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport type { ExtractedPair } from '../types.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n contextResolverAgent,\n formatConversation,\n} from './base-contextual-extractor.ts';\n\nexport type LastQueryExtractorOptions = BaseContextualExtractorOptions;\n\n/**\n * Extracts only the last SQL query with its resolved question.\n *\n * @example\n * ```typescript\n * const extractor = new LastQueryExtractor(messages, adapter);\n * const pairs = await toPairs(extractor); // Returns array with at most 1 pair\n * ```\n */\nexport class LastQueryExtractor extends BaseContextualExtractor {\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: LastQueryExtractorOptions = {},\n ) {\n super(messages, adapter, options);\n }\n\n /**\n * Add user message to context (keeps all messages).\n */\n protected async onUserMessage(text: string): Promise<void> {\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return all context accumulated so far.\n */\n protected getContextSnapshot(): string[] {\n return [...this.context];\n }\n\n /**\n * Override to only resolve the LAST query instead of all queries.\n */\n protected override async *resolveQuestions(\n introspection: string,\n ): AsyncGenerator<ExtractedPair[]> {\n if (this.results.length === 0) {\n return;\n }\n\n const last = this.results.at(-1)!;\n const { experimental_output } = await generate(\n contextResolverAgent,\n [user('Generate a standalone question for this SQL query.')],\n {\n conversation: formatConversation(last.conversationContext),\n sql: last.sql,\n introspection,\n },\n );\n\n yield [\n {\n question: experimental_output.question,\n sql: last.sql,\n context: last.conversationContext,\n success: last.success,\n },\n ];\n }\n}\n", "import pLimit from 'p-limit';\n\nimport type { AgentModel } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n type QuestionComplexity,\n generateQuestions,\n} from '../../agents/question.agent.ts';\nimport { toSql } from '../../agents/sql.agent.ts';\nimport type { Teachables } from '../../teach/teachables.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\nimport type { Persona } from './persona-generator.ts';\n\nexport interface SchemaSynthesizerOptions {\n count: number;\n complexity?: QuestionComplexity | QuestionComplexity[];\n personas?: Persona[];\n teachings?: Teachables[];\n model?: AgentModel;\n concurrency?: number;\n}\n/**\n * SchemaSynthesizer - Generate pairs from database schema.\n *\n * Fully synthetic: generates natural language questions at specified\n * complexity levels and personas, then generates SQL for each question.\n * Iterates through all persona \u00D7 complexity combinations.\n */\nexport class SchemaSynthesizer extends PairProducer {\n #complexities: QuestionComplexity[] = [];\n #personas: (Persona | undefined)[] = [];\n #limit: ReturnType<typeof pLimit>;\n\n /**\n * @param adapter - Database adapter for schema introspection and SQL validation\n * @param options - Synthesis configuration including count, complexity, and concurrency\n */\n constructor(\n private adapter: Adapter,\n private options: SchemaSynthesizerOptions,\n ) {\n super();\n this.#complexities = Array.isArray(this.options.complexity)\n ? this.options.complexity\n : [this.options.complexity ?? 'medium'];\n\n this.#personas = this.options.personas ?? [undefined];\n this.#limit = pLimit(this.options.concurrency ?? 5);\n }\n\n /**\n * Generates question-SQL pairs by iterating through all persona \u00D7 complexity combinations.\n * Uses parallel processing bounded by the configured concurrency limit.\n * Yields results as each combination completes (streaming pattern).\n * @returns Generated pairs from all combinations\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const introspection = await this.adapter.introspect();\n\n const combinations = this.#personas.flatMap((persona) =>\n this.#complexities.map((complexity) => ({ persona, complexity })),\n );\n\n // Process each combination and yield immediately as it completes\n // pLimit handles concurrency - no need to create all promises upfront\n for (const { persona, complexity } of combinations) {\n const pairs = await this.#processCombination(\n introspection,\n persona,\n complexity,\n );\n if (pairs.length) {\n yield pairs;\n }\n }\n }\n\n /**\n * Processes a single persona \u00D7 complexity combination by generating questions\n * and converting each to SQL in parallel.\n */\n async #processCombination(\n introspection: Awaited<ReturnType<Adapter['introspect']>>,\n persona: Persona | undefined,\n complexity: QuestionComplexity,\n ): Promise<ExtractedPair[]> {\n const personaContext = persona\n ? `As ${persona.role}, ${persona.perspective}\\n\\nGenerate questions this persona would ask.`\n : undefined;\n\n const prompt = personaContext\n ? `${personaContext}\\n\\nGenerate ${this.options.count} questions at ${complexity} complexity.`\n : undefined;\n\n const { questions } = await this.#limit(() =>\n generateQuestions({\n introspection,\n complexity,\n count: this.options.count,\n prompt,\n model: this.options.model,\n }),\n );\n\n const pairs = await Promise.all(\n questions.map(async (question) => {\n const result = await this.#limit(() =>\n toSql({\n input: question,\n adapter: this.adapter,\n introspection,\n instructions: this.options.teachings ?? [],\n model: this.options.model,\n }),\n );\n\n return {\n question,\n sql: result.sql,\n success: !result.errors || result.errors.length === 0,\n };\n }),\n );\n\n return pairs;\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nexport type QuestionComplexity = 'low' | 'medium' | 'hard' | 'window';\n\ntype QuestionGeneratorState = {\n introspection: string;\n complexity: QuestionComplexity;\n count: number;\n};\n\ntype QuestionGeneratorOutput = {\n questions: string[];\n};\n\nconst complexityInstructions: Record<QuestionComplexity, string> = {\n low: dedent`\n Generate simple questions that require:\n - Basic SELECT with single table\n - Simple WHERE clauses with one condition\n - COUNT(*) or basic aggregations\n - No joins required\n Examples: \"How many customers do we have?\", \"List all products\", \"What is the total revenue?\"\n `,\n medium: dedent`\n Generate moderate questions that require:\n - JOINs between 2-3 tables\n - Multiple WHERE conditions (AND/OR)\n - GROUP BY with HAVING clauses\n - ORDER BY with LIMIT\n - Basic subqueries\n Examples: \"What are the top 5 customers by total orders?\", \"Which products have never been ordered?\"\n `,\n hard: dedent`\n Generate complex questions that require:\n - Multiple JOINs (3+ tables)\n - Nested subqueries or CTEs\n - Complex aggregations with multiple GROUP BY columns\n - CASE expressions\n - Date/time calculations\n Examples: \"What is the month-over-month growth rate?\", \"Which customers have increased spending compared to last year?\"\n `,\n window: dedent`\n Generate advanced questions that require window functions:\n - ROW_NUMBER, RANK, DENSE_RANK\n - LAG, LEAD for comparisons\n - Running totals (SUM OVER)\n - Moving averages\n - PARTITION BY clauses\n Examples: \"What is the running total of sales per month?\", \"Rank customers by their purchase frequency within each region\"\n `,\n};\n\n/**\n * Agent that generates natural language questions from database introspection.\n * Used for creating synthetic training data for text-to-SQL models.\n */\nconst questionGeneratorAgent = agent<\n QuestionGeneratorOutput,\n QuestionGeneratorState\n>({\n name: 'question_generator',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.8, topP: 0.95 },\n }),\n }),\n handoffDescription:\n 'Generates natural language questions that users might ask about the database schema.',\n output: z.object({\n questions: z\n .array(z.string().describe('A natural language question about the data'))\n .min(1)\n .describe('List of natural language questions a user might ask'),\n }),\n prompt: (state) => {\n const count = state?.count;\n const complexity = state?.complexity ?? 'medium';\n\n return dedent`\n <identity>\n You are a synthetic data generator specializing in creating realistic natural language questions\n that users might ask about a database. You understand database schemas and can generate diverse,\n practical questions that would require SQL queries to answer.\n </identity>\n\n ${state?.introspection || ''}\n\n <complexity level=\"${complexity}\">\n ${complexityInstructions[complexity]}\n </complexity>\n\n <task>\n Generate exactly ${count} natural language questions at the \"${complexity}\" complexity level.\n The questions should:\n 1. Match the complexity requirements above\n 2. Use natural business language, not technical SQL terms\n 3. Be realistic questions a non-technical user would actually ask\n 4. Cover different tables and relationships when possible\n </task>\n\n <guardrails>\n - Questions MUST ONLY reference tables and columns that exist in the schema above\n - Before generating each question, verify that ALL entities (tables, columns, relationships) you reference are explicitly listed in the schema\n - DO NOT invent or assume tables/columns that aren't explicitly shown in the schema\n - Use natural language without SQL keywords like SELECT, WHERE, etc.\n - All questions must match the specified complexity level\n </guardrails>\n `;\n },\n});\n\nexport interface GenerateQuestionsParams {\n /** Database schema introspection */\n introspection: string;\n /** Complexity level for generated questions */\n complexity: QuestionComplexity;\n /** Number of questions to generate */\n count: number;\n /** Optional prompt to prepend (e.g., persona context) */\n prompt?: string;\n /** Optional model override */\n model?: AgentModel;\n}\n\nexport interface GenerateQuestionsResult {\n questions: string[];\n}\n\n/**\n * Generate natural language questions from database schema.\n * Used for creating synthetic training data for text-to-SQL models.\n */\nexport async function generateQuestions(\n params: GenerateQuestionsParams,\n): Promise<GenerateQuestionsResult> {\n const { introspection, complexity, count, prompt, model } = params;\n\n const agentInstance = model\n ? questionGeneratorAgent.clone({ model })\n : questionGeneratorAgent;\n\n const userPrompt =\n prompt ?? `Generate ${count} questions at ${complexity} complexity given db schema.`;\n\n const { experimental_output } = await generate(agentInstance, [user(userPrompt)], {\n introspection,\n complexity,\n count,\n });\n\n return { questions: experimental_output.questions };\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\ntype SqlGeneratorState = {\n // FIXME: this should not be here after creating the context package\n introspection: string;\n teachings: string;\n};\n\ntype SqlGeneratorOutput =\n | { sql: string; reasoning?: string }\n | { error: string };\n\n/**\n * Agent that generates SQL queries from introspection and natural language questions.\n * Used for creating synthetic training data for text-to-SQL models.\n */\n/** Temperature progression for retries: deterministic first, then increasingly exploratory */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\n\nconst sqlQueryAgent = agent<SqlGeneratorOutput, SqlGeneratorState>({\n name: 'text2sql',\n model: groq('openai/gpt-oss-20b'),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.union([\n z.object({\n sql: z.string().describe('The SQL query that answers the question'),\n reasoning: z\n .string()\n .optional()\n .describe('The reasoning steps taken to generate the SQL'),\n }),\n z.object({\n error: z\n .string()\n .describe(\n 'Error message explaining why the question cannot be answered with the given schema',\n ),\n }),\n ]),\n prompt: (state) => {\n return `\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n `;\n },\n});\n\n/** Extract SQL from markdown fenced code block if present */\nfunction extractSql(output: string): string {\n const match = output.match(/```sql\\n?([\\s\\S]*?)```/);\n return match ? match[1].trim() : output.trim();\n}\n\nexport type GenerateSqlResult =\n | { success: true; sql: string }\n | { success: false; error: string; isUnanswerable?: boolean };\n\nexport type GenerateSqlParams = {\n input: string;\n model: AgentModel;\n temperature: number;\n introspection: string;\n instructions: Teachables[];\n previousError?: string;\n};\n\ntype StepResult =\n | { ok: true; sql: string }\n | { ok: false; error: string; isUnanswerable?: boolean };\n\n/**\n * Generate SQL from natural language using the SQL agent.\n * Handles JSON validation errors from the API by returning an error result.\n */\nasync function generateSql(\n params: GenerateSqlParams,\n): Promise<GenerateSqlResult> {\n const {\n input,\n model,\n temperature,\n introspection,\n instructions,\n previousError,\n } = params;\n\n const agentInstance = sqlQueryAgent.clone({\n model: wrapLanguageModel({\n model,\n middleware: defaultSettingsMiddleware({\n settings: { temperature, topP: 1 },\n }),\n }),\n });\n\n const messages = previousError\n ? [\n user(input),\n user(\n `<validation_error>Your previous SQL query had the following error: ${previousError}. Please fix the query.</validation_error>`,\n ),\n ]\n : [user(input)];\n\n try {\n const { experimental_output: output } = await generate(\n agentInstance,\n messages,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator. You translate natural language questions into precise, efficient SQL queries based on the provided database schema.',\n }),\n ...instructions,\n ),\n introspection,\n },\n );\n\n // Handle error responses (question is unanswerable with given schema)\n if ('error' in output) {\n return { success: false, error: output.error, isUnanswerable: true };\n }\n\n return { success: true, sql: extractSql(output.sql) };\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message.includes('Failed to validate JSON') ||\n error.message.includes('response did not match schema'))\n ) {\n return {\n success: false,\n error: `Schema validation failed: ${error.message}`,\n };\n }\n throw error;\n }\n}\n\n/**\n * Exported object for mockability in tests.\n * Use `mock.method(sqlGenerators, 'generateSql', ...)` to mock.\n */\nexport const sqlGenerators = {\n generateSql,\n};\n\n/**\n * Generate SQL and validate it in a single step.\n * Returns a unified result for both generation and validation errors.\n */\nasync function generateAndValidate(\n options: ToSqlOptions,\n temperature: number,\n previousError?: string,\n): Promise<StepResult> {\n const result = await sqlGenerators.generateSql({\n input: options.input,\n model: options.model ?? sqlQueryAgent.model,\n temperature,\n introspection: options.introspection,\n instructions: options.instructions,\n previousError,\n });\n\n if (!result.success) {\n return {\n ok: false,\n error: result.error,\n isUnanswerable: result.isUnanswerable,\n };\n }\n\n const validationError = await options.adapter.validate(result.sql);\n if (validationError) {\n return { ok: false, error: validationError };\n }\n\n return { ok: true, sql: result.sql };\n}\n\nexport interface ToSqlOptions {\n /** The natural language input to convert to SQL */\n input: string;\n /** Database adapter for validation */\n adapter: Adapter;\n /** Introspection/schema context */\n introspection: string;\n /** Instructions/teachings to include */\n instructions: Teachables[];\n /** Optional model override */\n model?: AgentModel;\n /** Maximum retry attempts on validation failure (default: 3) */\n maxRetries?: number;\n}\n\nexport interface ToSqlResult {\n /** The generated SQL query */\n sql: string;\n /** Number of attempts made */\n attempts: number;\n /** Validation errors encountered (if any retries occurred) */\n errors?: string[];\n}\n\n/**\n * Generate SQL from natural language with post-generation validation.\n * Retries generation if validation fails, including the error in the retry prompt.\n * Also retries on API-level JSON validation errors from the model.\n * Does NOT retry when the question is unanswerable (intentional error response).\n */\nexport async function toSql(options: ToSqlOptions): Promise<ToSqlResult> {\n const { maxRetries = 3 } = options;\n const errors: string[] = [];\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const temperature = RETRY_TEMPERATURES[attempt - 1] ?? 0.3;\n const result = await generateAndValidate(\n options,\n temperature,\n errors.at(-1),\n );\n\n if (result.ok) {\n return {\n sql: result.sql,\n attempts: attempt,\n errors: errors.length ? errors : undefined,\n };\n }\n\n // Don't retry if the question is unanswerable - it's an intentional error\n if (result.isUnanswerable) {\n return { sql: '', attempts: attempt, errors: [result.error] };\n }\n\n errors.push(result.error);\n }\n\n return { sql: '', attempts: maxRetries, errors };\n}\n", "export function wrapBlock(tag: string, children: string[]): string {\n const content = children\n .filter((child): child is string => Boolean(child))\n .join('\\n');\n if (!content) {\n return '';\n }\n return `<${tag}>\\n${indentBlock(content, 2)}\\n</${tag}>`;\n}\n\nexport function list(tag: string, values: string[], childTag: string): string {\n if (!values.length) {\n return '';\n }\n const children = values.map((value) => leaf(childTag, value)).join('\\n');\n return `<${tag}>\\n${indentBlock(children, 2)}\\n</${tag}>`;\n}\n\nexport function leaf(tag: string, value: string): string {\n const safe = escapeXml(value);\n if (safe.includes('\\n')) {\n return `<${tag}>\\n${indentBlock(safe, 2)}\\n</${tag}>`;\n }\n return `<${tag}>${safe}</${tag}>`;\n}\n\nexport function indentBlock(text: string, spaces: number): string {\n if (!text.trim()) {\n return '';\n }\n const padding = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.length ? padding + line : padding))\n .join('\\n');\n}\n\nexport function escapeXml(value: string): string {\n if (value == null) {\n return '';\n }\n return value\n .replaceAll(/&/g, '&')\n .replaceAll(/</g, '<')\n .replaceAll(/>/g, '>')\n .replaceAll(/\"/g, '"')\n .replaceAll(/'/g, ''');\n}\n", "import { indentBlock, leaf, list, wrapBlock } from './xml.ts';\n\nexport interface Teachables {\n type: GeneratedTeachable['type'] | 'user_profile';\n /** Serialize to GeneratedTeachable for storage */\n encode: () => GeneratedTeachable;\n /** Render to XML string for prompts */\n decode: () => string;\n}\nexport type GeneratedTeachable =\n | { type: 'term'; name: string; definition: string }\n | { type: 'hint'; text: string }\n | { type: 'guardrail'; rule: string; reason?: string; action?: string }\n | {\n type: 'explain';\n concept: string;\n explanation: string;\n therefore?: string;\n }\n | { type: 'example'; question: string; answer: string; note?: string }\n | { type: 'clarification'; when: string; ask: string; reason: string }\n | {\n type: 'workflow';\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n }\n | { type: 'quirk'; issue: string; workaround: string }\n | { type: 'styleGuide'; prefer: string; never?: string; always?: string }\n | {\n type: 'analogy';\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n }\n | { type: 'glossary'; entries: Record<string, string> }\n // User-specific teachable types\n | { type: 'identity'; name?: string; role?: string }\n | { type: 'persona'; name: string; role: string; tone: string }\n | { type: 'alias'; term: string; meaning: string }\n | { type: 'preference'; aspect: string; value: string }\n | { type: 'context'; description: string }\n | { type: 'correction'; subject: string; clarification: string };\n\n/**\n * Teach the system domain-specific vocabulary and business terminology.\n *\n * Use this to define simple, direct mappings between business terms and their meanings.\n * The system will understand these terms when users mention them in queries.\n *\n * @param name - The business term or acronym to define\n * @param definition - What the term means in your domain\n *\n * @example\n * // Logistics/Transportation dataset\n * term(\"deadhead miles\", \"distance driven with empty truck between deliveries\")\n * term(\"dwell time\", \"total time a truck spends at a loading dock or warehouse\")\n * term(\"LTL\", \"less than truckload - shipment that doesn't fill entire truck\")\n *\n * @example\n * // Education/University dataset\n * term(\"matriculation\", \"students who completed enrollment and started classes\")\n * term(\"DFW rate\", \"percentage of students receiving D, F, or Withdrawal in a course\")\n * term(\"cohort\", \"group of students who entered the same semester or academic year\")\n *\n * @example\n * // Finance/Banking dataset\n * term(\"NPL\", \"non-performing loan - loan past due 90+ days\")\n * term(\"basis points\", \"one hundredth of a percentage point (1% = 100 bps)\")\n * term(\"AUM\", \"assets under management - total market value of client investments\")\n */\nexport function term(name: string, definition: string): Teachables {\n return {\n type: 'term',\n encode: () => ({ type: 'term', name, definition }),\n decode: () =>\n wrapBlock('term', [leaf('name', name), leaf('definition', definition)]),\n };\n}\n\n/**\n * Teach the system behavioral rules and constraints that should always apply.\n *\n * Use this for business logic, data quality rules, or query preferences that should\n * be automatically applied to all relevant queries. Hints are injected as constraints\n * in the system prompt.\n *\n * @param text - The rule or constraint to follow (use imperative language)\n *\n * @example\n * // Manufacturing/Supply Chain dataset\n * hint(\"Always exclude work orders with status = 'simulation' from production metrics\")\n * hint(\"When calculating OEE (overall equipment effectiveness), only count scheduled production time\")\n * hint(\"Defect rates should be calculated per batch, not per individual unit, for consistency\")\n *\n * @example\n * // Real Estate/Property dataset\n * hint(\"Never include properties with listing_status = 'draft' in market analysis\")\n * hint(\"Always filter out duplicate MLS listings - use the earliest listing_date for each property_id\")\n * hint(\"Square footage comparisons must specify if including or excluding basement/garage\")\n *\n * @example\n * // Social Media/Content Platform dataset\n * hint(\"Engagement metrics should exclude bot accounts identified by is_verified_human = false\")\n * hint(\"View counts reset daily - always use cumulative_views for historical analysis\")\n * hint(\"Default content filters to published_status = 'public' unless analyzing drafts\")\n */\nexport function hint(text: string): Teachables {\n return {\n type: 'hint',\n encode: () => ({ type: 'hint', text }),\n decode: () => leaf('hint', text),\n };\n}\n\n/**\n * Define hard guardrails, safety rules, and compliance boundaries the system must enforce.\n *\n * Use this for \"never do\" rules, sensitive data handling, and required behaviors when\n * certain conditions occur. Guardrails should be explicit and action oriented.\n *\n * @param input.rule - The guardrail or restriction to enforce\n * @param input.reason - Why this guardrail exists (compliance, security, performance)\n * @param input.action - What to do when this guardrail is triggered (block, ask, sanitize)\n *\n * @example\n * // Healthcare dataset\n * guardrail({\n * rule: \"Never return PHI like SSN, MRN, or full address in query results\",\n * reason: \"HIPAA compliance\",\n * action: \"If asked, state that identifiable patient data cannot be shared; offer de-identified aggregates instead\"\n * })\n *\n * @example\n * // Finance dataset\n * guardrail({\n * rule: \"Block any query exposing employee-level compensation by name\",\n * reason: \"Confidential payroll data\",\n * action: \"Provide ranges grouped by department or level instead of individual salaries\"\n * })\n *\n * @example\n * // E-commerce dataset\n * guardrail({\n * rule: \"Warn when a query would scan more than 10 million rows; require a narrower date range\",\n * reason: \"Performance and cost control\",\n * action: \"Ask the user to add filters (recent timeframe, specific categories) before proceeding\"\n * })\n */\nexport function guardrail(input: {\n rule: string;\n reason?: string;\n action?: string;\n}): Teachables {\n const { rule, reason, action } = input;\n return {\n type: 'guardrail',\n encode: () => ({ type: 'guardrail', rule, reason, action }),\n decode: () =>\n wrapBlock('guardrail', [\n leaf('rule', rule),\n reason ? leaf('reason', reason) : '',\n action ? leaf('action', action) : '',\n ]),\n };\n}\n\n/**\n * Teach the system a rich understanding of a single concept using metaphors and explanations.\n *\n * Use this when a simple term definition isn't enough - when you need to convey deeper\n * understanding about how to think about and calculate a metric or concept.\n *\n * @param input.concept - The concept being explained\n * @param input.explanation - A metaphor or detailed explanation (often using real-world comparisons)\n * @param input.therefore - Optional actionable instruction based on this understanding\n *\n * @example\n * // Gaming/Entertainment dataset\n * explain({\n * concept: \"daily active users to monthly active users ratio\",\n * explanation: \"like measuring how many club members visit daily vs just once a month - shows stickiness\",\n * therefore: \"Calculate as DAU / MAU, where higher ratio (closer to 1) means more engaged user base\"\n * })\n *\n * @example\n * // HR/Employee Management dataset\n * explain({\n * concept: \"time to fill\",\n * explanation: \"like measuring how long a house sits on the market - from posting job to accepting offer\",\n * therefore: \"Calculate as days between job_posted_date and offer_accepted_date, exclude cancelled requisitions\"\n * })\n *\n * @example\n * // Telecommunications dataset\n * explain({\n * concept: \"network congestion ratio\",\n * explanation: \"like rush hour traffic density - measures actual usage vs total capacity at peak times\",\n * therefore: \"Calculate as (peak_hour_bandwidth_used / total_bandwidth_capacity) during busiest hour of day\"\n * })\n */\nexport function explain(input: {\n concept: string;\n explanation: string;\n therefore?: string;\n}): Teachables {\n const { concept, explanation, therefore } = input;\n return {\n type: 'explain',\n encode: () => ({ type: 'explain', concept, explanation, therefore }),\n decode: () =>\n wrapBlock('explanation', [\n leaf('concept', concept),\n leaf('details', explanation),\n therefore ? leaf('therefore', therefore) : '',\n ]),\n };\n}\n\n/**\n * Teach the system through concrete examples of question \u2192 SQL pairs.\n *\n * Use this for few-shot learning - show the system exactly how to translate\n * specific types of questions into SQL queries. Great for establishing patterns\n * and handling domain-specific query structures.\n *\n * @param input.question - The natural language question or request\n * @param input.answer - The correct answer that responds to the question\n * @param input.note - Optional note or explanation about the example\n *\n * @example\n * // Energy/Utilities dataset\n * example({\n * question: \"show me peak demand hours for the last week\",\n * answer: \"SELECT DATE_TRUNC('hour', reading_timestamp) as hour, MAX(consumption_kwh) as peak_demand FROM meter_readings WHERE reading_timestamp >= CURRENT_DATE - INTERVAL '7 days' GROUP BY hour ORDER BY peak_demand DESC LIMIT 10\"\n * })\n *\n * @example\n * // Agriculture/Farm Management dataset\n * example({\n * question: \"what is the average yield per acre by crop type this season\",\n * answer: \"SELECT crop_type, AVG(harvest_quantity / field_acres) as yield_per_acre FROM harvests WHERE harvest_date >= '2024-01-01' GROUP BY crop_type ORDER BY yield_per_acre DESC\"\n * })\n *\n * @example\n * // Travel/Hospitality dataset\n * example({\n * question: \"show me hotel occupancy rate for this month\",\n * answer: \"SELECT hotel_name, (SUM(occupied_rooms) / SUM(total_rooms)) * 100 as occupancy_rate FROM daily_occupancy WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY hotel_id, hotel_name ORDER BY occupancy_rate DESC\",\n * note: \"Occupancy rate is a percentage - multiply by 100 for readable output\"\n * })\n */\nexport function example(input: {\n question: string;\n answer: string;\n note?: string;\n}): Teachables {\n const { question, answer, note } = input;\n return {\n type: 'example',\n encode: () => ({ type: 'example', question, answer, note }),\n decode: () =>\n wrapBlock('example', [\n leaf('question', question),\n leaf('answer', answer),\n note ? leaf('note', note) : '',\n ]),\n };\n}\n\n/**\n * Teach the system when and what to ask for clarification.\n *\n * Use this to handle ambiguous terms or situations where the system should\n * proactively ask the user for more information before generating a query.\n * Makes the system more conversational and precise.\n *\n * @param input.when - The condition or trigger that should prompt clarification\n * @param input.ask - The question to ask the user\n * @param input.reason - Why this clarification is necessary (helps system understand importance)\n *\n * @example\n * // Marketing/Advertising dataset\n * clarification({\n * when: \"user asks for 'conversion rate'\",\n * ask: \"Which conversion: click-to-lead, lead-to-opportunity, or opportunity-to-customer?\",\n * reason: \"Conversion rate means different things at each funnel stage - need to specify which metric\"\n * })\n *\n * @example\n * // Food Delivery dataset\n * clarification({\n * when: \"user asks about 'delivery time'\",\n * ask: \"Do you mean estimated time at order, actual delivery time, or time from kitchen to door?\",\n * reason: \"Multiple time metrics exist - estimated vs actual impacts customer satisfaction differently\"\n * })\n *\n * @example\n * // Fitness/Gym Management dataset\n * clarification({\n * when: \"user mentions 'active members'\",\n * ask: \"Do you mean paid memberships or members who actually visited in last 30 days?\",\n * reason: \"Many paid members don't use facilities - different metrics for revenue vs utilization\"\n * })\n */\nexport function clarification(input: {\n when: string;\n ask: string;\n reason: string;\n}): Teachables {\n const { when, ask, reason } = input;\n return {\n type: 'clarification',\n encode: () => ({ type: 'clarification', when, ask, reason }),\n decode: () =>\n wrapBlock('clarification', [\n leaf('when', when),\n leaf('ask', ask),\n leaf('reason', reason),\n ]),\n };\n}\n\n/**\n * Teach the system multi-step analytical processes that can't be solved with a single query.\n *\n * Use this for complex analytical tasks that require multiple CTEs, sequential logic,\n * or specific methodologies. Workflows teach the system HOW to approach a type of analysis.\n *\n * @param input.task - Name of the analytical task\n * @param input.steps - Sequential steps to execute (can include SQL snippets or descriptions)\n * @param input.triggers - Optional phrases that should activate this workflow\n * @param input.notes - Optional additional context, warnings, or guidance\n *\n * @example\n * // Insurance dataset\n * workflow({\n * task: \"Claims Loss Ratio Analysis\",\n * triggers: [\"loss ratio\", \"claims ratio\", \"underwriting performance\"],\n * steps: [\n * \"Calculate total claims paid for each policy period\",\n * \"Calculate total premiums earned for same period\",\n * \"Compute loss ratio as (claims_paid / premiums_earned) * 100\",\n * \"Segment by policy type, geography, and underwriter\",\n * \"Identify policies with loss ratio > 100% (losing money)\",\n * \"Calculate trend over time using rolling 12-month windows\"\n * ],\n * notes: \"Use incurred date for claims, not paid date. Exclude reinsurance recoveries from claims total.\"\n * })\n *\n * @example\n * // Media/Publishing dataset\n * workflow({\n * task: \"Content Performance Funnel\",\n * triggers: [\"content funnel\", \"engagement funnel\", \"content performance\"],\n * steps: [\n * \"Count total impressions (articles shown) per content piece\",\n * \"Count click-throughs (articles opened)\",\n * \"Count scroll depth > 50% (meaningful engagement)\",\n * \"Count shares, comments, or saves (viral actions)\",\n * \"Calculate conversion rate at each funnel stage\",\n * \"Identify top-performing content by final conversion rate\"\n * ],\n * notes: \"Requires multiple event types. Join events table multiple times or use conditional aggregation.\"\n * })\n *\n * @example\n * // Sports Analytics dataset\n * workflow({\n * task: \"Player Performance Rating Calculation\",\n * triggers: [\"player rating\", \"performance score\", \"player analytics\"],\n * steps: [\n * \"Aggregate per-game stats: points, assists, rebounds, turnovers\",\n * \"Calculate efficiency metrics: shooting percentage, plus/minus\",\n * \"Normalize each metric using z-scores vs league average\",\n * \"Apply position-specific weights to each metric\",\n * \"Combine weighted scores into overall performance rating (0-100)\",\n * \"Rank players within position group and overall\"\n * ],\n * notes: \"Requires league-wide statistics for normalization. Update weights each season based on game trends.\"\n * })\n */\nexport function workflow(input: {\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n}): Teachables {\n const { task, steps, triggers, notes } = input;\n return {\n type: 'workflow',\n encode: () => ({ type: 'workflow', task, steps, triggers, notes }),\n decode: () =>\n wrapBlock('workflow', [\n leaf('task', task),\n triggers?.length ? list('triggers', triggers, 'trigger') : '',\n list('steps', steps, 'step'),\n notes ? leaf('notes', notes) : '',\n ]),\n };\n}\n\n/**\n * Teach the system about data quirks, edge cases, or database-specific issues and their workarounds.\n *\n * Use this to document weird data patterns, database limitations, or special handling\n * required for specific scenarios. Helps the system navigate real-world messiness.\n *\n * @param input.issue - Description of the quirk, edge case, or problem\n * @param input.workaround - How to handle or work around this issue\n *\n * @example\n * // Government/Public Services dataset\n * quirk({\n * issue: \"Citizen IDs contain leading zeros but are stored as integers, losing the zeros\",\n * workaround: \"Always cast to VARCHAR and use LPAD(citizen_id::VARCHAR, 10, '0') to restore leading zeros\"\n * })\n *\n * @example\n * // Aviation dataset\n * quirk({\n * issue: \"Flight times crossing midnight show as negative duration (landing before takeoff)\",\n * workaround: \"Add 24 hours when calculated duration < 0: CASE WHEN duration < 0 THEN duration + INTERVAL '24 hours' ELSE duration END\"\n * })\n *\n * @example\n * // Automotive/Dealership dataset\n * quirk({\n * issue: \"VIN numbers with letter 'O' were incorrectly entered as zero '0' in legacy data\",\n * workaround: \"When searching by VIN, use REPLACE(vin, '0', 'O') or fuzzy matching to handle both cases\"\n * })\n */\nexport function quirk(input: {\n issue: string;\n workaround: string;\n}): Teachables {\n const { issue, workaround } = input;\n return {\n type: 'quirk',\n encode: () => ({ type: 'quirk', issue, workaround }),\n decode: () =>\n wrapBlock('quirk', [\n leaf('issue', issue),\n leaf('workaround', workaround),\n ]),\n };\n}\n\n/**\n * Teach the system SQL style preferences and coding standards for generated queries.\n *\n * Use this to enforce consistent SQL formatting, naming conventions, and best practices\n * specific to your team or organization. Improves readability and maintainability.\n *\n * @param input.prefer - Preferred SQL style or pattern\n * @param input.never - Optional anti-pattern to avoid\n * @param input.always - Optional rule that must always be followed\n *\n * @example\n * // Non-profit/Charity dataset\n * styleGuide({\n * prefer: \"Use donor-centric language in column aliases: 'donor_name' not 'customer_name'\",\n * never: \"Never expose internal donor IDs in external reports - use public gift IDs\",\n * always: \"Always include fiscal year in date-based aggregations (FY starts July 1)\"\n * })\n *\n * @example\n * // Legal/Law Firm dataset\n * styleGuide({\n * prefer: \"Use billable_hours with 2 decimal precision for accurate client billing\",\n * never: \"Never include attorney_rate in queries visible to paralegals - confidential data\",\n * always: \"Always filter by matter_status = 'open' unless specifically analyzing closed cases\"\n * })\n *\n * @example\n * // Inventory/Warehouse dataset\n * styleGuide({\n * prefer: \"Use location_id in joins rather than location_name (duplicates exist across warehouses)\",\n * never: \"Never aggregate inventory without grouping by warehouse_id first\",\n * always: \"Always use inventory_on_hand - inventory_reserved for available stock calculations\"\n * })\n */\nexport function styleGuide(input: {\n prefer: string;\n never?: string;\n always?: string;\n}): Teachables {\n const { prefer, never, always } = input;\n return {\n type: 'styleGuide',\n encode: () => ({ type: 'styleGuide', prefer, never, always }),\n decode: () =>\n wrapBlock('style_guide', [\n leaf('prefer', prefer),\n always ? leaf('always', always) : '',\n never ? leaf('never', never) : '',\n ]),\n };\n}\n\n/**\n * Teach the system by comparing related concepts through real-world analogies.\n *\n * Use this to teach relational understanding between two concepts by drawing comparisons\n * to familiar real-world scenarios. Helps the system understand WHY concepts differ and\n * when to use each one appropriately.\n *\n * @param input.concept - Array of two related concepts to compare\n * @param input.relationship - The comparison/analogy using real-world examples\n * @param input.insight - Optional key insight the analogy reveals\n * @param input.therefore - Optional actionable instruction based on this understanding\n * @param input.pitfall - Optional common mistake to avoid\n *\n * @example\n * // E-commerce dataset\n * analogy({\n * concept: [\"cart abandonment\", \"browse abandonment\"],\n * relationship: \"Cart abandonment is like leaving items at a checkout counter, browse abandonment is like window shopping without picking anything up\",\n * insight: \"Cart abandonment shows purchase intent (added to cart), browse abandonment shows only interest\",\n * therefore: \"Prioritize cart abandonment recovery campaigns - higher conversion potential than browse\",\n * pitfall: \"Don't combine both into generic 'abandonment rate' - they need different marketing strategies\"\n * })\n *\n * @example\n * // SaaS dataset\n * analogy({\n * concept: [\"logo churn\", \"revenue churn\"],\n * relationship: \"Logo churn is like counting how many customers left the store, revenue churn is how much money walked out\",\n * insight: \"Losing 10 small customers (high logo churn) might hurt less than losing 1 enterprise customer (high revenue churn)\",\n * therefore: \"Always report both metrics - logo churn for customer satisfaction, revenue churn for financial health\",\n * pitfall: \"Don't use logo churn to predict revenue impact - customer size distribution matters\"\n * })\n *\n * @example\n * // Healthcare dataset\n * analogy({\n * concept: [\"incident\", \"prevalence\"],\n * relationship: \"Incidence is like new house sales this month, prevalence is total houses currently occupied\",\n * insight: \"Incidence measures new cases over time, prevalence measures all existing cases at a point in time\",\n * therefore: \"For tracking disease outbreaks use incidence rate, for resource planning use prevalence\",\n * pitfall: \"Don't sum incidence rates across time periods - it's a rate not a count\"\n * })\n */\nexport function analogy(input: {\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n}): Teachables {\n const { concept, relationship, insight, therefore, pitfall } = input;\n return {\n type: 'analogy',\n encode: () => ({\n type: 'analogy',\n concept,\n relationship,\n insight,\n therefore,\n pitfall,\n }),\n decode: () =>\n wrapBlock('analogy', [\n list('concepts', concept, 'concept'),\n leaf('relationship', relationship),\n insight ? leaf('insight', insight) : '',\n therefore ? leaf('therefore', therefore) : '',\n pitfall ? leaf('pitfall', pitfall) : '',\n ]),\n };\n}\n\n/**\n * Map business terms directly to SQL expressions or fragments.\n *\n * Use this to teach the system how to CALCULATE or QUERY specific business concepts.\n * The system will substitute these SQL patterns when users mention the term.\n *\n * **Glossary vs Alias:**\n * - `alias` = user vocabulary \u2192 table/column name (\"the big table\" \u2192 \"orders table\")\n * - `glossary` = business term \u2192 SQL expression (\"revenue\" \u2192 \"SUM(orders.total_amount)\")\n *\n * In short: alias renames, glossary computes.\n *\n * @param entries - Record mapping business terms to their SQL expressions\n *\n * @example\n * glossary({\n * \"revenue\": \"SUM(orders.total_amount)\",\n * \"average order value\": \"AVG(orders.total_amount)\",\n * \"active user\": \"last_login > NOW() - INTERVAL '30 days'\",\n * \"churned\": \"status = 'churned'\",\n * \"power user\": \"order_count > 10\",\n * \"net revenue\": \"SUM(orders.total_amount) - SUM(refunds.amount)\",\n * })\n */\nexport function glossary(entries: Record<string, string>): Teachables {\n return {\n type: 'glossary',\n encode: () => ({ type: 'glossary', entries }),\n decode: () =>\n wrapBlock(\n 'glossary',\n Object.entries(entries).map(([term, sql]) =>\n wrapBlock('entry', [leaf('term', term), leaf('sql', sql)]),\n ),\n ),\n };\n}\n\n// =============================================================================\n// User-Specific Teachable Types\n// =============================================================================\n\n/**\n * Define the user's identity including name and/or role.\n *\n * Use this to capture who the user is and what lens they view data through.\n * Helps tailor explanations, terminology, and focus areas.\n *\n * @param input.name - The user's name (optional)\n * @param input.role - The user's role or position (optional)\n *\n * @example\n * identity({ name: \"John\", role: \"VP of Sales\" })\n * identity({ role: \"Data analyst in the marketing team\" })\n * identity({ name: \"Sarah\" })\n * identity({ role: \"Finance manager focused on cost optimization\" })\n */\nexport function identity(input: { name?: string; role?: string }): Teachables {\n const { name, role } = input;\n return {\n type: 'identity',\n encode: () => ({ type: 'identity', name, role }),\n decode: () =>\n wrapBlock('identity', [\n name ? leaf('name', name) : '',\n role ? leaf('role', role) : '',\n ]),\n };\n}\n\n/**\n * Define an AI persona with a name, role, and communication tone.\n *\n * Use this to customize the assistant's personality and how it communicates.\n * The persona influences the style and approach of responses.\n *\n * @param input.name - The persona's name\n * @param input.role - The persona's role or expertise\n * @param input.tone - The communication style (e.g., friendly, professional, concise)\n *\n * @example\n * persona({ name: \"DataBot\", role: \"SQL Expert\", tone: \"friendly and encouraging\" })\n * persona({ name: \"QueryMaster\", role: \"Database Analyst\", tone: \"professional and concise\" })\n * persona({ name: \"SQLHelper\", role: \"Data Assistant\", tone: \"casual and approachable\" })\n */\nexport function persona(input: {\n name: string;\n role: string;\n tone?: string;\n}): Teachables {\n const { name, role, tone } = input;\n return {\n type: 'persona',\n encode: () => ({ type: 'persona', name, role, tone: tone ?? '' }),\n decode: () =>\n wrapBlock('persona', [\n leaf('name', name),\n leaf('role', role),\n tone ? leaf('tone', tone) : '',\n ]),\n };\n}\n\n/**\n * Define user-specific term meanings and vocabulary.\n *\n * Use this when the user has their own definitions for terms that might\n * differ from standard or domain definitions. Like `term()` but personal.\n *\n * @param termName - The term the user uses\n * @param meaning - What the user means by this term\n *\n * @example\n * alias(\"revenue\", \"gross revenue before deductions, not net\")\n * alias(\"active users\", \"users who logged in within the last 30 days\")\n * alias(\"the big table\", \"the orders table\")\n * alias(\"Q4\", \"October through December, not fiscal Q4\")\n */\nexport function alias(termName: string, meaning: string): Teachables {\n return {\n type: 'alias',\n encode: () => ({ type: 'alias', term: termName, meaning }),\n decode: () =>\n wrapBlock('alias', [leaf('term', termName), leaf('meaning', meaning)]),\n };\n}\n\n/**\n * Define how the user prefers results presented.\n *\n * Use this to capture output formatting, style, and behavioral preferences\n * that should apply to all interactions with this user.\n *\n * @param aspect - What aspect of output this preference applies to\n * @param value - The user's preference\n *\n * @example\n * preference(\"date format\", \"YYYY-MM-DD\")\n * preference(\"output style\", \"tables over charts unless trend data\")\n * preference(\"detail level\", \"always show the SQL query in responses\")\n * preference(\"row limit\", \"default to 50 rows unless I ask for more\")\n * preference(\"explanation style\", \"brief and to the point\")\n */\nexport function preference(aspect: string, value: string): Teachables {\n return {\n type: 'preference',\n encode: () => ({ type: 'preference', aspect, value }),\n decode: () =>\n wrapBlock('preference', [leaf('aspect', aspect), leaf('value', value)]),\n };\n}\n\n/**\n * Define the user's current working focus or project.\n *\n * Use this to capture temporary context that helps inform defaults,\n * assumptions, and suggestions. Should be updated as focus changes.\n *\n * @param description - What the user is currently working on\n *\n * @example\n * context(\"Preparing Q4 board presentation\")\n * context(\"Investigating drop in signups last week\")\n * context(\"Working on EMEA regional analysis for strategy meeting\")\n * context(\"Debugging discrepancy in revenue numbers\")\n */\nexport function context(description: string): Teachables {\n return {\n type: 'context',\n encode: () => ({ type: 'context', description }),\n decode: () => leaf('context', description),\n };\n}\n\n/**\n * Record a correction the user made to previous understanding.\n *\n * Use this when the user corrects a misunderstanding about data, columns,\n * or business logic. Prevents repeating the same mistake.\n *\n * @param subject - What was misunderstood\n * @param clarification - The correct understanding\n *\n * @example\n * correction(\"status column\", \"1 = active, 0 = inactive, not boolean true/false\")\n * correction(\"orders table\", \"Use orders_v2, not the deprecated legacy_orders table\")\n * correction(\"date field\", \"order_date is when order was placed, ship_date is when shipped\")\n * correction(\"revenue calculation\", \"Must exclude refunds and chargebacks\")\n */\nexport function correction(subject: string, clarification: string): Teachables {\n return {\n type: 'correction',\n encode: () => ({ type: 'correction', subject, clarification }),\n decode: () =>\n wrapBlock('correction', [\n leaf('subject', subject),\n leaf('clarification', clarification),\n ]),\n };\n}\n\nexport function teachable(\n tag: string,\n ...teachables: Teachables[]\n): Teachables {\n return {\n type: 'user_profile',\n encode: () => teachables[0]?.encode() ?? ({ type: 'context', description: '' }),\n decode: () => toInstructions(tag, ...teachables),\n };\n}\n\nexport function toInstructions(\n tag: string,\n ...teachables: Teachables[]\n): string {\n if (!teachables.length) {\n return '';\n }\n\n const grouped = new Map<Teachables['type'], Teachables[]>();\n for (const teachable of teachables) {\n const existing = grouped.get(teachable.type) ?? [];\n existing.push(teachable);\n grouped.set(teachable.type, existing);\n }\n\n const definedTypes = new Set(SECTION_ORDER.map((s) => s.type));\n\n const sections = SECTION_ORDER.map(({ type, tag }) => {\n const items = grouped.get(type);\n if (!items?.length) {\n return '';\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (!renderedItems.length) {\n return '';\n }\n return `<${tag}>\\n${renderedItems}\\n</${tag}>`;\n }).filter((section): section is string => Boolean(section));\n\n // Render types not defined in SECTION_ORDER at the end\n for (const [type, items] of grouped) {\n if (definedTypes.has(type)) {\n continue;\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (renderedItems.length) {\n sections.push(renderedItems);\n }\n }\n\n if (!sections.length) {\n return '';\n }\n\n const content = indentBlock(sections.join('\\n'), 2);\n return `<${tag}>\\n${content}\\n</${tag}>`;\n}\n\nconst SECTION_ORDER: Array<{ type: Teachables['type']; tag: string }> = [\n // User context (render first - most important for personalization)\n { type: 'identity', tag: 'identity' },\n { type: 'persona', tag: 'persona' },\n { type: 'context', tag: 'user_context' },\n { type: 'preference', tag: 'user_preferences' },\n { type: 'alias', tag: 'user_vocabulary' },\n { type: 'correction', tag: 'user_corrections' },\n // Domain knowledge\n { type: 'guardrail', tag: 'guardrails' },\n { type: 'styleGuide', tag: 'style_guides' },\n { type: 'hint', tag: 'hints' },\n { type: 'clarification', tag: 'clarifications' },\n { type: 'workflow', tag: 'workflows' },\n { type: 'quirk', tag: 'quirks' },\n { type: 'term', tag: 'terminology' },\n { type: 'explain', tag: 'explanations' },\n { type: 'analogy', tag: 'analogies' },\n { type: 'glossary', tag: 'glossary' },\n { type: 'example', tag: 'examples' },\n];\n\nexport function toTeachables(generated: GeneratedTeachable[]): Teachables[] {\n return generated.map((item) => {\n switch (item.type) {\n case 'persona':\n return persona({ name: item.name, role: item.role, tone: item.tone });\n case 'term':\n return term(item.name, item.definition);\n case 'hint':\n return hint(item.text);\n case 'guardrail':\n return guardrail({\n rule: item.rule,\n reason: item.reason,\n action: item.action,\n });\n case 'explain':\n return explain({\n concept: item.concept,\n explanation: item.explanation,\n therefore: item.therefore,\n });\n case 'example':\n return example({\n question: item.question,\n answer: item.answer,\n note: item.note,\n });\n case 'clarification':\n return clarification({\n when: item.when,\n ask: item.ask,\n reason: item.reason,\n });\n case 'workflow':\n return workflow({\n task: item.task,\n steps: item.steps,\n triggers: item.triggers,\n notes: item.notes,\n });\n case 'quirk':\n return quirk({\n issue: item.issue,\n workaround: item.workaround,\n });\n case 'styleGuide':\n return styleGuide({\n prefer: item.prefer,\n never: item.never,\n always: item.always,\n });\n case 'analogy':\n return analogy({\n concept: item.concept,\n relationship: item.relationship,\n insight: item.insight,\n therefore: item.therefore,\n pitfall: item.pitfall,\n });\n case 'glossary':\n return glossary(item.entries);\n // User-specific teachable types\n case 'identity':\n return identity({ name: item.name, role: item.role });\n case 'alias':\n return alias(item.term, item.meaning);\n case 'preference':\n return preference(item.aspect, item.value);\n case 'context':\n return context(item.description);\n case 'correction':\n return correction(item.subject, item.clarification);\n }\n });\n}\n\n/**\n * Convert Teachables back to GeneratedTeachable format for storage.\n *\n * @param teachables - Array of Teachables to convert\n * @returns Array of GeneratedTeachable objects suitable for storage\n *\n * @example\n * const teachings = [term('NPL', 'non-performing loan'), hint('Always filter by status')];\n * const forStorage = fromTeachables(teachings);\n * // [{ type: 'term', name: 'NPL', definition: 'non-performing loan' }, { type: 'hint', text: 'Always filter by status' }]\n */\nexport function fromTeachables(teachables: Teachables[]): GeneratedTeachable[] {\n return teachables.map((t) => t.encode());\n}\n\n/**\n * Default export containing all system teachable factory functions.\n * Excludes user-specific teachables (identity, alias, preference, context, correction).\n */\nexport default {\n persona,\n term,\n hint,\n guardrail,\n explain,\n example,\n clarification,\n workflow,\n quirk,\n styleGuide,\n analogy,\n glossary,\n teachable,\n};\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport { type ExtractedPair, PairProducer } from '../types.ts';\nimport type { Persona } from './persona-generator.ts';\nimport { styleInstructions } from './styles.ts';\n\nexport interface BreadthEvolverOptions {\n count: number;\n persona?: Persona;\n model?: AgentModel;\n concurrency?: number;\n}\n\ntype ParaphraserState = {\n question: string;\n sql: string;\n count: number;\n persona?: Persona;\n};\n\ntype ParaphraserOutput = {\n paraphrases: string[];\n};\n\nconst paraphraserAgent = agent<ParaphraserOutput, ParaphraserState>({\n name: 'question_paraphraser',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.9, topP: 0.95, frequencyPenalty: 0.2 },\n }),\n }),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.object({\n paraphrases: z\n .array(\n z.string().describe('A paraphrased version of the original question'),\n )\n .min(1)\n .describe(\n 'List of paraphrased questions that would produce the same SQL',\n ),\n }),\n prompt: (state) => {\n const personaInstruction = state?.persona\n ? dedent`\n <persona role=\"${state.persona.role}\">\n ${state.persona.perspective}\n\n Paraphrase the question as this persona would naturally ask it.\n Use their vocabulary, priorities, and framing style.\n </persona>\n `\n : '';\n\n const styleInstruction =\n state?.persona?.styles && state.persona.styles.length > 0\n ? dedent`\n <communication_styles>\n Generate paraphrases using these communication styles: ${state.persona.styles.join(', ')}\n\n Style definitions:\n ${state.persona.styles.map((s) => `- ${s}: ${styleInstructions[s]}`).join('\\n')}\n\n Distribute paraphrases across these styles for variety.\n </communication_styles>\n `\n : '';\n\n return dedent`\n <identity>\n You are a linguistic expert specializing in paraphrasing database questions.\n Your task is to generate alternative phrasings of questions that preserve\n the exact same semantic meaning - they must all produce the identical SQL query.\n </identity>\n\n <original_question>\n ${state?.question}\n </original_question>\n\n <reference_sql>\n ${state?.sql}\n (This SQL shows what the question is really asking - all paraphrases must ask for exactly this)\n </reference_sql>\n\n ${personaInstruction}\n\n ${styleInstruction}\n\n <task>\n Generate exactly ${state?.count} paraphrased versions of the original question.\n\n Requirements:\n 1. Each paraphrase must be semantically equivalent - it should produce the EXACT same SQL\n 2. Vary the sentence structure, word choice, and phrasing style\n 3. Use natural language without SQL keywords (SELECT, WHERE, JOIN, etc.)\n 4. Keep paraphrases realistic - how actual users would ask\n 5. Do not add or remove any conditions, filters, or requirements from the original\n ${state?.persona?.styles?.length ? '6. Apply the specified communication styles to create diverse phrasings' : ''}\n </task>\n\n <guardrails>\n - NEVER change what data is being requested\n - NEVER add filters, aggregations, or conditions not in the original\n - NEVER remove any specificity from the original question\n - All paraphrases must be answerable by the exact same SQL query\n </guardrails>\n `;\n },\n});\n/**\n * BreadthEvolver - Generate paraphrased variations of questions (in-breadth evolution).\n *\n * Takes existing question/SQL pairs and generates variations of the questions\n * while keeping the SQL identical. This creates training data diversity where\n * many different phrasings map to the same SQL query.\n *\n * Based on Microsoft's Evol-Instruct methodology for in-breadth evolution.\n */\nexport class BreadthEvolver extends PairProducer {\n #limit: ReturnType<typeof pLimit>;\n\n /**\n * @param source - Source pairs or producer to evolve\n * @param options - Evolution options including count, persona, and concurrency\n */\n constructor(\n private source: PairProducer | ExtractedPair[],\n private options: BreadthEvolverOptions,\n ) {\n super();\n this.#limit = pLimit(this.options.concurrency ?? 4);\n }\n\n /**\n * Batch pairs within each chunk for concurrent processing.\n * Uses pLimit for concurrency control, yields results per pair after chunk completes.\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n for await (const chunk of this.from(this.source)) {\n const tasks = chunk.map((pair) =>\n this.#limit(async () => {\n const { experimental_output } = await generate(\n paraphraserAgent.clone({ model: this.options.model }),\n [\n user(\n `Paraphrase this question ${this.options.count} times: \"${pair.question}\"`,\n ),\n ],\n {\n question: pair.question,\n sql: pair.sql,\n count: this.options.count,\n persona: this.options.persona,\n },\n );\n\n return experimental_output.paraphrases.map((paraphrase) => ({\n question: paraphrase,\n sql: pair.sql,\n context: pair.context,\n success: pair.success,\n }));\n }),\n );\n\n const results = await Promise.all(tasks);\n yield results.flat();\n }\n }\n}\n", "/**\n * Natural language styles for text-to-SQL question generation.\n * Based on OmniSQL paper (March 2025): https://arxiv.org/html/2503.02240\n */\n\nexport type NLStyle =\n | 'formal' // Professional business language\n | 'colloquial' // Casual everyday speech\n | 'imperative' // Commands: \"Show me...\", \"Get...\"\n | 'interrogative' // Questions: \"What is...\", \"How many...\"\n | 'descriptive' // Verbose, detailed\n | 'concise' // Brief, minimal\n | 'vague' // Ambiguous, hedging\n | 'metaphorical' // Figurative language\n | 'conversational'; // Chat-like\n\nexport const styleInstructions: Record<NLStyle, string> = {\n formal: 'Use professional business language, complete sentences, no slang',\n colloquial: 'Use casual everyday speech, contractions, informal tone',\n imperative: 'Phrase as commands: \"Show me...\", \"Get...\", \"List...\"',\n interrogative: 'Phrase as questions: \"What is...\", \"How many...\", \"Which...\"',\n descriptive: 'Use detailed, verbose phrasing with extra context',\n concise: 'Use minimal words, telegram-style brevity',\n vague: 'Be intentionally ambiguous, use hedging language',\n metaphorical: 'Use figurative language, analogies, creative phrasing',\n conversational: 'Chat-like tone, as if talking to a colleague',\n};\n\nexport const ALL_STYLES: NLStyle[] = [\n 'formal',\n 'colloquial',\n 'imperative',\n 'interrogative',\n 'descriptive',\n 'concise',\n 'vague',\n 'metaphorical',\n 'conversational',\n];\n", "import { groq } from '@ai-sdk/groq';\nimport {\n NoObjectGeneratedError,\n NoOutputGeneratedError,\n defaultSettingsMiddleware,\n wrapLanguageModel,\n} from 'ai';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { toSql } from '../../agents/sql.agent.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\n/**\n * Techniques for evolving questions into more complex versions.\n * Each technique transforms the question in a specific way.\n */\nexport type DepthTechnique =\n | 'add-aggregation'\n | 'add-filter'\n | 'add-join'\n | 'add-reasoning'\n | 'hypothetical';\n\nconst techniqueInstructions: Record<DepthTechnique, string> = {\n 'add-aggregation': dedent`\n Add aggregation requirements to the question.\n Transform it to require GROUP BY, COUNT, SUM, AVG, MIN, MAX, or similar operations.\n Examples:\n - \"Show orders\" \u2192 \"Show total order count by customer\"\n - \"List products\" \u2192 \"What is the average price per category?\"\n - \"Get employees\" \u2192 \"How many employees are in each department?\"\n `,\n 'add-filter': dedent`\n Add filtering conditions to the question.\n Transform it to require WHERE clauses with specific conditions.\n Examples:\n - \"Show orders\" \u2192 \"Show orders from the last 30 days\"\n - \"List customers\" \u2192 \"List customers who have made more than 5 purchases\"\n - \"Get products\" \u2192 \"Get products with price above $100\"\n `,\n 'add-join': dedent`\n Add requirements that need data from related tables.\n Transform it to require JOIN operations between multiple tables.\n Examples:\n - \"Show orders\" \u2192 \"Show orders with customer names and addresses\"\n - \"List products\" \u2192 \"List products with their supplier information\"\n - \"Get employees\" \u2192 \"Get employees with their department and manager names\"\n `,\n 'add-reasoning': dedent`\n Add multi-step reasoning requirements.\n Transform it to require logical deduction, comparisons, or derived calculations.\n Examples:\n - \"Show orders\" \u2192 \"Which customers have orders above the average order value?\"\n - \"List products\" \u2192 \"Which products are underperforming compared to their category average?\"\n - \"Get revenue\" \u2192 \"Which month had the highest growth compared to the previous month?\"\n `,\n hypothetical: dedent`\n Add a hypothetical or speculative scenario.\n Transform it to require applying calculations or projections.\n Examples:\n - \"Show revenue\" \u2192 \"What would revenue be if we increased all prices by 15%?\"\n - \"List inventory\" \u2192 \"How many days of stock remain at current sales rate?\"\n - \"Get costs\" \u2192 \"What would be the impact of a 10% discount on profit margins?\"\n `,\n};\n\nexport interface DepthEvolverOptions {\n techniques?: DepthTechnique[];\n count?: number;\n model?: AgentModel;\n concurrency?: number;\n}\n\ntype EvolverState = {\n question: string;\n sql: string;\n schema: string;\n technique: DepthTechnique;\n techniqueInstruction: string;\n};\n\ntype EvolverOutput = {\n evolvedQuestion: string;\n};\n\nconst questionEvolverAgent = agent<EvolverOutput, EvolverState>({\n name: 'question_evolver',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.7, topP: 0.95 },\n }),\n }),\n output: z.object({\n evolvedQuestion: z\n .string()\n .describe('The evolved, more complex version of the original question'),\n }),\n prompt: (state) => {\n return dedent`\n <identity>\n You are an expert at evolving simple database questions into more complex ones.\n Your task is to take a basic question and transform it into a more sophisticated\n version that requires advanced SQL techniques to answer.\n </identity>\n\n <original_question>\n ${state?.question}\n </original_question>\n\n <original_sql>\n ${state?.sql}\n (This shows what the original question required)\n </original_sql>\n\n <database_schema>\n ${state?.schema}\n </database_schema>\n\n <technique name=\"${state?.technique}\">\n ${state?.techniqueInstruction}\n </technique>\n\n <task>\n Evolve the original question using the \"${state?.technique}\" technique.\n\n Requirements:\n 1. The evolved question must be MORE COMPLEX than the original\n 2. Apply the specific technique described above\n 3. The evolved question must be answerable using the provided schema\n 4. Use natural language - no SQL keywords\n 5. Keep the question realistic and practical\n 6. The evolved question should build upon the original topic/domain\n </task>\n\n <guardrails>\n - The evolved question MUST require more complex SQL than the original\n - Do not ask for data that doesn't exist in the schema\n - Keep the question grounded in the same domain as the original\n - Make sure the question is clear and unambiguous\n </guardrails>\n `;\n },\n});\n\nconst ALL_TECHNIQUES: DepthTechnique[] = [\n 'add-aggregation',\n 'add-filter',\n 'add-join',\n 'add-reasoning',\n 'hypothetical',\n];\n/**\n * DepthEvolver - Evolve questions into more complex versions (in-depth evolution).\n *\n * Takes existing question/SQL pairs and evolves them into more complex versions\n * using specific techniques. Both the question AND SQL change - the evolved\n * question requires a more sophisticated query to answer.\n *\n * Based on Microsoft's Evol-Instruct methodology for in-depth evolution.\n */\nexport class DepthEvolver extends PairProducer {\n #limit: ReturnType<typeof pLimit>;\n\n /**\n * @param source - Source pairs or producer to evolve\n * @param adapter - Database adapter for SQL generation\n * @param options - Evolution options including techniques, count, and concurrency\n */\n constructor(\n private source: PairProducer | ExtractedPair[],\n private adapter: Adapter,\n private options?: DepthEvolverOptions,\n ) {\n super();\n this.#limit = pLimit(this.options?.concurrency ?? 4);\n }\n\n /**\n * Yields evolved pairs as each completes (streaming pattern).\n * Removes batch barrier - no longer waits for all evolutions before yielding.\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const introspection = await this.adapter.introspect();\n const count = this.options?.count ?? 1;\n const techniques = this.options?.techniques ?? ALL_TECHNIQUES;\n\n let pairIndex = 0;\n for await (const chunk of this.from(this.source)) {\n for (const pair of chunk) {\n const tasks = Array.from({ length: count }, (_, i) => {\n const technique = this.options?.techniques\n ? techniques[i % techniques.length]\n : techniques[(pairIndex * count + i) % techniques.length];\n return this.#limit(() =>\n this.#processTask(pair, technique, introspection),\n );\n });\n\n const results = await Promise.all(tasks);\n yield results;\n pairIndex++;\n }\n }\n }\n\n async #processTask(\n pair: ExtractedPair,\n technique: DepthTechnique,\n introspection: string,\n ) {\n const { experimental_output } = await withRetry(() =>\n generate(\n questionEvolverAgent.clone({\n model: this.options?.model,\n }),\n [user(`Evolve this question using \"${technique}\": \"${pair.question}\"`)],\n {\n question: pair.question,\n sql: pair.sql,\n schema: introspection,\n technique,\n techniqueInstruction: techniqueInstructions[technique],\n },\n ),\n );\n\n const evolvedQuestion = experimental_output.evolvedQuestion;\n\n const sqlResult = await toSql({\n input: evolvedQuestion,\n adapter: this.adapter,\n introspection,\n instructions: [],\n model: this.options?.model,\n });\n\n return {\n question: evolvedQuestion,\n sql: sqlResult.sql,\n context: pair.context,\n success: !sqlResult.errors || sqlResult.errors.length === 0,\n };\n }\n}\n\nasync function withRetry<T>(computation: () => Promise<T>): Promise<T> {\n return pRetry(computation, {\n retries: 3,\n shouldRetry: (context) => {\n return (\n NoObjectGeneratedError.isInstance(context.error) ||\n NoOutputGeneratedError.isInstance(context.error)\n );\n },\n onFailedAttempt(context) {\n console.log(\n `Attempt ${context.attemptNumber} failed. There are ${context.retriesLeft} retries left.`,\n );\n console.error(context.error);\n },\n });\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { ALL_STYLES, type NLStyle } from './styles.ts';\n\nexport interface Persona {\n role: string;\n perspective: string;\n styles: NLStyle[];\n}\n\nexport interface PersonaGeneratorOptions {\n count?: number;\n model?: AgentModel;\n}\n\ntype PersonaGeneratorState = {\n schema: string;\n count: number;\n};\n\ntype PersonaGeneratorOutput = {\n personas: Persona[];\n};\n\nconst personaGeneratorAgent = agent<\n PersonaGeneratorOutput,\n PersonaGeneratorState\n>({\n name: 'persona_generator',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.8, topP: 0.95, presencePenalty: 0.2 },\n }),\n }),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.object({\n personas: z\n .array(\n z.object({\n role: z.string().describe('The job title or role of this persona'),\n perspective: z\n .string()\n .describe(\n 'Rich description of what this persona cares about when querying the database',\n ),\n styles: z\n .array(z.enum(ALL_STYLES as [NLStyle, ...NLStyle[]]))\n .min(1)\n .max(3)\n .describe(\n 'Typical communication styles for this persona (1-3 styles)',\n ),\n }),\n )\n .min(1)\n .describe('List of personas who would query this database'),\n }),\n prompt: (state) => {\n return dedent`\n <identity>\n You are an expert at understanding database schemas and inferring who would use them.\n Your task is to analyze a database schema and generate realistic personas representing\n the different types of users who would query this database.\n </identity>\n\n <database_schema>\n ${state?.schema}\n </database_schema>\n\n <task>\n Generate exactly ${state?.count} distinct personas who would query this database.\n\n For each persona, provide:\n 1. **role**: Their job title or role (e.g., \"Financial Analyst\", \"Customer Support Rep\")\n 2. **perspective**: A rich description of what they care about, including:\n - What questions they typically ask\n - What metrics/data points matter to them\n - How they prefer data formatted or presented\n - Their priorities (speed vs accuracy, detail vs summary)\n - Domain-specific concerns relevant to their role\n 3. **styles**: 1-3 communication styles typical for this persona. Choose from:\n - formal: Professional business language, complete sentences\n - colloquial: Casual everyday speech, contractions\n - imperative: Commands like \"Show me...\", \"Get...\", \"List...\"\n - interrogative: Questions like \"What is...\", \"How many...\"\n - descriptive: Verbose, detailed phrasing\n - concise: Brief, minimal words\n - vague: Ambiguous, hedging language\n - metaphorical: Figurative language, analogies\n - conversational: Chat-like, casual tone\n\n Requirements:\n - Personas should be realistic for the given schema\n - Each persona should have distinct concerns and priorities\n - Perspectives should be detailed enough to guide question paraphrasing\n - Cover different levels of technical expertise (some technical, some business-focused)\n - Styles should match how this persona would naturally communicate\n </task>\n\n <example>\n For an e-commerce schema with orders, customers, products tables:\n\n {\n \"role\": \"Customer Support Rep\",\n \"perspective\": \"As customer support, I care about:\\\\n- Quick lookups by order ID or customer email\\\\n- Order status and shipping tracking\\\\n- Return and refund history\\\\n- Customer contact details and order history\\\\n- I need fast answers, not complex analysis\",\n \"styles\": [\"imperative\", \"concise\"]\n }\n\n {\n \"role\": \"Inventory Manager\",\n \"perspective\": \"As inventory manager, I care about:\\\\n- Current stock levels and reorder points\\\\n- Product availability across warehouses\\\\n- Slow-moving inventory identification\\\\n- Supplier lead times and pending orders\\\\n- I need accurate counts, often aggregated by location\",\n \"styles\": [\"formal\", \"interrogative\"]\n }\n </example>\n\n <guardrails>\n - Only generate personas relevant to the actual schema provided\n - Do not invent tables or data that don't exist in the schema\n - Ensure perspectives are specific to the domain, not generic\n </guardrails>\n `;\n },\n});\n/**\n * PersonaGenerator - Generate relevant personas from database schema.\n *\n * Analyzes the schema to infer who would query this database and what\n * they care about. Generated personas can be used with BreadthEvolver\n * to create diverse question paraphrases from different perspectives.\n */\nexport class PersonaGenerator {\n /**\n * @param adapter - Database adapter for schema introspection\n * @param options - Generation options including count and model\n */\n constructor(\n private adapter: Adapter,\n private options?: PersonaGeneratorOptions,\n ) {}\n\n /**\n * Generates personas by analyzing the database schema to infer user types.\n * @returns Array of personas with roles and perspectives\n */\n async generate(): Promise<Persona[]> {\n const schema = await this.adapter.introspect();\n const count = this.options?.count ?? 5;\n\n const { experimental_output } = await generate(\n personaGeneratorAgent.clone({\n model: this.options?.model,\n }),\n [user(`Generate ${count} personas for this database schema.`)],\n {\n schema,\n count,\n },\n );\n\n return experimental_output.personas;\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport {\n type GeneratedTeachable,\n type Teachables,\n toTeachables,\n} from '../teach/teachables.ts';\n\nconst outputSchema = z.object({\n terms: z\n .array(z.object({ name: z.string(), definition: z.string() }))\n .optional()\n .describe('Domain terminology definitions'),\n hints: z\n .array(z.object({ text: z.string() }))\n .optional()\n .describe('Helpful hints for SQL generation'),\n guardrails: z\n .array(\n z.object({\n rule: z.string(),\n reason: z.string().optional(),\n action: z.string().optional(),\n }),\n )\n .optional()\n .describe('Safety rules and constraints'),\n explains: z\n .array(\n z.object({\n concept: z.string(),\n explanation: z.string(),\n therefore: z.string().optional(),\n }),\n )\n .optional()\n .describe('Concept explanations'),\n examples: z\n .array(\n z.object({\n question: z.string(),\n answer: z.string(),\n note: z.string().optional(),\n }),\n )\n .optional()\n .describe('Example question-answer pairs'),\n clarifications: z\n .array(z.object({ when: z.string(), ask: z.string(), reason: z.string() }))\n .optional()\n .describe('When to ask for clarification'),\n workflows: z\n .array(\n z.object({\n task: z.string(),\n steps: z.array(z.string()).min(1),\n triggers: z.array(z.string()).optional(),\n notes: z.string().optional(),\n }),\n )\n .optional()\n .describe('Multi-step workflows'),\n quirks: z\n .array(z.object({ issue: z.string(), workaround: z.string() }))\n .optional()\n .describe('Known issues and workarounds'),\n styleGuides: z\n .array(\n z.object({\n prefer: z.string(),\n never: z.string().optional(),\n always: z.string().optional(),\n }),\n )\n .optional()\n .describe('SQL style preferences'),\n analogies: z\n .array(\n z.object({\n concept: z.array(z.string()).min(2),\n relationship: z.string(),\n insight: z.string().optional(),\n therefore: z.string().optional(),\n pitfall: z.string().optional(),\n }),\n )\n .optional()\n .describe('Concept analogies'),\n});\n\ntype TeachablesOutput = z.infer<typeof outputSchema>;\n\nconst teachablesAuthorAgent = agent<\n TeachablesOutput,\n { schema: string; context?: string }\n>({\n name: 'teachables-author',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.4, topP: 0.95 },\n }),\n }),\n output: outputSchema,\n prompt: (state) => dedent`\n <identity>\n You design \"teachables\" for a Text2SQL system. Teachables become structured XML instructions.\n Choose only high-impact items that improve accuracy, safety, or clarity for this database.\n </identity>\n\n <database_schema>\n ${state?.schema}\n </database_schema>\n\n ${state?.context ? `<additional_context>${state.context}</additional_context>` : ''}\n\n <output_structure>\n Output a JSON object with these optional arrays (include only relevant ones):\n - terms: [{ name: string, definition: string }] - Domain terminology\n - hints: [{ text: string }] - Helpful SQL generation hints\n - guardrails: [{ rule: string, reason?: string, action?: string }] - Safety constraints\n - explains: [{ concept: string, explanation: string, therefore?: string }] - Concept explanations\n - examples: [{ question: string, answer: string, note?: string }] - Q&A examples\n - clarifications: [{ when: string, ask: string, reason: string }] - Clarification triggers\n - workflows: [{ task: string, steps: string[], triggers?: string[], notes?: string }] - Multi-step tasks\n - quirks: [{ issue: string, workaround: string }] - Known issues\n - styleGuides: [{ prefer: string, never?: string, always?: string }] - SQL style rules\n - analogies: [{ concept: string[], relationship: string, insight?: string, therefore?: string, pitfall?: string }]\n </output_structure>\n\n <instructions>\n 1. Analyze the schema to infer domain, relationships, and sensitive columns.\n 2. Generate 3-10 teachables total across all categories, prioritizing:\n - guardrails for PII columns (email, ssn, phone, etc)\n - hints for status/enum columns\n - clarifications for ambiguous terms\n 3. Ground everything in the schema - do not invent tables/columns.\n 4. Only include categories that are relevant to this schema.\n </instructions>\n `,\n});\n\nexport interface GenerateToTeachingsOptions {\n model?: AgentModel;\n}\n\nexport async function toTeachings(\n input: { schema: string; context?: string },\n options?: GenerateToTeachingsOptions,\n): Promise<Teachables[]> {\n const { experimental_output: result } = await generate(\n teachablesAuthorAgent.clone({ model: options?.model }),\n [\n user(\n `Analyze this database schema and generate teachings that will help an AI generate accurate SQL queries.`,\n ),\n ],\n input,\n );\n\n const generated: GeneratedTeachable[] = [\n ...(result.terms?.map((t) => ({ type: 'term' as const, ...t })) ?? []),\n ...(result.hints?.map((h) => ({ type: 'hint' as const, ...h })) ?? []),\n ...(result.guardrails?.map((g) => ({ type: 'guardrail' as const, ...g })) ??\n []),\n ...(result.explains?.map((e) => ({ type: 'explain' as const, ...e })) ??\n []),\n ...(result.examples?.map((e) => ({ type: 'example' as const, ...e })) ??\n []),\n ...(result.clarifications?.map((c) => ({\n type: 'clarification' as const,\n ...c,\n })) ?? []),\n ...(result.workflows?.map((w) => ({ type: 'workflow' as const, ...w })) ??\n []),\n ...(result.quirks?.map((q) => ({ type: 'quirk' as const, ...q })) ?? []),\n ...(result.styleGuides?.map((s) => ({\n type: 'styleGuide' as const,\n ...s,\n })) ?? []),\n ...(result.analogies?.map((a) => ({ type: 'analogy' as const, ...a })) ??\n []),\n ];\n\n return toTeachables(generated);\n}\n", "import type { AgentModel } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { toTeachings } from '../../agents/teachables.agent.ts';\nimport type { Teachables } from '../../teach/teachables.ts';\n\nexport interface TeachingsGeneratorOptions {\n context?: string;\n model?: AgentModel;\n}\n/**\n * TeachingsGenerator - Generate domain-specific teachings from database schema.\n *\n * Analyzes the schema to generate teachings that improve SQL generation accuracy.\n * Teachings include domain vocabulary, SQL patterns, guardrails, and examples\n * that help the SQL generator understand the domain and produce semantically\n * correct queries.\n */\nexport class TeachingsGenerator {\n /**\n * @param adapter - Database adapter for schema introspection\n * @param options - Generation options including context and model\n */\n constructor(\n private adapter: Adapter,\n private options?: TeachingsGeneratorOptions,\n ) {}\n\n /**\n * Generates domain-specific teachings by analyzing the database schema.\n * Retries on transient generation errors up to maxRetries attempts.\n * @param maxRetries - Maximum retry attempts for transient failures\n * @returns Array of teachings including vocabulary, patterns, and guardrails\n */\n async generate(maxRetries = 3): Promise<Teachables[]> {\n const schema = await this.adapter.introspect();\n\n let lastError: Error | undefined;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await toTeachings(\n {\n schema,\n context: this.options?.context,\n },\n { model: this.options?.model },\n );\n } catch (error) {\n lastError = error as Error;\n const isRetryable =\n lastError.message.includes('parse') ||\n lastError.message.includes('schema') ||\n lastError.message.includes('No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,GAAG,EAAE,EAAE,KAAK,CAAC;AAAA,IACtE,GAAI,OAAO,aAAa,IAAI,CAAC,OAAO;AAAA,MAClC,MAAM;AAAA,MACN,GAAG;AAAA,IACL,EAAE,KAAK,CAAC;AAAA,IACR,GAAI,OAAO,WAAW,IAAI,CAAC,OAAO,EAAE,MAAM,WAAoB,GAAG,EAAE,EAAE,KACnE,CAAC;AAAA,EACL;AAEA,SAAO,aAAa,SAAS;AAC/B;;;AC5KO,IAAM,qBAAN,MAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9B,YACU,SACA,SACR;AAFQ;AACA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQH,MAAM,SAAS,aAAa,GAA0B;AACpD,UAAM,SAAS,MAAM,KAAK,QAAQ,WAAW;AAE7C,QAAI;AACJ,aAAS,UAAU,GAAG,UAAU,YAAY,WAAW;AACrD,UAAI;AACF,eAAO,MAAM;AAAA,UACX;AAAA,YACE;AAAA,YACA,SAAS,KAAK,SAAS;AAAA,UACzB;AAAA,UACA,EAAE,OAAO,KAAK,SAAS,MAAM;AAAA,QAC/B;AAAA,MACF,SAAS,OAAO;AACd,oBAAY;AACZ,cAAM,cACJ,UAAU,QAAQ,SAAS,OAAO,KAClC,UAAU,QAAQ,SAAS,QAAQ,KACnC,UAAU,QAAQ,SAAS,qBAAqB,KAChD,UAAU,KAAK,SAAS,KAAK;AAC/B,YAAI,CAAC,aAAa;AAChB,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM;AAAA,EACR;AACF;",
|
|
6
|
-
"names": ["getToolOrDynamicToolName", "isToolOrDynamicToolUIPart", "isToolOrDynamicToolUIPart", "getToolOrDynamicToolName", "groq", "dedent", "z", "agent", "generate", "user", "agent", "groq", "z", "dedent", "generate", "user", "groq", "dedent", "z", "agent", "generate", "user", "agent", "groq", "z", "dedent", "generate", "user", "generate", "user", "generate", "user", "groq", "dedent", "z", "agent", "generate", "user", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "z", "agent", "generate", "user", "term", "clarification", "tag", "agent", "groq", "z", "wrapLanguageModel", "defaultSettingsMiddleware", "user", "generate", "persona", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "pLimit", "z", "agent", "generate", "user", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "z", "dedent", "pLimit", "generate", "user", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "pLimit", "z", "agent", "generate", "user", "dedent", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "z", "pLimit", "generate", "user", "context", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "z", "agent", "generate", "user", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "z", "dedent", "generate", "user", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "z", "agent", "generate", "user", "z", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "dedent", "generate", "user"]
|
|
4
|
+
"sourcesContent": ["/**\n * A question/SQL pair extracted or synthesized for training data.\n */\nexport interface ExtractedPair {\n question: string;\n sql: string;\n context?: string[];\n success: boolean;\n}\n\n/**\n * Interface for all pair producers (extractors and synthesizers).\n * Implementations encapsulate their specific inputs and logic.\n */\nexport abstract class PairProducer<T extends ExtractedPair = ExtractedPair> {\n /**\n * Produce question/SQL pairs.\n */\n abstract produce(): AsyncGenerator<T[], void, unknown>;\n\n protected from(producer: PairProducer<ExtractedPair> | ExtractedPair[]) {\n return Array.isArray(producer)\n ? (async function* (pairs: ExtractedPair[]) {\n yield pairs;\n })(producer)\n : producer.produce();\n }\n\n public toPairs(): Promise<T[]> {\n return toPairs(this);\n }\n}\n\n/**\n * Entry point for producing pairs from any source.\n */\nexport async function toPairs<T extends ExtractedPair>(\n producer: PairProducer<T>,\n): Promise<T[]> {\n const pairs: T[] = [];\n for await (const chunk of producer.produce()) {\n pairs.push(...chunk);\n }\n return pairs;\n}\n", "import { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface FilteredProducerOptions {\n successOnly?: boolean;\n tables?: string[];\n filter?: (pair: ExtractedPair) => boolean;\n}\n\n/**\n * FilteredProducer - Filter pairs from another producer.\n *\n * Wraps another PairProducer and filters the output based on criteria.\n */\nexport class FilteredProducer extends PairProducer {\n /**\n * @param producer - Source producer to filter\n * @param options - Filter configuration\n */\n constructor(\n private producer: PairProducer,\n private options: FilteredProducerOptions = {},\n ) {\n super();\n }\n\n /**\n * Produces pairs filtered by success status, table usage, and custom predicates.\n * @returns Pairs matching all configured filter criteria\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n for await (const chunk of this.producer.produce()) {\n const filtered = chunk.filter((pair) => {\n if (this.options.successOnly !== false && !pair.success) {\n return false;\n }\n\n if (this.options.tables?.length) {\n const sqlLower = pair.sql.toLowerCase();\n const hasTable = this.options.tables.some((t) =>\n sqlLower.includes(t.toLowerCase()),\n );\n if (!hasTable) return false;\n }\n\n if (this.options.filter && !this.options.filter(pair)) {\n return false;\n }\n\n return true;\n });\n\n if (filtered.length) {\n yield filtered;\n }\n }\n }\n}\n", "import { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface DeduplicatedProducerOptions {\n strategy?: 'exact' | 'sql-only' | 'question-only';\n}\n\n/**\n * DeduplicatedProducer - Remove duplicate pairs from another producer.\n *\n * Wraps another PairProducer and removes duplicates based on\n * exact match or semantic similarity.\n */\nexport class DeduplicatedProducer extends PairProducer {\n /**\n * @param producer - Source producer to deduplicate\n * @param options - Deduplication configuration\n */\n constructor(\n private producer: PairProducer,\n private options: DeduplicatedProducerOptions = {},\n ) {\n super();\n }\n\n /**\n * Produces pairs with duplicates removed based on the configured strategy.\n * @returns Unique pairs after deduplication\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const { strategy = 'exact' } = this.options;\n const seen = new Set<string>();\n\n for await (const chunk of this.producer.produce()) {\n const unique: ExtractedPair[] = [];\n\n for (const pair of chunk) {\n let key: string;\n\n switch (strategy) {\n case 'sql-only':\n key = this.normalizeSQL(pair.sql);\n break;\n case 'question-only':\n key = pair.question.toLowerCase().trim();\n break;\n case 'exact':\n default:\n key = `${pair.question.toLowerCase().trim()}|||${this.normalizeSQL(pair.sql)}`;\n }\n\n if (!seen.has(key)) {\n seen.add(key);\n unique.push(pair);\n }\n }\n\n if (unique.length) {\n yield unique;\n }\n }\n }\n\n private normalizeSQL(sql: string): string {\n return sql.toLowerCase().replace(/\\s+/g, ' ').trim();\n }\n}\n", "import type { Adapter } from '../../adapters/adapter.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface ValidatedProducerOptions {\n execute?: boolean;\n removeInvalid?: boolean;\n}\n\nexport interface ValidatedPair extends ExtractedPair {\n rowCount?: number;\n error?: string;\n}\n/**\n * ValidatedProducer - Validate SQL from another producer.\n *\n * Wraps another PairProducer and validates each SQL query,\n * optionally executing to attach results.\n */\nexport class ValidatedProducer extends PairProducer<ValidatedPair> {\n /**\n * @param producer - Source producer to validate\n * @param adapter - Database adapter for SQL validation\n * @param options - Validation configuration\n */\n constructor(\n private producer: PairProducer,\n private adapter: Adapter,\n private options: ValidatedProducerOptions = {},\n ) {\n super();\n }\n\n /**\n * Produces pairs with SQL validation applied, optionally executing queries.\n * @returns Validated pairs with error/rowCount metadata attached\n */\n async *produce(): AsyncGenerator<ValidatedPair[]> {\n for await (const chunk of this.producer.produce()) {\n const validated: ValidatedPair[] = [];\n\n for (const pair of chunk) {\n const error = await this.adapter.validate(pair.sql);\n\n if (error) {\n if (!this.options.removeInvalid) {\n validated.push({\n ...pair,\n success: false,\n error,\n });\n }\n continue;\n }\n\n let rowCount: number | undefined;\n if (this.options.execute) {\n try {\n const result = await this.adapter.execute(pair.sql);\n rowCount = Array.isArray(result) ? result.length : undefined;\n } catch {\n // no op\n }\n }\n\n validated.push({\n ...pair,\n success: true,\n rowCount,\n });\n }\n\n if (validated.length) {\n yield validated;\n }\n }\n }\n}\n", "import {\n type UIMessage,\n getToolOrDynamicToolName,\n isToolOrDynamicToolUIPart,\n} from 'ai';\n\nimport { type ExtractedPair, PairProducer } from '../types.ts';\nimport {\n type DbQueryInput,\n getMessageText,\n} from './base-contextual-extractor.ts';\n\nexport interface MessageExtractorOptions {\n includeFailures?: boolean;\n toolName?: string;\n}\n/**\n * MessageExtractor - Extract pairs from chat history by parsing tool calls.\n *\n * Deterministic extraction: parses db_query tool calls and pairs them\n * with the preceding user message.\n */\nexport class MessageExtractor extends PairProducer {\n /**\n * @param messages - Chat history to extract pairs from\n * @param options - Extraction configuration\n */\n constructor(\n private messages: UIMessage[],\n private options: MessageExtractorOptions = {},\n ) {\n super();\n }\n\n /**\n * Extracts question-SQL pairs by parsing tool calls and pairing with user messages.\n * @returns Pairs extracted from db_query tool invocations\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const { includeFailures = false, toolName = 'db_query' } = this.options;\n let lastUserMessage: UIMessage | null = null;\n\n for (const message of this.messages) {\n if (message.role === 'user') {\n lastUserMessage = message;\n continue;\n }\n\n if (message.role === 'assistant' && lastUserMessage) {\n for (const part of message.parts) {\n if (!isToolOrDynamicToolUIPart(part)) {\n continue;\n }\n\n if (getToolOrDynamicToolName(part) !== toolName) {\n continue;\n }\n\n // Handle both static and dynamic tool part shapes\n const toolInput = ('input' in part ? part.input : undefined) as\n | DbQueryInput\n | undefined;\n if (!toolInput?.sql) {\n continue;\n }\n\n const success = part.state === 'output-available';\n const failed = part.state === 'output-error';\n\n if (failed && !includeFailures) {\n continue;\n }\n\n // Skip incomplete tool calls (streaming or pending)\n if (!success && !failed) {\n continue;\n }\n\n const question = getMessageText(lastUserMessage);\n if (!question) {\n continue;\n }\n\n yield [\n {\n question,\n sql: toolInput.sql,\n success,\n },\n ];\n }\n }\n }\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport {\n type UIMessage,\n getToolOrDynamicToolName,\n isTextUIPart,\n isToolOrDynamicToolUIPart,\n} from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface DbQueryInput {\n sql: string;\n reasoning?: string;\n}\n\nexport interface SqlWithContext {\n sql: string;\n success: boolean;\n conversationContext: string[];\n}\n\nexport interface BaseContextualExtractorOptions {\n includeFailures?: boolean;\n toolName?: string;\n}\nexport const contextResolverAgent = agent<\n { question: string },\n { conversation: string; sql: string; introspection?: string }\n>({\n name: 'context_resolver',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n question: z\n .string()\n .describe(\n 'A standalone natural language question that the SQL query answers',\n ),\n }),\n prompt: (state) => dedent`\n <identity>\n You are an expert at understanding conversational context and generating clear,\n standalone questions from multi-turn conversations.\n </identity>\n\n ${state?.introspection ? `<schema>\\n${state.introspection}\\n</schema>` : ''}\n\n <conversation>\n ${state?.conversation}\n </conversation>\n\n <sql>\n ${state?.sql}\n </sql>\n\n <task>\n Given the conversation above and the SQL query that was executed,\n generate a single, standalone natural language question that:\n 1. Fully captures the user's intent without needing prior context\n 2. Uses natural business language (not SQL terminology)\n 3. Could be asked by someone who hasn't seen the conversation\n 4. Accurately represents what the SQL query answers\n </task>\n\n <examples>\n Conversation: \"Show me customers\" \u2192 \"Filter to NY\" \u2192 \"Sort by revenue\"\n SQL: SELECT * FROM customers WHERE region = 'NY' ORDER BY revenue DESC\n Question: \"Show me customers in the NY region sorted by revenue\"\n\n Conversation: \"What were sales last month?\" \u2192 \"Break it down by category\"\n SQL: SELECT category, SUM(amount) FROM sales WHERE date >= '2024-11-01' GROUP BY category\n Question: \"What were sales by category for last month?\"\n </examples>\n `,\n});\n\nexport function getMessageText(message: UIMessage): string {\n const textParts = message.parts.filter(isTextUIPart).map((part) => part.text);\n return textParts.join(' ').trim();\n}\n\nexport function formatConversation(messages: string[]): string {\n return messages.map((msg, i) => `[${i + 1}] ${msg}`).join('\\n');\n}\n\n/**\n * Abstract base class for contextual extractors using Template Pattern.\n *\n * The `produce()` method defines the algorithm skeleton:\n * 1. Iterate through messages\n * 2. Call `onUserMessage()` hook for user messages\n * 3. Extract SQL from assistant messages using `getContextSnapshot()` hook\n * 4. Resolve questions using LLM\n *\n * Subclasses implement the hooks to customize context management.\n */\nexport abstract class BaseContextualExtractor extends PairProducer {\n protected context: string[] = [];\n protected results: SqlWithContext[] = [];\n\n constructor(\n protected messages: UIMessage[],\n protected adapter: Adapter,\n protected options: BaseContextualExtractorOptions = {},\n ) {\n super();\n }\n\n /**\n * Template method - defines the extraction algorithm skeleton.\n * Subclasses customize behavior via hooks, not by overriding this method.\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n // Reset state for each produce() invocation to prevent race conditions\n // if produce() is called multiple times concurrently\n this.context = [];\n this.results = [];\n\n const { includeFailures = false, toolName = 'db_query' } = this.options;\n\n // Step 1: Extract SQLs with context (calls hooks)\n await this.extractSqlsWithContext(toolName, includeFailures);\n\n if (this.results.length === 0) {\n return;\n }\n\n // Step 2: Get introspection for schema context\n const introspection = await this.adapter.introspect();\n\n // Step 3: Resolve each SQL's context into a standalone question\n yield* this.resolveQuestions(introspection);\n }\n\n /**\n * Core extraction loop - iterates through messages and calls hooks.\n */\n private async extractSqlsWithContext(\n toolName: string,\n includeFailures: boolean,\n ): Promise<void> {\n for (const message of this.messages) {\n if (message.role === 'user') {\n const text = getMessageText(message);\n if (text) {\n await this.onUserMessage(text);\n }\n continue;\n }\n\n if (message.role === 'assistant') {\n await this.extractFromAssistant(message, toolName, includeFailures);\n }\n }\n }\n\n /**\n * Extract SQL from assistant message parts.\n */\n private async extractFromAssistant(\n message: UIMessage,\n toolName: string,\n includeFailures: boolean,\n ): Promise<void> {\n for (const part of message.parts) {\n if (!isToolOrDynamicToolUIPart(part)) {\n continue;\n }\n\n if (getToolOrDynamicToolName(part) !== toolName) {\n continue;\n }\n\n // Use 'input' property (not 'args') to match useChat structure\n const toolInput = ('input' in part ? part.input : undefined) as\n | DbQueryInput\n | undefined;\n if (!toolInput?.sql) {\n continue;\n }\n\n const success = part.state === 'output-available';\n const failed = part.state === 'output-error';\n\n if (failed && !includeFailures) {\n continue;\n }\n\n // Skip if still streaming or not yet executed\n if (!success && !failed) {\n continue;\n }\n\n const snapshot = this.getContextSnapshot();\n // Skip if no context available\n if (snapshot.length === 0) {\n continue;\n }\n\n this.results.push({\n sql: toolInput.sql,\n success,\n conversationContext: snapshot,\n });\n }\n\n // Add assistant text responses to context (for multi-turn understanding)\n const assistantText = getMessageText(message);\n if (assistantText) {\n this.context.push(`Assistant: ${assistantText}`);\n }\n }\n\n /**\n * Resolve extracted SQL contexts into standalone questions using LLM.\n */\n protected async *resolveQuestions(\n introspection: string,\n ): AsyncGenerator<ExtractedPair[]> {\n for (const item of this.results) {\n const { experimental_output } = await generate(\n contextResolverAgent,\n [user('Generate a standalone question for this SQL query.')],\n {\n conversation: formatConversation(item.conversationContext),\n sql: item.sql,\n introspection,\n },\n );\n\n yield [\n {\n question: experimental_output.question,\n sql: item.sql,\n context: item.conversationContext,\n success: item.success,\n },\n ];\n }\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // HOOKS - Subclasses override these to customize context management\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Hook called when a user message is encountered.\n * Subclasses implement this to decide how to update context.\n */\n protected abstract onUserMessage(text: string): Promise<void>;\n\n /**\n * Hook called when extracting SQL to get the current context snapshot.\n * Subclasses implement this to decide what context to include.\n */\n protected abstract getContextSnapshot(): string[];\n}\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\nexport interface SqlExtractorOptions {\n validateSql?: boolean;\n skipInvalid?: boolean;\n}\n\n/**\n * Agent that generates natural language questions from SQL queries.\n */\nconst sqlToQuestionAgent = agent<\n { question: string },\n { sql: string; introspection: string }\n>({\n name: 'sql_to_question',\n model: groq('llama-3.3-70b-versatile'),\n output: z.object({\n question: z\n .string()\n .describe('A natural language question that the SQL query answers'),\n }),\n prompt: (state) => dedent`\n <identity>\n You are an expert at understanding SQL queries and generating clear,\n natural language questions that describe what the query retrieves.\n </identity>\n\n <schema>\n ${state?.introspection}\n </schema>\n\n <sql>\n ${state?.sql}\n </sql>\n\n <task>\n Given the database schema and the SQL query above, generate a single\n natural language question that:\n 1. Accurately describes what information the query retrieves\n 2. Uses natural business language (not SQL terminology)\n 3. Could be asked by a non-technical user\n 4. Is concise but complete\n </task>\n\n <examples>\n SQL: SELECT COUNT(*) FROM customers WHERE region = 'NY'\n Question: \"How many customers do we have in New York?\"\n\n SQL: SELECT product_name, SUM(quantity) as total FROM orders GROUP BY product_name ORDER BY total DESC LIMIT 10\n Question: \"What are our top 10 products by quantity sold?\"\n\n SQL: SELECT c.name, COUNT(o.id) FROM customers c LEFT JOIN orders o ON c.id = o.customer_id GROUP BY c.id HAVING COUNT(o.id) = 0\n Question: \"Which customers have never placed an order?\"\n </examples>\n `,\n});\n/**\n * SqlExtractor - Generate questions for existing SQL queries.\n *\n * Given a list of SQL queries, uses an LLM to generate the natural\n * language questions they answer.\n */\nexport class SqlExtractor extends PairProducer {\n #sqls: string[];\n #adapter: Adapter;\n #options: SqlExtractorOptions;\n\n /**\n * @param sql - SQL query or queries to generate questions for\n * @param adapter - Database adapter for validation and schema introspection\n * @param options - Extraction configuration\n */\n constructor(\n sql: string[] | string,\n adapter: Adapter,\n options: SqlExtractorOptions = {},\n ) {\n super();\n this.#sqls = Array.isArray(sql) ? sql : [sql];\n this.#adapter = adapter;\n this.#options = options;\n }\n\n /**\n * Generates natural language questions for each SQL query using an LLM.\n * @returns Pairs with generated questions and original SQL\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const { validateSql = true, skipInvalid = false } = this.#options;\n const introspection = await this.#adapter.introspect();\n\n for (const sql of this.#sqls) {\n let isValid = true;\n if (validateSql) {\n const error = await this.#adapter.validate(sql);\n isValid = error === undefined || error === null;\n\n if (!isValid && skipInvalid) {\n continue;\n }\n }\n\n const { experimental_output } = await generate(\n sqlToQuestionAgent,\n [user('Generate a natural language question for this SQL query.')],\n {\n sql,\n introspection,\n },\n );\n\n yield [\n {\n question: experimental_output.question,\n sql,\n success: isValid,\n },\n ];\n }\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n} from './base-contextual-extractor.ts';\n\nexport type FullContextExtractorOptions = BaseContextualExtractorOptions;\n\n/**\n * Extracts SQL pairs with full conversation context.\n *\n * @example\n * ```typescript\n * const extractor = new FullContextExtractor(messages, adapter);\n * const pairs = await extractor.produce();\n * ```\n */\nexport class FullContextExtractor extends BaseContextualExtractor {\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: FullContextExtractorOptions = {},\n ) {\n super(messages, adapter, options);\n }\n\n /**\n * Add user message to context (keeps all messages).\n */\n protected async onUserMessage(text: string): Promise<void> {\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return all context accumulated so far.\n */\n protected getContextSnapshot(): string[] {\n return [...this.context];\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n} from './base-contextual-extractor.ts';\n\nexport interface WindowedContextExtractorOptions\n extends BaseContextualExtractorOptions {\n windowSize: number;\n}\n\n/**\n * Extracts SQL pairs with a sliding window of conversation context.\n *\n * @example\n * ```typescript\n * const extractor = new WindowedContextExtractor(messages, adapter, {\n * windowSize: 5,\n * });\n * const pairs = await extractor.produce();\n * ```\n */\nexport class WindowedContextExtractor extends BaseContextualExtractor {\n private windowSize: number;\n\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: WindowedContextExtractorOptions,\n ) {\n super(messages, adapter, options);\n this.windowSize = options.windowSize;\n }\n\n /**\n * Add user message to context (keeps all, windowing happens on snapshot).\n */\n protected async onUserMessage(text: string): Promise<void> {\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return only the last N messages based on window size.\n */\n protected getContextSnapshot(): string[] {\n if (this.context.length <= this.windowSize) {\n return [...this.context];\n }\n return this.context.slice(-this.windowSize);\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport type { UIMessage } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n contextResolverAgent,\n formatConversation,\n} from './base-contextual-extractor.ts';\n\nexport type SegmentedContextExtractorOptions = BaseContextualExtractorOptions;\n\n/** Agent that detects if a new message represents a topic change */\nconst topicChangeAgent = agent<\n { isTopicChange: boolean; reason: string },\n { context: string; newMessage: string }\n>({\n name: 'topic_change_detector',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n isTopicChange: z\n .boolean()\n .describe('Whether the new message represents a topic change'),\n reason: z.string().describe('Brief explanation for the decision'),\n }),\n prompt: (state) => dedent`\n <identity>\n You are an expert at understanding conversational flow and detecting topic changes.\n </identity>\n\n <conversation_context>\n ${state?.context || '(no prior context)'}\n </conversation_context>\n\n <new_message>\n ${state?.newMessage}\n </new_message>\n\n <task>\n Determine if the new message represents a significant topic change from the\n prior conversation context. A topic change occurs when:\n 1. The user asks about a completely different entity/table/domain\n 2. The user starts a new analytical question unrelated to prior discussion\n 3. There's a clear shift in what data or metrics are being discussed\n\n NOT a topic change:\n - Follow-up questions refining the same query (\"filter by...\", \"sort by...\")\n - Questions about the same entities with different conditions\n - Requests for more details on the same topic\n </task>\n\n <examples>\n Context: \"Show me customers in NY\" \u2192 \"Sort by revenue\"\n New: \"Filter to those with orders over $1000\"\n Decision: NOT a topic change (still refining customer query)\n\n Context: \"Show me customers in NY\" \u2192 \"Sort by revenue\"\n New: \"What were our total sales last quarter?\"\n Decision: Topic change (shifted from customers to sales metrics)\n\n Context: \"List all products\"\n New: \"How many orders did we have last month?\"\n Decision: Topic change (products \u2192 orders/sales)\n </examples>\n `,\n});\n\n/**\n * Extracts SQL pairs with topic-aware context segmentation.\n *\n * When a topic change is detected:\n * 1. The triggering message is resolved to standalone form using LLM\n * 2. Context is reset\n * 3. The resolved message becomes the start of the new context\n *\n * @example\n * ```typescript\n * const extractor = new SegmentedContextExtractor(messages, adapter);\n * const pairs = await extractor.produce();\n * ```\n */\nexport class SegmentedContextExtractor extends BaseContextualExtractor {\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: SegmentedContextExtractorOptions = {},\n ) {\n super(messages, adapter, options);\n }\n\n /**\n * Handle user message with topic change detection.\n * If topic changes, resolve the message to standalone form before resetting.\n *\n * Note: We capture context snapshot before async LLM calls to prevent race conditions\n * where context might be modified during the async operation.\n */\n protected async onUserMessage(text: string): Promise<void> {\n // Check for topic change if we have enough context\n if (this.context.length >= 2) {\n // Capture snapshot BEFORE async calls to prevent race conditions\n const contextSnapshot = [...this.context];\n const isTopicChange = await this.detectTopicChange(text, contextSnapshot);\n if (isTopicChange) {\n // Resolve the triggering message BEFORE resetting context\n const resolved = await this.resolveToStandalone(text, contextSnapshot);\n this.context = [`User: ${resolved}`];\n return;\n }\n }\n\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return all context in current topic segment.\n */\n protected getContextSnapshot(): string[] {\n return [...this.context];\n }\n\n /**\n * Detect if a new message represents a topic change using LLM.\n * @param newMessage - The new user message to check\n * @param contextSnapshot - Snapshot of context captured before this async call\n */\n private async detectTopicChange(\n newMessage: string,\n contextSnapshot: string[],\n ): Promise<boolean> {\n const { experimental_output } = await generate(\n topicChangeAgent,\n [user('Determine if this is a topic change.')],\n {\n context: formatConversation(contextSnapshot),\n newMessage,\n },\n );\n\n return experimental_output.isTopicChange;\n }\n\n /**\n * Resolve a context-dependent message into a standalone question.\n * Called when topic change is detected to preserve the meaning of\n * the triggering message before context is reset.\n * @param text - The user message to resolve\n * @param contextSnapshot - Snapshot of context captured before this async call\n */\n private async resolveToStandalone(\n text: string,\n contextSnapshot: string[],\n ): Promise<string> {\n const { experimental_output } = await generate(\n contextResolverAgent,\n [user('Generate a standalone question for this message.')],\n {\n conversation: formatConversation([...contextSnapshot, `User: ${text}`]),\n sql: '', // No SQL yet, just resolving the question\n },\n );\n\n return experimental_output.question;\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport { generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport type { ExtractedPair } from '../types.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n contextResolverAgent,\n formatConversation,\n} from './base-contextual-extractor.ts';\n\nexport type LastQueryExtractorOptions = BaseContextualExtractorOptions;\n\n/**\n * Extracts only the last SQL query with its resolved question.\n *\n * @example\n * ```typescript\n * const extractor = new LastQueryExtractor(messages, adapter);\n * const pairs = await toPairs(extractor); // Returns array with at most 1 pair\n * ```\n */\nexport class LastQueryExtractor extends BaseContextualExtractor {\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: LastQueryExtractorOptions = {},\n ) {\n super(messages, adapter, options);\n }\n\n /**\n * Add user message to context (keeps all messages).\n */\n protected async onUserMessage(text: string): Promise<void> {\n this.context.push(`User: ${text}`);\n }\n\n /**\n * Return all context accumulated so far.\n */\n protected getContextSnapshot(): string[] {\n return [...this.context];\n }\n\n /**\n * Override to only resolve the LAST query instead of all queries.\n */\n protected override async *resolveQuestions(\n introspection: string,\n ): AsyncGenerator<ExtractedPair[]> {\n if (this.results.length === 0) {\n return;\n }\n\n const last = this.results.at(-1)!;\n const { experimental_output } = await generate(\n contextResolverAgent,\n [user('Generate a standalone question for this SQL query.')],\n {\n conversation: formatConversation(last.conversationContext),\n sql: last.sql,\n introspection,\n },\n );\n\n yield [\n {\n question: experimental_output.question,\n sql: last.sql,\n context: last.conversationContext,\n success: last.success,\n },\n ];\n }\n}\n", "import pLimit from 'p-limit';\n\nimport type { AgentModel } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n type QuestionComplexity,\n generateQuestions,\n} from '../../agents/question.agent.ts';\nimport {\n type ToSqlResult,\n UnanswerableSQLError,\n toSql,\n} from '../../agents/sql.agent.ts';\nimport type { Teachables } from '../../teach/teachables.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\nimport type { Persona } from './persona-generator.ts';\n\nexport interface SchemaSynthesizerOptions {\n count: number;\n complexity?: QuestionComplexity | QuestionComplexity[];\n personas?: Persona[];\n teachings?: Teachables[];\n model?: AgentModel;\n concurrency?: number;\n}\n/**\n * SchemaSynthesizer - Generate pairs from database schema.\n *\n * Fully synthetic: generates natural language questions at specified\n * complexity levels and personas, then generates SQL for each question.\n * Iterates through all persona \u00D7 complexity combinations.\n */\nexport class SchemaSynthesizer extends PairProducer {\n #complexities: QuestionComplexity[] = [];\n #personas: (Persona | undefined)[] = [];\n #limit: ReturnType<typeof pLimit>;\n\n /**\n * @param adapter - Database adapter for schema introspection and SQL validation\n * @param options - Synthesis configuration including count, complexity, and concurrency\n */\n constructor(\n private adapter: Adapter,\n private options: SchemaSynthesizerOptions,\n ) {\n super();\n this.#complexities = Array.isArray(this.options.complexity)\n ? this.options.complexity\n : [this.options.complexity ?? 'moderate'];\n\n this.#personas = this.options.personas ?? [undefined];\n this.#limit = pLimit(this.options.concurrency ?? 5);\n }\n\n /**\n * Generates question-SQL pairs by iterating through all persona \u00D7 complexity combinations.\n * Uses parallel processing bounded by the configured concurrency limit.\n * Yields results as each combination completes (streaming pattern).\n * @returns Generated pairs from all combinations\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const introspection = await this.adapter.introspect();\n\n const combinations = this.#personas.flatMap((persona) =>\n this.#complexities.map((complexity) => ({ persona, complexity })),\n );\n\n // Process each combination and yield immediately as it completes\n // pLimit handles concurrency - no need to create all promises upfront\n for (const { persona, complexity } of combinations) {\n const pairs = await this.#processCombination(\n introspection,\n persona,\n complexity,\n );\n if (pairs.length) {\n yield pairs;\n }\n }\n }\n\n /**\n * Processes a single persona \u00D7 complexity combination by generating questions\n * and converting each to SQL in parallel.\n */\n async #processCombination(\n introspection: Awaited<ReturnType<Adapter['introspect']>>,\n persona: Persona | undefined,\n complexity: QuestionComplexity,\n ): Promise<ExtractedPair[]> {\n const personaContext = persona\n ? `As ${persona.role}, ${persona.perspective}\\n\\nGenerate questions this persona would ask.`\n : undefined;\n\n const prompt = personaContext\n ? `${personaContext}\\n\\nGenerate ${this.options.count} questions at ${complexity} complexity.`\n : undefined;\n\n const { questions } = await this.#limit(() =>\n generateQuestions({\n introspection,\n complexity,\n count: this.options.count,\n prompt,\n model: this.options.model,\n }),\n );\n\n const pairs = await Promise.all(\n questions.map(async (question) => {\n const result = await this.#limit(async () => {\n try {\n return await toSql({\n input: question,\n adapter: this.adapter,\n introspection,\n instructions: this.options.teachings ?? [],\n model: this.options.model,\n });\n } catch (error) {\n if (UnanswerableSQLError.isInstance(error)) {\n return {\n attempts: 0,\n sql: '',\n errors: [\n `Cannot answer the question ${question} because ${error.message}`,\n ],\n } satisfies ToSqlResult;\n }\n throw error;\n }\n });\n\n return {\n question,\n sql: result.sql,\n success: !result.errors || result.errors.length === 0,\n };\n }),\n );\n\n return pairs;\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nexport type QuestionComplexity =\n | 'simple'\n | 'moderate'\n | 'complex'\n | 'high complex';\n\ntype QuestionGeneratorState = {\n introspection: string;\n complexity: QuestionComplexity;\n count: number;\n};\n\ntype QuestionGeneratorOutput = {\n questions: string[];\n};\n\nconst complexityInstructions: Record<QuestionComplexity, string> = {\n simple: dedent`\n Generate simple questions that require:\n - Basic SELECT with single table\n - Simple WHERE clauses with one condition\n - COUNT(*) or basic aggregations\n - No joins required\n Examples: \"How many customers do we have?\", \"List all products\", \"What is the total revenue?\"\n `,\n moderate: dedent`\n Generate moderate questions that require:\n - JOINs between 2-3 tables\n - Multiple WHERE conditions (AND/OR)\n - GROUP BY with HAVING clauses\n - ORDER BY with LIMIT\n - Basic subqueries\n Examples: \"What are the top 5 customers by total orders?\", \"Which products have never been ordered?\"\n `,\n complex: dedent`\n Generate complex questions that require:\n - Multiple JOINs (3+ tables)\n - Nested subqueries or CTEs\n - Complex aggregations with multiple GROUP BY columns\n - CASE expressions\n - Date/time calculations\n Examples: \"What is the month-over-month growth rate?\", \"Which customers have increased spending compared to last year?\"\n `,\n 'high complex': dedent`\n Generate highly complex questions that require advanced SQL features:\n - Window functions (ROW_NUMBER, RANK, DENSE_RANK)\n - LAG, LEAD for comparisons\n - Running totals (SUM OVER)\n - Moving averages\n - PARTITION BY clauses\n - Complex CTEs with multiple levels\n Examples: \"What is the running total of sales per month?\", \"Rank customers by their purchase frequency within each region\"\n `,\n};\n\n/**\n * Agent that generates natural language questions from database introspection.\n */\nconst questionGeneratorAgent = agent<\n QuestionGeneratorOutput,\n QuestionGeneratorState\n>({\n name: 'question_generator',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.8, topP: 0.95 },\n }),\n }),\n handoffDescription:\n 'Generates natural language questions that users might ask about the database schema.',\n output: z.object({\n questions: z\n .array(z.string().describe('A natural language question about the data'))\n .min(1)\n .describe('List of natural language questions a user might ask'),\n }),\n prompt: (state) => {\n const count = state?.count;\n const complexity = state?.complexity ?? 'moderate';\n\n return dedent`\n <identity>\n You are a synthetic data generator specializing in creating realistic natural language questions\n that users might ask about a database. You understand database schemas and can generate diverse,\n practical questions that would require SQL queries to answer.\n </identity>\n\n ${state?.introspection || ''}\n\n <complexity level=\"${complexity}\">\n ${complexityInstructions[complexity]}\n </complexity>\n\n <task>\n Generate exactly ${count} natural language questions at the \"${complexity}\" complexity level.\n The questions should:\n 1. Match the complexity requirements above\n 2. Use natural business language, not technical SQL terms\n 3. Be realistic questions a non-technical user would actually ask\n 4. Cover different tables and relationships when possible\n </task>\n\n <guardrails>\n - Questions MUST ONLY reference tables and columns that exist in the schema above\n - Before generating each question, verify that ALL entities (tables, columns, relationships) you reference are explicitly listed in the schema\n - DO NOT invent or assume tables/columns that aren't explicitly shown in the schema\n - Use natural language without SQL keywords like SELECT, WHERE, etc.\n - All questions must match the specified complexity level\n </guardrails>\n `;\n },\n});\n\nexport interface GenerateQuestionsParams {\n /** Database schema introspection */\n introspection: string;\n /** Complexity level for generated questions */\n complexity: QuestionComplexity;\n /** Number of questions to generate */\n count: number;\n /** Optional prompt to prepend (e.g., persona context) */\n prompt?: string;\n /** Optional model override */\n model?: AgentModel;\n}\n\nexport interface GenerateQuestionsResult {\n questions: string[];\n}\n\n/**\n * Generate natural language questions from database schema.\n * Used for creating synthetic training data for text-to-SQL models.\n */\nexport async function generateQuestions(\n params: GenerateQuestionsParams,\n): Promise<GenerateQuestionsResult> {\n const { introspection, complexity, count, prompt, model } = params;\n\n const agentInstance = model\n ? questionGeneratorAgent.clone({ model })\n : questionGeneratorAgent;\n\n const userPrompt =\n prompt ??\n `Generate ${count} questions at ${complexity} complexity given db schema.`;\n\n const { experimental_output } = await generate(\n agentInstance,\n [user(userPrompt)],\n {\n introspection,\n complexity,\n count,\n },\n );\n\n return { questions: experimental_output.questions };\n}\n", "import { groq } from '@ai-sdk/groq';\nimport {\n APICallError,\n JSONParseError,\n NoContentGeneratedError,\n NoObjectGeneratedError,\n NoOutputGeneratedError,\n TypeValidationError,\n defaultSettingsMiddleware,\n wrapLanguageModel,\n} from 'ai';\nimport { Console } from 'node:console';\nimport { createWriteStream } from 'node:fs';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport {\n type AgentModel,\n agent,\n generate,\n toOutput,\n user,\n} from '@deepagents/agent';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\nexport interface ToSqlOptions {\n /** The natural language input to convert to SQL */\n input: string;\n /** Database adapter for validation */\n adapter: Adapter;\n /** Introspection/schema context */\n introspection: string;\n /** Instructions/teachings to include */\n instructions: Teachables[];\n /** Optional model override */\n model?: AgentModel;\n /** Maximum retry attempts on validation failure (default: 3) */\n maxRetries?: number;\n}\n\nexport interface ToSqlResult {\n /** The generated SQL query */\n sql: string;\n /** Number of attempts made */\n attempts: number;\n /** Validation errors encountered (if any retries occurred) */\n errors?: string[];\n}\n\nconst logger = new Console({\n stdout: createWriteStream('./sql-agent.log', { flags: 'a' }),\n stderr: createWriteStream('./sql-agent-error.log', { flags: 'a' }),\n inspectOptions: { depth: null },\n});\n\ntype SqlGeneratorState = {\n // FIXME: this should not be here after creating the context package\n introspection: string;\n teachings: string;\n};\n\ntype SqlGeneratorOutput =\n | { sql: string; reasoning?: string }\n | { error: string };\n\n/**\n * Agent that generates SQL queries from introspection and natural language questions.\n * Used for creating synthetic training data for text-to-SQL models.\n */\n/** Temperature progression for retries: deterministic first, then increasingly exploratory */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\n\nconst sqlQueryAgent = agent<SqlGeneratorOutput, SqlGeneratorState>({\n name: 'text2sql',\n model: groq('openai/gpt-oss-20b'),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.union([\n z.object({\n sql: z.string().describe('The SQL query that answers the question'),\n reasoning: z\n .string()\n .optional()\n .describe('The reasoning steps taken to generate the SQL'),\n }),\n z.object({\n error: z\n .string()\n .describe(\n 'Error message explaining why the question cannot be answered with the given schema',\n ),\n }),\n ]),\n prompt: (state) => {\n return `\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n `;\n },\n});\n\n/** Extract SQL from markdown fenced code block if present */\nfunction extractSql(output: string): string {\n const match = output.match(/```sql\\n?([\\s\\S]*?)```/);\n return match ? match[1].trim() : output.trim();\n}\n\nconst marker = Symbol('SQLValidationError');\n/**\n * Error thrown when SQL validation fails.\n */\nexport class SQLValidationError extends Error {\n [marker]: true;\n constructor(message: string) {\n super(message);\n this.name = 'SQLValidationError';\n this[marker] = true;\n }\n static isInstance(error: unknown): error is SQLValidationError {\n return error instanceof SQLValidationError && error[marker] === true;\n }\n}\n\n/**\n * Error thrown when the question cannot be answered with the given schema.\n */\nexport class UnanswerableSQLError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UnanswerableSQLError';\n }\n static isInstance(error: unknown): error is UnanswerableSQLError {\n return error instanceof UnanswerableSQLError;\n }\n}\n\nexport async function toSql(options: ToSqlOptions): Promise<ToSqlResult> {\n const { maxRetries = 3 } = options;\n\n return withRetry(\n async (attemptNumber, errors, attempts) => {\n const agentInstance = sqlQueryAgent.clone({\n model: wrapLanguageModel({\n model: options.model ?? sqlQueryAgent.model,\n middleware: defaultSettingsMiddleware({\n settings: {\n temperature: RETRY_TEMPERATURES[attemptNumber - 1] ?? 0.3,\n topP: 1,\n },\n }),\n }),\n });\n\n const messages = errors.length\n ? [\n user(options.input),\n user(\n `<validation_error>Your previous SQL query had the following error: ${errors.at(-1)?.message}. Please fix the query.</validation_error>`,\n ),\n ]\n : [user(options.input)];\n\n const output = await toOutput(\n generate(agentInstance, messages, {\n introspection: options.introspection,\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator. You translate natural language questions into precise, efficient SQL queries based on the provided database schema.',\n }),\n ...options.instructions,\n ),\n }),\n );\n\n // Handle error responses (question is unanswerable with given schema)\n if ('error' in output) {\n throw new UnanswerableSQLError(output.error);\n }\n\n const sql = extractSql(output.sql);\n\n // Validate the generated SQL\n const validationError = await options.adapter.validate(sql);\n if (validationError) {\n throw new SQLValidationError(validationError);\n }\n\n return {\n attempts,\n sql,\n errors: errors.length ? errors.map(formatErrorMessage) : undefined,\n };\n },\n { retries: maxRetries - 1 },\n );\n}\n\nfunction formatErrorMessage(error: Error) {\n if (APICallError.isInstance(error)) {\n if (error.message.startsWith('Failed to validate JSON')) {\n return `Schema validation failed: ${error.message}`;\n }\n return error.message;\n }\n if (SQLValidationError.isInstance(error)) {\n return `SQL Validation Error: ${error.message}`;\n }\n return error.message;\n}\n\nasync function withRetry<T>(\n computation: (\n attemptNumber: number,\n errors: Error[],\n attempts: number,\n ) => Promise<T>,\n options: { retries: number } = { retries: 3 },\n) {\n const errors: Error[] = [];\n let attempts = 0;\n return pRetry(\n (attemptNumber) => {\n return computation(attemptNumber, errors, ++attempts);\n },\n {\n retries: options.retries,\n shouldRetry: (context) => {\n // Don't retry if unanswerable - it's intentional\n if (UnanswerableSQLError.isInstance(context.error)) {\n return false;\n }\n // Retry on validation errors\n if (SQLValidationError.isInstance(context.error)) {\n return true;\n }\n console.log({\n NoObjectGeneratedError: NoObjectGeneratedError.isInstance(\n context.error,\n ),\n NoOutputGeneratedError: NoOutputGeneratedError.isInstance(\n context.error,\n ),\n APICallError: APICallError.isInstance(context.error),\n JSONParseError: JSONParseError.isInstance(context.error),\n TypeValidationError: TypeValidationError.isInstance(context.error),\n NoContentGeneratedError: NoContentGeneratedError.isInstance(\n context.error,\n ),\n });\n // Retry on AI SDK errors\n return (\n APICallError.isInstance(context.error) ||\n JSONParseError.isInstance(context.error) ||\n TypeValidationError.isInstance(context.error) ||\n NoObjectGeneratedError.isInstance(context.error) ||\n NoOutputGeneratedError.isInstance(context.error) ||\n NoContentGeneratedError.isInstance(context.error)\n );\n },\n onFailedAttempt(context) {\n logger.error(`toSQL`, context.error);\n console.log(\n `Attempt ${context.attemptNumber} failed. There are ${context.retriesLeft} retries left.`,\n );\n // console.dir(context.error, { depth: null });\n errors.push(context.error);\n },\n },\n );\n}\n", "export function wrapBlock(tag: string, children: string[]): string {\n const content = children\n .filter((child): child is string => Boolean(child))\n .join('\\n');\n if (!content) {\n return '';\n }\n return `<${tag}>\\n${indentBlock(content, 2)}\\n</${tag}>`;\n}\n\nexport function list(tag: string, values: string[], childTag: string): string {\n if (!values.length) {\n return '';\n }\n const children = values.map((value) => leaf(childTag, value)).join('\\n');\n return `<${tag}>\\n${indentBlock(children, 2)}\\n</${tag}>`;\n}\n\nexport function leaf(tag: string, value: string): string {\n const safe = escapeXml(value);\n if (safe.includes('\\n')) {\n return `<${tag}>\\n${indentBlock(safe, 2)}\\n</${tag}>`;\n }\n return `<${tag}>${safe}</${tag}>`;\n}\n\nexport function indentBlock(text: string, spaces: number): string {\n if (!text.trim()) {\n return '';\n }\n const padding = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.length ? padding + line : padding))\n .join('\\n');\n}\n\nexport function escapeXml(value: string): string {\n if (value == null) {\n return '';\n }\n return value\n .replaceAll(/&/g, '&')\n .replaceAll(/</g, '<')\n .replaceAll(/>/g, '>')\n .replaceAll(/\"/g, '"')\n .replaceAll(/'/g, ''');\n}\n", "import { indentBlock, leaf, list, wrapBlock } from './xml.ts';\n\nexport interface Teachables {\n type: GeneratedTeachable['type'] | 'user_profile';\n /** Serialize to GeneratedTeachable for storage */\n encode: () => GeneratedTeachable;\n /** Render to XML string for prompts */\n decode: () => string;\n}\nexport type GeneratedTeachable =\n | { type: 'term'; name: string; definition: string }\n | { type: 'hint'; text: string }\n | { type: 'guardrail'; rule: string; reason?: string; action?: string }\n | {\n type: 'explain';\n concept: string;\n explanation: string;\n therefore?: string;\n }\n | { type: 'example'; question: string; answer: string; note?: string }\n | { type: 'clarification'; when: string; ask: string; reason: string }\n | {\n type: 'workflow';\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n }\n | { type: 'quirk'; issue: string; workaround: string }\n | { type: 'styleGuide'; prefer: string; never?: string; always?: string }\n | {\n type: 'analogy';\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n }\n | { type: 'glossary'; entries: Record<string, string> }\n // User-specific teachable types\n | { type: 'identity'; name?: string; role?: string }\n | { type: 'persona'; name: string; role: string; tone: string }\n | { type: 'alias'; term: string; meaning: string }\n | { type: 'preference'; aspect: string; value: string }\n | { type: 'context'; description: string }\n | { type: 'correction'; subject: string; clarification: string };\n\n/**\n * Teach the system domain-specific vocabulary and business terminology.\n *\n * Use this to define simple, direct mappings between business terms and their meanings.\n * The system will understand these terms when users mention them in queries.\n *\n * @param name - The business term or acronym to define\n * @param definition - What the term means in your domain\n *\n * @example\n * // Logistics/Transportation dataset\n * term(\"deadhead miles\", \"distance driven with empty truck between deliveries\")\n * term(\"dwell time\", \"total time a truck spends at a loading dock or warehouse\")\n * term(\"LTL\", \"less than truckload - shipment that doesn't fill entire truck\")\n *\n * @example\n * // Education/University dataset\n * term(\"matriculation\", \"students who completed enrollment and started classes\")\n * term(\"DFW rate\", \"percentage of students receiving D, F, or Withdrawal in a course\")\n * term(\"cohort\", \"group of students who entered the same semester or academic year\")\n *\n * @example\n * // Finance/Banking dataset\n * term(\"NPL\", \"non-performing loan - loan past due 90+ days\")\n * term(\"basis points\", \"one hundredth of a percentage point (1% = 100 bps)\")\n * term(\"AUM\", \"assets under management - total market value of client investments\")\n */\nexport function term(name: string, definition: string): Teachables {\n return {\n type: 'term',\n encode: () => ({ type: 'term', name, definition }),\n decode: () =>\n wrapBlock('term', [leaf('name', name), leaf('definition', definition)]),\n };\n}\n\n/**\n * Teach the system behavioral rules and constraints that should always apply.\n *\n * Use this for business logic, data quality rules, or query preferences that should\n * be automatically applied to all relevant queries. Hints are injected as constraints\n * in the system prompt.\n *\n * @param text - The rule or constraint to follow (use imperative language)\n *\n * @example\n * // Manufacturing/Supply Chain dataset\n * hint(\"Always exclude work orders with status = 'simulation' from production metrics\")\n * hint(\"When calculating OEE (overall equipment effectiveness), only count scheduled production time\")\n * hint(\"Defect rates should be calculated per batch, not per individual unit, for consistency\")\n *\n * @example\n * // Real Estate/Property dataset\n * hint(\"Never include properties with listing_status = 'draft' in market analysis\")\n * hint(\"Always filter out duplicate MLS listings - use the earliest listing_date for each property_id\")\n * hint(\"Square footage comparisons must specify if including or excluding basement/garage\")\n *\n * @example\n * // Social Media/Content Platform dataset\n * hint(\"Engagement metrics should exclude bot accounts identified by is_verified_human = false\")\n * hint(\"View counts reset daily - always use cumulative_views for historical analysis\")\n * hint(\"Default content filters to published_status = 'public' unless analyzing drafts\")\n */\nexport function hint(text: string): Teachables {\n return {\n type: 'hint',\n encode: () => ({ type: 'hint', text }),\n decode: () => leaf('hint', text),\n };\n}\n\n/**\n * Define hard guardrails, safety rules, and compliance boundaries the system must enforce.\n *\n * Use this for \"never do\" rules, sensitive data handling, and required behaviors when\n * certain conditions occur. Guardrails should be explicit and action oriented.\n *\n * @param input.rule - The guardrail or restriction to enforce\n * @param input.reason - Why this guardrail exists (compliance, security, performance)\n * @param input.action - What to do when this guardrail is triggered (block, ask, sanitize)\n *\n * @example\n * // Healthcare dataset\n * guardrail({\n * rule: \"Never return PHI like SSN, MRN, or full address in query results\",\n * reason: \"HIPAA compliance\",\n * action: \"If asked, state that identifiable patient data cannot be shared; offer de-identified aggregates instead\"\n * })\n *\n * @example\n * // Finance dataset\n * guardrail({\n * rule: \"Block any query exposing employee-level compensation by name\",\n * reason: \"Confidential payroll data\",\n * action: \"Provide ranges grouped by department or level instead of individual salaries\"\n * })\n *\n * @example\n * // E-commerce dataset\n * guardrail({\n * rule: \"Warn when a query would scan more than 10 million rows; require a narrower date range\",\n * reason: \"Performance and cost control\",\n * action: \"Ask the user to add filters (recent timeframe, specific categories) before proceeding\"\n * })\n */\nexport function guardrail(input: {\n rule: string;\n reason?: string;\n action?: string;\n}): Teachables {\n const { rule, reason, action } = input;\n return {\n type: 'guardrail',\n encode: () => ({ type: 'guardrail', rule, reason, action }),\n decode: () =>\n wrapBlock('guardrail', [\n leaf('rule', rule),\n reason ? leaf('reason', reason) : '',\n action ? leaf('action', action) : '',\n ]),\n };\n}\n\n/**\n * Teach the system a rich understanding of a single concept using metaphors and explanations.\n *\n * Use this when a simple term definition isn't enough - when you need to convey deeper\n * understanding about how to think about and calculate a metric or concept.\n *\n * @param input.concept - The concept being explained\n * @param input.explanation - A metaphor or detailed explanation (often using real-world comparisons)\n * @param input.therefore - Optional actionable instruction based on this understanding\n *\n * @example\n * // Gaming/Entertainment dataset\n * explain({\n * concept: \"daily active users to monthly active users ratio\",\n * explanation: \"like measuring how many club members visit daily vs just once a month - shows stickiness\",\n * therefore: \"Calculate as DAU / MAU, where higher ratio (closer to 1) means more engaged user base\"\n * })\n *\n * @example\n * // HR/Employee Management dataset\n * explain({\n * concept: \"time to fill\",\n * explanation: \"like measuring how long a house sits on the market - from posting job to accepting offer\",\n * therefore: \"Calculate as days between job_posted_date and offer_accepted_date, exclude cancelled requisitions\"\n * })\n *\n * @example\n * // Telecommunications dataset\n * explain({\n * concept: \"network congestion ratio\",\n * explanation: \"like rush hour traffic density - measures actual usage vs total capacity at peak times\",\n * therefore: \"Calculate as (peak_hour_bandwidth_used / total_bandwidth_capacity) during busiest hour of day\"\n * })\n */\nexport function explain(input: {\n concept: string;\n explanation: string;\n therefore?: string;\n}): Teachables {\n const { concept, explanation, therefore } = input;\n return {\n type: 'explain',\n encode: () => ({ type: 'explain', concept, explanation, therefore }),\n decode: () =>\n wrapBlock('explanation', [\n leaf('concept', concept),\n leaf('details', explanation),\n therefore ? leaf('therefore', therefore) : '',\n ]),\n };\n}\n\n/**\n * Teach the system through concrete examples of question \u2192 SQL pairs.\n *\n * Use this for few-shot learning - show the system exactly how to translate\n * specific types of questions into SQL queries. Great for establishing patterns\n * and handling domain-specific query structures.\n *\n * @param input.question - The natural language question or request\n * @param input.answer - The correct answer that responds to the question\n * @param input.note - Optional note or explanation about the example\n *\n * @example\n * // Energy/Utilities dataset\n * example({\n * question: \"show me peak demand hours for the last week\",\n * answer: \"SELECT DATE_TRUNC('hour', reading_timestamp) as hour, MAX(consumption_kwh) as peak_demand FROM meter_readings WHERE reading_timestamp >= CURRENT_DATE - INTERVAL '7 days' GROUP BY hour ORDER BY peak_demand DESC LIMIT 10\"\n * })\n *\n * @example\n * // Agriculture/Farm Management dataset\n * example({\n * question: \"what is the average yield per acre by crop type this season\",\n * answer: \"SELECT crop_type, AVG(harvest_quantity / field_acres) as yield_per_acre FROM harvests WHERE harvest_date >= '2024-01-01' GROUP BY crop_type ORDER BY yield_per_acre DESC\"\n * })\n *\n * @example\n * // Travel/Hospitality dataset\n * example({\n * question: \"show me hotel occupancy rate for this month\",\n * answer: \"SELECT hotel_name, (SUM(occupied_rooms) / SUM(total_rooms)) * 100 as occupancy_rate FROM daily_occupancy WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY hotel_id, hotel_name ORDER BY occupancy_rate DESC\",\n * note: \"Occupancy rate is a percentage - multiply by 100 for readable output\"\n * })\n */\nexport function example(input: {\n question: string;\n answer: string;\n note?: string;\n}): Teachables {\n const { question, answer, note } = input;\n return {\n type: 'example',\n encode: () => ({ type: 'example', question, answer, note }),\n decode: () =>\n wrapBlock('example', [\n leaf('question', question),\n leaf('answer', answer),\n note ? leaf('note', note) : '',\n ]),\n };\n}\n\n/**\n * Teach the system when and what to ask for clarification.\n *\n * Use this to handle ambiguous terms or situations where the system should\n * proactively ask the user for more information before generating a query.\n * Makes the system more conversational and precise.\n *\n * @param input.when - The condition or trigger that should prompt clarification\n * @param input.ask - The question to ask the user\n * @param input.reason - Why this clarification is necessary (helps system understand importance)\n *\n * @example\n * // Marketing/Advertising dataset\n * clarification({\n * when: \"user asks for 'conversion rate'\",\n * ask: \"Which conversion: click-to-lead, lead-to-opportunity, or opportunity-to-customer?\",\n * reason: \"Conversion rate means different things at each funnel stage - need to specify which metric\"\n * })\n *\n * @example\n * // Food Delivery dataset\n * clarification({\n * when: \"user asks about 'delivery time'\",\n * ask: \"Do you mean estimated time at order, actual delivery time, or time from kitchen to door?\",\n * reason: \"Multiple time metrics exist - estimated vs actual impacts customer satisfaction differently\"\n * })\n *\n * @example\n * // Fitness/Gym Management dataset\n * clarification({\n * when: \"user mentions 'active members'\",\n * ask: \"Do you mean paid memberships or members who actually visited in last 30 days?\",\n * reason: \"Many paid members don't use facilities - different metrics for revenue vs utilization\"\n * })\n */\nexport function clarification(input: {\n when: string;\n ask: string;\n reason: string;\n}): Teachables {\n const { when, ask, reason } = input;\n return {\n type: 'clarification',\n encode: () => ({ type: 'clarification', when, ask, reason }),\n decode: () =>\n wrapBlock('clarification', [\n leaf('when', when),\n leaf('ask', ask),\n leaf('reason', reason),\n ]),\n };\n}\n\n/**\n * Teach the system multi-step analytical processes that can't be solved with a single query.\n *\n * Use this for complex analytical tasks that require multiple CTEs, sequential logic,\n * or specific methodologies. Workflows teach the system HOW to approach a type of analysis.\n *\n * @param input.task - Name of the analytical task\n * @param input.steps - Sequential steps to execute (can include SQL snippets or descriptions)\n * @param input.triggers - Optional phrases that should activate this workflow\n * @param input.notes - Optional additional context, warnings, or guidance\n *\n * @example\n * // Insurance dataset\n * workflow({\n * task: \"Claims Loss Ratio Analysis\",\n * triggers: [\"loss ratio\", \"claims ratio\", \"underwriting performance\"],\n * steps: [\n * \"Calculate total claims paid for each policy period\",\n * \"Calculate total premiums earned for same period\",\n * \"Compute loss ratio as (claims_paid / premiums_earned) * 100\",\n * \"Segment by policy type, geography, and underwriter\",\n * \"Identify policies with loss ratio > 100% (losing money)\",\n * \"Calculate trend over time using rolling 12-month windows\"\n * ],\n * notes: \"Use incurred date for claims, not paid date. Exclude reinsurance recoveries from claims total.\"\n * })\n *\n * @example\n * // Media/Publishing dataset\n * workflow({\n * task: \"Content Performance Funnel\",\n * triggers: [\"content funnel\", \"engagement funnel\", \"content performance\"],\n * steps: [\n * \"Count total impressions (articles shown) per content piece\",\n * \"Count click-throughs (articles opened)\",\n * \"Count scroll depth > 50% (meaningful engagement)\",\n * \"Count shares, comments, or saves (viral actions)\",\n * \"Calculate conversion rate at each funnel stage\",\n * \"Identify top-performing content by final conversion rate\"\n * ],\n * notes: \"Requires multiple event types. Join events table multiple times or use conditional aggregation.\"\n * })\n *\n * @example\n * // Sports Analytics dataset\n * workflow({\n * task: \"Player Performance Rating Calculation\",\n * triggers: [\"player rating\", \"performance score\", \"player analytics\"],\n * steps: [\n * \"Aggregate per-game stats: points, assists, rebounds, turnovers\",\n * \"Calculate efficiency metrics: shooting percentage, plus/minus\",\n * \"Normalize each metric using z-scores vs league average\",\n * \"Apply position-specific weights to each metric\",\n * \"Combine weighted scores into overall performance rating (0-100)\",\n * \"Rank players within position group and overall\"\n * ],\n * notes: \"Requires league-wide statistics for normalization. Update weights each season based on game trends.\"\n * })\n */\nexport function workflow(input: {\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n}): Teachables {\n const { task, steps, triggers, notes } = input;\n return {\n type: 'workflow',\n encode: () => ({ type: 'workflow', task, steps, triggers, notes }),\n decode: () =>\n wrapBlock('workflow', [\n leaf('task', task),\n triggers?.length ? list('triggers', triggers, 'trigger') : '',\n list('steps', steps, 'step'),\n notes ? leaf('notes', notes) : '',\n ]),\n };\n}\n\n/**\n * Teach the system about data quirks, edge cases, or database-specific issues and their workarounds.\n *\n * Use this to document weird data patterns, database limitations, or special handling\n * required for specific scenarios. Helps the system navigate real-world messiness.\n *\n * @param input.issue - Description of the quirk, edge case, or problem\n * @param input.workaround - How to handle or work around this issue\n *\n * @example\n * // Government/Public Services dataset\n * quirk({\n * issue: \"Citizen IDs contain leading zeros but are stored as integers, losing the zeros\",\n * workaround: \"Always cast to VARCHAR and use LPAD(citizen_id::VARCHAR, 10, '0') to restore leading zeros\"\n * })\n *\n * @example\n * // Aviation dataset\n * quirk({\n * issue: \"Flight times crossing midnight show as negative duration (landing before takeoff)\",\n * workaround: \"Add 24 hours when calculated duration < 0: CASE WHEN duration < 0 THEN duration + INTERVAL '24 hours' ELSE duration END\"\n * })\n *\n * @example\n * // Automotive/Dealership dataset\n * quirk({\n * issue: \"VIN numbers with letter 'O' were incorrectly entered as zero '0' in legacy data\",\n * workaround: \"When searching by VIN, use REPLACE(vin, '0', 'O') or fuzzy matching to handle both cases\"\n * })\n */\nexport function quirk(input: {\n issue: string;\n workaround: string;\n}): Teachables {\n const { issue, workaround } = input;\n return {\n type: 'quirk',\n encode: () => ({ type: 'quirk', issue, workaround }),\n decode: () =>\n wrapBlock('quirk', [\n leaf('issue', issue),\n leaf('workaround', workaround),\n ]),\n };\n}\n\n/**\n * Teach the system SQL style preferences and coding standards for generated queries.\n *\n * Use this to enforce consistent SQL formatting, naming conventions, and best practices\n * specific to your team or organization. Improves readability and maintainability.\n *\n * @param input.prefer - Preferred SQL style or pattern\n * @param input.never - Optional anti-pattern to avoid\n * @param input.always - Optional rule that must always be followed\n *\n * @example\n * // Non-profit/Charity dataset\n * styleGuide({\n * prefer: \"Use donor-centric language in column aliases: 'donor_name' not 'customer_name'\",\n * never: \"Never expose internal donor IDs in external reports - use public gift IDs\",\n * always: \"Always include fiscal year in date-based aggregations (FY starts July 1)\"\n * })\n *\n * @example\n * // Legal/Law Firm dataset\n * styleGuide({\n * prefer: \"Use billable_hours with 2 decimal precision for accurate client billing\",\n * never: \"Never include attorney_rate in queries visible to paralegals - confidential data\",\n * always: \"Always filter by matter_status = 'open' unless specifically analyzing closed cases\"\n * })\n *\n * @example\n * // Inventory/Warehouse dataset\n * styleGuide({\n * prefer: \"Use location_id in joins rather than location_name (duplicates exist across warehouses)\",\n * never: \"Never aggregate inventory without grouping by warehouse_id first\",\n * always: \"Always use inventory_on_hand - inventory_reserved for available stock calculations\"\n * })\n */\nexport function styleGuide(input: {\n prefer: string;\n never?: string;\n always?: string;\n}): Teachables {\n const { prefer, never, always } = input;\n return {\n type: 'styleGuide',\n encode: () => ({ type: 'styleGuide', prefer, never, always }),\n decode: () =>\n wrapBlock('style_guide', [\n leaf('prefer', prefer),\n always ? leaf('always', always) : '',\n never ? leaf('never', never) : '',\n ]),\n };\n}\n\n/**\n * Teach the system by comparing related concepts through real-world analogies.\n *\n * Use this to teach relational understanding between two concepts by drawing comparisons\n * to familiar real-world scenarios. Helps the system understand WHY concepts differ and\n * when to use each one appropriately.\n *\n * @param input.concept - Array of two related concepts to compare\n * @param input.relationship - The comparison/analogy using real-world examples\n * @param input.insight - Optional key insight the analogy reveals\n * @param input.therefore - Optional actionable instruction based on this understanding\n * @param input.pitfall - Optional common mistake to avoid\n *\n * @example\n * // E-commerce dataset\n * analogy({\n * concept: [\"cart abandonment\", \"browse abandonment\"],\n * relationship: \"Cart abandonment is like leaving items at a checkout counter, browse abandonment is like window shopping without picking anything up\",\n * insight: \"Cart abandonment shows purchase intent (added to cart), browse abandonment shows only interest\",\n * therefore: \"Prioritize cart abandonment recovery campaigns - higher conversion potential than browse\",\n * pitfall: \"Don't combine both into generic 'abandonment rate' - they need different marketing strategies\"\n * })\n *\n * @example\n * // SaaS dataset\n * analogy({\n * concept: [\"logo churn\", \"revenue churn\"],\n * relationship: \"Logo churn is like counting how many customers left the store, revenue churn is how much money walked out\",\n * insight: \"Losing 10 small customers (high logo churn) might hurt less than losing 1 enterprise customer (high revenue churn)\",\n * therefore: \"Always report both metrics - logo churn for customer satisfaction, revenue churn for financial health\",\n * pitfall: \"Don't use logo churn to predict revenue impact - customer size distribution matters\"\n * })\n *\n * @example\n * // Healthcare dataset\n * analogy({\n * concept: [\"incident\", \"prevalence\"],\n * relationship: \"Incidence is like new house sales this month, prevalence is total houses currently occupied\",\n * insight: \"Incidence measures new cases over time, prevalence measures all existing cases at a point in time\",\n * therefore: \"For tracking disease outbreaks use incidence rate, for resource planning use prevalence\",\n * pitfall: \"Don't sum incidence rates across time periods - it's a rate not a count\"\n * })\n */\nexport function analogy(input: {\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n}): Teachables {\n const { concept, relationship, insight, therefore, pitfall } = input;\n return {\n type: 'analogy',\n encode: () => ({\n type: 'analogy',\n concept,\n relationship,\n insight,\n therefore,\n pitfall,\n }),\n decode: () =>\n wrapBlock('analogy', [\n list('concepts', concept, 'concept'),\n leaf('relationship', relationship),\n insight ? leaf('insight', insight) : '',\n therefore ? leaf('therefore', therefore) : '',\n pitfall ? leaf('pitfall', pitfall) : '',\n ]),\n };\n}\n\n/**\n * Map business terms directly to SQL expressions or fragments.\n *\n * Use this to teach the system how to CALCULATE or QUERY specific business concepts.\n * The system will substitute these SQL patterns when users mention the term.\n *\n * **Glossary vs Alias:**\n * - `alias` = user vocabulary \u2192 table/column name (\"the big table\" \u2192 \"orders table\")\n * - `glossary` = business term \u2192 SQL expression (\"revenue\" \u2192 \"SUM(orders.total_amount)\")\n *\n * In short: alias renames, glossary computes.\n *\n * @param entries - Record mapping business terms to their SQL expressions\n *\n * @example\n * glossary({\n * \"revenue\": \"SUM(orders.total_amount)\",\n * \"average order value\": \"AVG(orders.total_amount)\",\n * \"active user\": \"last_login > NOW() - INTERVAL '30 days'\",\n * \"churned\": \"status = 'churned'\",\n * \"power user\": \"order_count > 10\",\n * \"net revenue\": \"SUM(orders.total_amount) - SUM(refunds.amount)\",\n * })\n */\nexport function glossary(entries: Record<string, string>): Teachables {\n return {\n type: 'glossary',\n encode: () => ({ type: 'glossary', entries }),\n decode: () =>\n wrapBlock(\n 'glossary',\n Object.entries(entries).map(([term, sql]) =>\n wrapBlock('entry', [leaf('term', term), leaf('sql', sql)]),\n ),\n ),\n };\n}\n\n// =============================================================================\n// User-Specific Teachable Types\n// =============================================================================\n\n/**\n * Define the user's identity including name and/or role.\n *\n * Use this to capture who the user is and what lens they view data through.\n * Helps tailor explanations, terminology, and focus areas.\n *\n * @param input.name - The user's name (optional)\n * @param input.role - The user's role or position (optional)\n *\n * @example\n * identity({ name: \"John\", role: \"VP of Sales\" })\n * identity({ role: \"Data analyst in the marketing team\" })\n * identity({ name: \"Sarah\" })\n * identity({ role: \"Finance manager focused on cost optimization\" })\n */\nexport function identity(input: { name?: string; role?: string }): Teachables {\n const { name, role } = input;\n return {\n type: 'identity',\n encode: () => ({ type: 'identity', name, role }),\n decode: () =>\n wrapBlock('identity', [\n name ? leaf('name', name) : '',\n role ? leaf('role', role) : '',\n ]),\n };\n}\n\n/**\n * Define an AI persona with a name, role, and communication tone.\n *\n * Use this to customize the assistant's personality and how it communicates.\n * The persona influences the style and approach of responses.\n *\n * @param input.name - The persona's name\n * @param input.role - The persona's role or expertise\n * @param input.tone - The communication style (e.g., friendly, professional, concise)\n *\n * @example\n * persona({ name: \"DataBot\", role: \"SQL Expert\", tone: \"friendly and encouraging\" })\n * persona({ name: \"QueryMaster\", role: \"Database Analyst\", tone: \"professional and concise\" })\n * persona({ name: \"SQLHelper\", role: \"Data Assistant\", tone: \"casual and approachable\" })\n */\nexport function persona(input: {\n name: string;\n role: string;\n tone?: string;\n}): Teachables {\n const { name, role, tone } = input;\n return {\n type: 'persona',\n encode: () => ({ type: 'persona', name, role, tone: tone ?? '' }),\n decode: () =>\n wrapBlock('persona', [\n leaf('name', name),\n leaf('role', role),\n tone ? leaf('tone', tone) : '',\n ]),\n };\n}\n\n/**\n * Define user-specific term meanings and vocabulary.\n *\n * Use this when the user has their own definitions for terms that might\n * differ from standard or domain definitions. Like `term()` but personal.\n *\n * @param termName - The term the user uses\n * @param meaning - What the user means by this term\n *\n * @example\n * alias(\"revenue\", \"gross revenue before deductions, not net\")\n * alias(\"active users\", \"users who logged in within the last 30 days\")\n * alias(\"the big table\", \"the orders table\")\n * alias(\"Q4\", \"October through December, not fiscal Q4\")\n */\nexport function alias(termName: string, meaning: string): Teachables {\n return {\n type: 'alias',\n encode: () => ({ type: 'alias', term: termName, meaning }),\n decode: () =>\n wrapBlock('alias', [leaf('term', termName), leaf('meaning', meaning)]),\n };\n}\n\n/**\n * Define how the user prefers results presented.\n *\n * Use this to capture output formatting, style, and behavioral preferences\n * that should apply to all interactions with this user.\n *\n * @param aspect - What aspect of output this preference applies to\n * @param value - The user's preference\n *\n * @example\n * preference(\"date format\", \"YYYY-MM-DD\")\n * preference(\"output style\", \"tables over charts unless trend data\")\n * preference(\"detail level\", \"always show the SQL query in responses\")\n * preference(\"row limit\", \"default to 50 rows unless I ask for more\")\n * preference(\"explanation style\", \"brief and to the point\")\n */\nexport function preference(aspect: string, value: string): Teachables {\n return {\n type: 'preference',\n encode: () => ({ type: 'preference', aspect, value }),\n decode: () =>\n wrapBlock('preference', [leaf('aspect', aspect), leaf('value', value)]),\n };\n}\n\n/**\n * Define the user's current working focus or project.\n *\n * Use this to capture temporary context that helps inform defaults,\n * assumptions, and suggestions. Should be updated as focus changes.\n *\n * @param description - What the user is currently working on\n *\n * @example\n * context(\"Preparing Q4 board presentation\")\n * context(\"Investigating drop in signups last week\")\n * context(\"Working on EMEA regional analysis for strategy meeting\")\n * context(\"Debugging discrepancy in revenue numbers\")\n */\nexport function context(description: string): Teachables {\n return {\n type: 'context',\n encode: () => ({ type: 'context', description }),\n decode: () => leaf('context', description),\n };\n}\n\n/**\n * Record a correction the user made to previous understanding.\n *\n * Use this when the user corrects a misunderstanding about data, columns,\n * or business logic. Prevents repeating the same mistake.\n *\n * @param subject - What was misunderstood\n * @param clarification - The correct understanding\n *\n * @example\n * correction(\"status column\", \"1 = active, 0 = inactive, not boolean true/false\")\n * correction(\"orders table\", \"Use orders_v2, not the deprecated legacy_orders table\")\n * correction(\"date field\", \"order_date is when order was placed, ship_date is when shipped\")\n * correction(\"revenue calculation\", \"Must exclude refunds and chargebacks\")\n */\nexport function correction(subject: string, clarification: string): Teachables {\n return {\n type: 'correction',\n encode: () => ({ type: 'correction', subject, clarification }),\n decode: () =>\n wrapBlock('correction', [\n leaf('subject', subject),\n leaf('clarification', clarification),\n ]),\n };\n}\n\nexport function teachable(\n tag: string,\n ...teachables: Teachables[]\n): Teachables {\n return {\n type: 'user_profile',\n encode: () => teachables[0]?.encode() ?? ({ type: 'context', description: '' }),\n decode: () => toInstructions(tag, ...teachables),\n };\n}\n\nexport function toInstructions(\n tag: string,\n ...teachables: Teachables[]\n): string {\n if (!teachables.length) {\n return '';\n }\n\n const grouped = new Map<Teachables['type'], Teachables[]>();\n for (const teachable of teachables) {\n const existing = grouped.get(teachable.type) ?? [];\n existing.push(teachable);\n grouped.set(teachable.type, existing);\n }\n\n const definedTypes = new Set(SECTION_ORDER.map((s) => s.type));\n\n const sections = SECTION_ORDER.map(({ type, tag }) => {\n const items = grouped.get(type);\n if (!items?.length) {\n return '';\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (!renderedItems.length) {\n return '';\n }\n return `<${tag}>\\n${renderedItems}\\n</${tag}>`;\n }).filter((section): section is string => Boolean(section));\n\n // Render types not defined in SECTION_ORDER at the end\n for (const [type, items] of grouped) {\n if (definedTypes.has(type)) {\n continue;\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (renderedItems.length) {\n sections.push(renderedItems);\n }\n }\n\n if (!sections.length) {\n return '';\n }\n\n const content = indentBlock(sections.join('\\n'), 2);\n return `<${tag}>\\n${content}\\n</${tag}>`;\n}\n\nconst SECTION_ORDER: Array<{ type: Teachables['type']; tag: string }> = [\n // User context (render first - most important for personalization)\n { type: 'identity', tag: 'identity' },\n { type: 'persona', tag: 'persona' },\n { type: 'context', tag: 'user_context' },\n { type: 'preference', tag: 'user_preferences' },\n { type: 'alias', tag: 'user_vocabulary' },\n { type: 'correction', tag: 'user_corrections' },\n // Domain knowledge\n { type: 'guardrail', tag: 'guardrails' },\n { type: 'styleGuide', tag: 'style_guides' },\n { type: 'hint', tag: 'hints' },\n { type: 'clarification', tag: 'clarifications' },\n { type: 'workflow', tag: 'workflows' },\n { type: 'quirk', tag: 'quirks' },\n { type: 'term', tag: 'terminology' },\n { type: 'explain', tag: 'explanations' },\n { type: 'analogy', tag: 'analogies' },\n { type: 'glossary', tag: 'glossary' },\n { type: 'example', tag: 'examples' },\n];\n\nexport function toTeachables(generated: GeneratedTeachable[]): Teachables[] {\n return generated.map((item) => {\n switch (item.type) {\n case 'persona':\n return persona({ name: item.name, role: item.role, tone: item.tone });\n case 'term':\n return term(item.name, item.definition);\n case 'hint':\n return hint(item.text);\n case 'guardrail':\n return guardrail({\n rule: item.rule,\n reason: item.reason,\n action: item.action,\n });\n case 'explain':\n return explain({\n concept: item.concept,\n explanation: item.explanation,\n therefore: item.therefore,\n });\n case 'example':\n return example({\n question: item.question,\n answer: item.answer,\n note: item.note,\n });\n case 'clarification':\n return clarification({\n when: item.when,\n ask: item.ask,\n reason: item.reason,\n });\n case 'workflow':\n return workflow({\n task: item.task,\n steps: item.steps,\n triggers: item.triggers,\n notes: item.notes,\n });\n case 'quirk':\n return quirk({\n issue: item.issue,\n workaround: item.workaround,\n });\n case 'styleGuide':\n return styleGuide({\n prefer: item.prefer,\n never: item.never,\n always: item.always,\n });\n case 'analogy':\n return analogy({\n concept: item.concept,\n relationship: item.relationship,\n insight: item.insight,\n therefore: item.therefore,\n pitfall: item.pitfall,\n });\n case 'glossary':\n return glossary(item.entries);\n // User-specific teachable types\n case 'identity':\n return identity({ name: item.name, role: item.role });\n case 'alias':\n return alias(item.term, item.meaning);\n case 'preference':\n return preference(item.aspect, item.value);\n case 'context':\n return context(item.description);\n case 'correction':\n return correction(item.subject, item.clarification);\n }\n });\n}\n\n/**\n * Convert Teachables back to GeneratedTeachable format for storage.\n *\n * @param teachables - Array of Teachables to convert\n * @returns Array of GeneratedTeachable objects suitable for storage\n *\n * @example\n * const teachings = [term('NPL', 'non-performing loan'), hint('Always filter by status')];\n * const forStorage = fromTeachables(teachings);\n * // [{ type: 'term', name: 'NPL', definition: 'non-performing loan' }, { type: 'hint', text: 'Always filter by status' }]\n */\nexport function fromTeachables(teachables: Teachables[]): GeneratedTeachable[] {\n return teachables.map((t) => t.encode());\n}\n\n/**\n * Default export containing all system teachable factory functions.\n * Excludes user-specific teachables (identity, alias, preference, context, correction).\n */\nexport default {\n persona,\n term,\n hint,\n guardrail,\n explain,\n example,\n clarification,\n workflow,\n quirk,\n styleGuide,\n analogy,\n glossary,\n teachable,\n};\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport z from 'zod';\n\nimport {\n type AgentModel,\n agent,\n generate,\n toOutput,\n user,\n} from '@deepagents/agent';\n\nimport { type ExtractedPair, PairProducer } from '../types.ts';\nimport type { Persona } from './persona-generator.ts';\nimport { styleInstructions } from './styles.ts';\n\nexport interface BreadthEvolverOptions {\n count: number;\n persona?: Persona;\n model?: AgentModel;\n concurrency?: number;\n}\n\ntype ParaphraserState = {\n question: string;\n sql: string;\n count: number;\n persona?: Persona;\n};\n\ntype ParaphraserOutput = {\n paraphrases: string[];\n};\n\nconst paraphraserAgent = agent<ParaphraserOutput, ParaphraserState>({\n name: 'question_paraphraser',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.9, topP: 0.95, frequencyPenalty: 0.2 },\n }),\n }),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.object({\n paraphrases: z\n .array(\n z.string().describe('A paraphrased version of the original question'),\n )\n .min(1)\n .describe(\n 'List of paraphrased questions that would produce the same SQL',\n ),\n }),\n prompt: (state) => {\n const personaInstruction = state?.persona\n ? dedent`\n <persona role=\"${state.persona.role}\">\n ${state.persona.perspective}\n\n Paraphrase the question as this persona would naturally ask it.\n Use their vocabulary, priorities, and framing style.\n </persona>\n `\n : '';\n\n const styleInstruction =\n state?.persona?.styles && state.persona.styles.length > 0\n ? dedent`\n <communication_styles>\n Generate paraphrases using these communication styles: ${state.persona.styles.join(', ')}\n\n Style definitions:\n ${state.persona.styles.map((s) => `- ${s}: ${styleInstructions[s]}`).join('\\n')}\n\n Distribute paraphrases across these styles for variety.\n </communication_styles>\n `\n : '';\n\n return dedent`\n <identity>\n You are a linguistic expert specializing in paraphrasing database questions.\n Your task is to generate alternative phrasings of questions that preserve\n the exact same semantic meaning - they must all produce the identical SQL query.\n </identity>\n\n <original_question>\n ${state?.question}\n </original_question>\n\n <reference_sql>\n ${state?.sql}\n (This SQL shows what the question is really asking - all paraphrases must ask for exactly this)\n </reference_sql>\n\n ${personaInstruction}\n\n ${styleInstruction}\n\n <task>\n Generate exactly ${state?.count} paraphrased versions of the original question.\n\n Requirements:\n 1. Each paraphrase must be semantically equivalent - it should produce the EXACT same SQL\n 2. Vary the sentence structure, word choice, and phrasing style\n 3. Use natural language without SQL keywords (SELECT, WHERE, JOIN, etc.)\n 4. Keep paraphrases realistic - how actual users would ask\n 5. Do not add or remove any conditions, filters, or requirements from the original\n ${state?.persona?.styles?.length ? '6. Apply the specified communication styles to create diverse phrasings' : ''}\n </task>\n\n <guardrails>\n - NEVER change what data is being requested\n - NEVER add filters, aggregations, or conditions not in the original\n - NEVER remove any specificity from the original question\n - All paraphrases must be answerable by the exact same SQL query\n </guardrails>\n `;\n },\n});\n/**\n * BreadthEvolver - Generate paraphrased variations of questions (in-breadth evolution).\n *\n * Takes existing question/SQL pairs and generates variations of the questions\n * while keeping the SQL identical. This creates training data diversity where\n * many different phrasings map to the same SQL query.\n *\n * Based on Microsoft's Evol-Instruct methodology for in-breadth evolution.\n */\nexport class BreadthEvolver extends PairProducer {\n #limit: ReturnType<typeof pLimit>;\n\n /**\n * @param source - Source pairs or producer to evolve\n * @param options - Evolution options including count, persona, and concurrency\n */\n constructor(\n private source: PairProducer | ExtractedPair[],\n private options: BreadthEvolverOptions,\n ) {\n super();\n this.#limit = pLimit(this.options.concurrency ?? 4);\n }\n\n /**\n * Batch pairs within each chunk for concurrent processing.\n * Uses pLimit for concurrency control, yields results per pair after chunk completes.\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n for await (const chunk of this.from(this.source)) {\n const tasks = chunk.map((pair) =>\n this.#limit(async () => {\n const { paraphrases } = await toOutput(\n generate(\n paraphraserAgent.clone({ model: this.options.model }),\n [\n user(\n `Paraphrase this question ${this.options.count} times: \"${pair.question}\"`,\n ),\n ],\n {\n question: pair.question,\n sql: pair.sql,\n count: this.options.count,\n persona: this.options.persona,\n },\n ),\n );\n\n return paraphrases.map((paraphrase) => ({\n question: paraphrase,\n sql: pair.sql,\n context: pair.context,\n success: pair.success,\n }));\n }),\n );\n\n const results = await Promise.all(tasks);\n yield results.flat();\n }\n }\n}\n", "/**\n * Natural language styles for text-to-SQL question generation.\n * Based on OmniSQL paper (March 2025): https://arxiv.org/html/2503.02240\n */\n\nexport const ALL_STYLES = [\n 'formal', // Professional business language\n 'colloquial', // Casual everyday speech\n 'imperative', // Commands: \"Show me...\", \"Get...\"\n 'interrogative', // Questions: \"What is...\", \"How many...\"\n 'descriptive', // Verbose, detailed\n 'concise', // Brief, minimal\n 'vague', // Ambiguous, hedging\n 'metaphorical', // Figurative language\n 'conversational', // Chat-like\n] as const;\n\nexport type NLStyle = (typeof ALL_STYLES)[number];\n\nexport const styleInstructions: Record<NLStyle, string> = {\n formal: 'Use professional business language, complete sentences, no slang',\n colloquial: 'Use casual everyday speech, contractions, informal tone',\n imperative: 'Phrase as commands: \"Show me...\", \"Get...\", \"List...\"',\n interrogative: 'Phrase as questions: \"What is...\", \"How many...\", \"Which...\"',\n descriptive: 'Use detailed, verbose phrasing with extra context',\n concise: 'Use minimal words, telegram-style brevity',\n vague: 'Be intentionally ambiguous, use hedging language',\n metaphorical: 'Use figurative language, analogies, creative phrasing',\n conversational: 'Chat-like tone, as if talking to a colleague',\n};\n", "import { groq } from '@ai-sdk/groq';\nimport {\n NoObjectGeneratedError,\n NoOutputGeneratedError,\n defaultSettingsMiddleware,\n wrapLanguageModel,\n} from 'ai';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { UnanswerableSQLError, toSql } from '../../agents/sql.agent.ts';\nimport { type ExtractedPair, PairProducer } from '../types.ts';\n\n/**\n * Techniques for evolving questions into more complex versions.\n * Each technique transforms the question in a specific way.\n */\nexport type DepthTechnique =\n | 'add-aggregation'\n | 'add-filter'\n | 'add-join'\n | 'add-reasoning'\n | 'hypothetical';\n\nconst techniqueInstructions: Record<DepthTechnique, string> = {\n 'add-aggregation': dedent`\n Add aggregation requirements to the question.\n Transform it to require GROUP BY, COUNT, SUM, AVG, MIN, MAX, or similar operations.\n Examples:\n - \"Show orders\" \u2192 \"Show total order count by customer\"\n - \"List products\" \u2192 \"What is the average price per category?\"\n - \"Get employees\" \u2192 \"How many employees are in each department?\"\n `,\n 'add-filter': dedent`\n Add filtering conditions to the question.\n Transform it to require WHERE clauses with specific conditions.\n Examples:\n - \"Show orders\" \u2192 \"Show orders from the last 30 days\"\n - \"List customers\" \u2192 \"List customers who have made more than 5 purchases\"\n - \"Get products\" \u2192 \"Get products with price above $100\"\n `,\n 'add-join': dedent`\n Add requirements that need data from related tables.\n Transform it to require JOIN operations between multiple tables.\n Examples:\n - \"Show orders\" \u2192 \"Show orders with customer names and addresses\"\n - \"List products\" \u2192 \"List products with their supplier information\"\n - \"Get employees\" \u2192 \"Get employees with their department and manager names\"\n `,\n 'add-reasoning': dedent`\n Add multi-step reasoning requirements.\n Transform it to require logical deduction, comparisons, or derived calculations.\n Examples:\n - \"Show orders\" \u2192 \"Which customers have orders above the average order value?\"\n - \"List products\" \u2192 \"Which products are underperforming compared to their category average?\"\n - \"Get revenue\" \u2192 \"Which month had the highest growth compared to the previous month?\"\n `,\n hypothetical: dedent`\n Add a hypothetical or speculative scenario.\n Transform it to require applying calculations or projections.\n Examples:\n - \"Show revenue\" \u2192 \"What would revenue be if we increased all prices by 15%?\"\n - \"List inventory\" \u2192 \"How many days of stock remain at current sales rate?\"\n - \"Get costs\" \u2192 \"What would be the impact of a 10% discount on profit margins?\"\n `,\n};\n\nexport interface DepthEvolverOptions {\n techniques?: DepthTechnique[];\n count?: number;\n model?: AgentModel;\n concurrency?: number;\n}\n\ntype EvolverState = {\n question: string;\n sql: string;\n schema: string;\n technique: DepthTechnique;\n techniqueInstruction: string;\n};\n\ntype EvolverOutput = {\n evolvedQuestion: string;\n};\n\nconst questionEvolverAgent = agent<EvolverOutput, EvolverState>({\n name: 'question_evolver',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.7, topP: 0.95 },\n }),\n }),\n output: z.object({\n evolvedQuestion: z\n .string()\n .describe('The evolved, more complex version of the original question'),\n }),\n prompt: (state) => {\n return dedent`\n <identity>\n You are an expert at evolving simple database questions into more complex ones.\n Your task is to take a basic question and transform it into a more sophisticated\n version that requires advanced SQL techniques to answer.\n </identity>\n\n <original_question>\n ${state?.question}\n </original_question>\n\n <original_sql>\n ${state?.sql}\n (This shows what the original question required)\n </original_sql>\n\n <database_schema>\n ${state?.schema}\n </database_schema>\n\n <technique name=\"${state?.technique}\">\n ${state?.techniqueInstruction}\n </technique>\n\n <task>\n Evolve the original question using the \"${state?.technique}\" technique.\n\n Requirements:\n 1. The evolved question must be MORE COMPLEX than the original\n 2. Apply the specific technique described above\n 3. The evolved question must be answerable using the provided schema\n 4. Use natural language - no SQL keywords\n 5. Keep the question realistic and practical\n 6. The evolved question should build upon the original topic/domain\n </task>\n\n <guardrails>\n - The evolved question MUST require more complex SQL than the original\n - Do not ask for data that doesn't exist in the schema\n - Keep the question grounded in the same domain as the original\n - Make sure the question is clear and unambiguous\n </guardrails>\n `;\n },\n});\n\nconst ALL_TECHNIQUES: DepthTechnique[] = [\n 'add-aggregation',\n 'add-filter',\n 'add-join',\n 'add-reasoning',\n 'hypothetical',\n];\n/**\n * DepthEvolver - Evolve questions into more complex versions (in-depth evolution).\n *\n * Takes existing question/SQL pairs and evolves them into more complex versions\n * using specific techniques. Both the question AND SQL change - the evolved\n * question requires a more sophisticated query to answer.\n *\n * Based on Microsoft's Evol-Instruct methodology for in-depth evolution.\n */\nexport class DepthEvolver extends PairProducer {\n #limit: ReturnType<typeof pLimit>;\n\n /**\n * @param source - Source pairs or producer to evolve\n * @param adapter - Database adapter for SQL generation\n * @param options - Evolution options including techniques, count, and concurrency\n */\n constructor(\n private source: PairProducer | ExtractedPair[],\n private adapter: Adapter,\n private options?: DepthEvolverOptions,\n ) {\n super();\n this.#limit = pLimit(this.options?.concurrency ?? 4);\n }\n\n /**\n * Yields evolved pairs as each completes (streaming pattern).\n * Removes batch barrier - no longer waits for all evolutions before yielding.\n */\n async *produce(): AsyncGenerator<ExtractedPair[]> {\n const introspection = await this.adapter.introspect();\n const count = this.options?.count ?? 1;\n const techniques = this.options?.techniques ?? ALL_TECHNIQUES;\n\n let pairIndex = 0;\n for await (const chunk of this.from(this.source)) {\n for (const pair of chunk) {\n const tasks = Array.from({ length: count }, (_, i) => {\n const technique = this.options?.techniques\n ? techniques[i % techniques.length]\n : techniques[(pairIndex * count + i) % techniques.length];\n return this.#limit(() =>\n this.#processTask(pair, technique, introspection),\n );\n });\n\n const results = await Promise.all(tasks);\n yield results;\n pairIndex++;\n }\n }\n }\n\n async #processTask(\n pair: ExtractedPair,\n technique: DepthTechnique,\n introspection: string,\n ) {\n const { experimental_output } = await withRetry(() =>\n generate(\n questionEvolverAgent.clone({\n model: this.options?.model,\n }),\n [user(`Evolve this question using \"${technique}\": \"${pair.question}\"`)],\n {\n question: pair.question,\n sql: pair.sql,\n schema: introspection,\n technique,\n techniqueInstruction: techniqueInstructions[technique],\n },\n ),\n );\n\n const evolvedQuestion = experimental_output.evolvedQuestion;\n try {\n const sqlResult = await toSql({\n input: evolvedQuestion,\n adapter: this.adapter,\n introspection,\n instructions: [],\n model: this.options?.model,\n });\n\n return {\n question: evolvedQuestion,\n sql: sqlResult.sql,\n context: pair.context,\n success: !sqlResult.errors || sqlResult.errors.length === 0,\n };\n } catch (error) {\n if (UnanswerableSQLError.isInstance(error)) {\n return {\n question: evolvedQuestion,\n sql: '',\n context: pair.context,\n success: false,\n errors: [\n `Cannot answer the question ${evolvedQuestion} because ${error.message}`,\n ],\n };\n }\n throw error;\n }\n }\n}\n\nasync function withRetry<T>(computation: () => Promise<T>): Promise<T> {\n return pRetry(computation, {\n retries: 3,\n shouldRetry: (context) => {\n console.log({\n NoObjectGeneratedError: NoObjectGeneratedError.isInstance(\n context.error,\n ),\n NoOutputGeneratedError: NoOutputGeneratedError.isInstance(\n context.error,\n ),\n });\n return (\n NoObjectGeneratedError.isInstance(context.error) ||\n NoOutputGeneratedError.isInstance(context.error)\n );\n },\n onFailedAttempt(context) {\n console.log(\n `Attempt ${context.attemptNumber} failed. There are ${context.retriesLeft} retries left.`,\n );\n console.dir(context.error, { depth: null });\n },\n });\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { ALL_STYLES, type NLStyle } from './styles.ts';\n\nexport interface Persona {\n role: string;\n perspective: string;\n styles: NLStyle[];\n}\n\nexport interface PersonaGeneratorOptions {\n count?: number;\n model?: AgentModel;\n}\n\ntype PersonaGeneratorState = {\n schema: string;\n count: number;\n};\n\ntype PersonaGeneratorOutput = {\n personas: Persona[];\n};\n\nconst personaGeneratorAgent = agent<\n PersonaGeneratorOutput,\n PersonaGeneratorState\n>({\n name: 'persona_generator',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.8, topP: 0.95, presencePenalty: 0.2 },\n }),\n }),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.object({\n personas: z\n .array(\n z.object({\n role: z.string().describe('The job title or role of this persona'),\n perspective: z\n .string()\n .describe(\n 'Rich description of what this persona cares about when querying the database',\n ),\n styles: z\n .array(z.enum(ALL_STYLES))\n .min(1)\n .max(3)\n .describe(\n 'Typical communication styles for this persona (1-3 styles)',\n ),\n }),\n )\n .min(1)\n .describe('List of personas who would query this database'),\n }),\n prompt: (state) => {\n return dedent`\n <identity>\n You are an expert at understanding database schemas and inferring who would use them.\n Your task is to analyze a database schema and generate realistic personas representing\n the different types of users who would query this database.\n </identity>\n\n <database_schema>\n ${state?.schema}\n </database_schema>\n\n <task>\n Generate exactly ${state?.count} distinct personas who would query this database.\n\n For each persona, provide:\n 1. **role**: Their job title or role (e.g., \"Financial Analyst\", \"Customer Support Rep\")\n 2. **perspective**: A rich description of what they care about, including:\n - What questions they typically ask\n - What metrics/data points matter to them\n - How they prefer data formatted or presented\n - Their priorities (speed vs accuracy, detail vs summary)\n - Domain-specific concerns relevant to their role\n 3. **styles**: 1-3 communication styles typical for this persona. Choose from:\n - formal: Professional business language, complete sentences\n - colloquial: Casual everyday speech, contractions\n - imperative: Commands like \"Show me...\", \"Get...\", \"List...\"\n - interrogative: Questions like \"What is...\", \"How many...\"\n - descriptive: Verbose, detailed phrasing\n - concise: Brief, minimal words\n - vague: Ambiguous, hedging language\n - metaphorical: Figurative language, analogies\n - conversational: Chat-like, casual tone\n\n Requirements:\n - Personas should be realistic for the given schema\n - Each persona should have distinct concerns and priorities\n - Perspectives should be detailed enough to guide question paraphrasing\n - Cover different levels of technical expertise (some technical, some business-focused)\n - Styles should match how this persona would naturally communicate\n </task>\n\n <example>\n For an e-commerce schema with orders, customers, products tables:\n\n {\n \"role\": \"Customer Support Rep\",\n \"perspective\": \"As customer support, I care about:\\\\n- Quick lookups by order ID or customer email\\\\n- Order status and shipping tracking\\\\n- Return and refund history\\\\n- Customer contact details and order history\\\\n- I need fast answers, not complex analysis\",\n \"styles\": [\"imperative\", \"concise\"]\n }\n\n {\n \"role\": \"Inventory Manager\",\n \"perspective\": \"As inventory manager, I care about:\\\\n- Current stock levels and reorder points\\\\n- Product availability across warehouses\\\\n- Slow-moving inventory identification\\\\n- Supplier lead times and pending orders\\\\n- I need accurate counts, often aggregated by location\",\n \"styles\": [\"formal\", \"interrogative\"]\n }\n </example>\n\n <guardrails>\n - Only generate personas relevant to the actual schema provided\n - Do not invent tables or data that don't exist in the schema\n - Ensure perspectives are specific to the domain, not generic\n </guardrails>\n `;\n },\n});\n/**\n * PersonaGenerator - Generate relevant personas from database schema.\n *\n * Analyzes the schema to infer who would query this database and what\n * they care about. Generated personas can be used with BreadthEvolver\n * to create diverse question paraphrases from different perspectives.\n */\nexport class PersonaGenerator {\n /**\n * @param adapter - Database adapter for schema introspection\n * @param options - Generation options including count and model\n */\n constructor(\n private adapter: Adapter,\n private options?: PersonaGeneratorOptions,\n ) {}\n\n /**\n * Generates personas by analyzing the database schema to infer user types.\n * @returns Array of personas with roles and perspectives\n */\n async generate(): Promise<Persona[]> {\n const schema = await this.adapter.introspect();\n const count = this.options?.count ?? 5;\n\n const { experimental_output } = await generate(\n personaGeneratorAgent.clone({\n model: this.options?.model,\n }),\n [user(`Generate ${count} personas for this database schema.`)],\n {\n schema,\n count,\n },\n );\n\n return experimental_output.personas;\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport {\n type GeneratedTeachable,\n type Teachables,\n toTeachables,\n} from '../teach/teachables.ts';\n\nconst outputSchema = z.object({\n terms: z\n .array(z.object({ name: z.string(), definition: z.string() }))\n .optional()\n .describe('Domain terminology definitions'),\n hints: z\n .array(z.object({ text: z.string() }))\n .optional()\n .describe('Helpful hints for SQL generation'),\n guardrails: z\n .array(\n z.object({\n rule: z.string(),\n reason: z.string().optional(),\n action: z.string().optional(),\n }),\n )\n .optional()\n .describe('Safety rules and constraints'),\n explains: z\n .array(\n z.object({\n concept: z.string(),\n explanation: z.string(),\n therefore: z.string().optional(),\n }),\n )\n .optional()\n .describe('Concept explanations'),\n examples: z\n .array(\n z.object({\n question: z.string(),\n answer: z.string(),\n note: z.string().optional(),\n }),\n )\n .optional()\n .describe('Example question-answer pairs'),\n clarifications: z\n .array(z.object({ when: z.string(), ask: z.string(), reason: z.string() }))\n .optional()\n .describe('When to ask for clarification'),\n workflows: z\n .array(\n z.object({\n task: z.string(),\n steps: z.array(z.string()).min(1),\n triggers: z.array(z.string()).optional(),\n notes: z.string().optional(),\n }),\n )\n .optional()\n .describe('Multi-step workflows'),\n quirks: z\n .array(z.object({ issue: z.string(), workaround: z.string() }))\n .optional()\n .describe('Known issues and workarounds'),\n styleGuides: z\n .array(\n z.object({\n prefer: z.string(),\n never: z.string().optional(),\n always: z.string().optional(),\n }),\n )\n .optional()\n .describe('SQL style preferences'),\n analogies: z\n .array(\n z.object({\n concept: z.array(z.string()).min(2),\n relationship: z.string(),\n insight: z.string().optional(),\n therefore: z.string().optional(),\n pitfall: z.string().optional(),\n }),\n )\n .optional()\n .describe('Concept analogies'),\n});\n\ntype TeachablesOutput = z.infer<typeof outputSchema>;\n\nconst teachablesAuthorAgent = agent<\n TeachablesOutput,\n { schema: string; context?: string }\n>({\n name: 'teachables-author',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.4, topP: 0.95 },\n }),\n }),\n output: outputSchema,\n prompt: (state) => dedent`\n <identity>\n You design \"teachables\" for a Text2SQL system. Teachables become structured XML instructions.\n Choose only high-impact items that improve accuracy, safety, or clarity for this database.\n </identity>\n\n <database_schema>\n ${state?.schema}\n </database_schema>\n\n ${state?.context ? `<additional_context>${state.context}</additional_context>` : ''}\n\n <output_structure>\n Output a JSON object with these optional arrays (include only relevant ones):\n - terms: [{ name: string, definition: string }] - Domain terminology\n - hints: [{ text: string }] - Helpful SQL generation hints\n - guardrails: [{ rule: string, reason?: string, action?: string }] - Safety constraints\n - explains: [{ concept: string, explanation: string, therefore?: string }] - Concept explanations\n - examples: [{ question: string, answer: string, note?: string }] - Q&A examples\n - clarifications: [{ when: string, ask: string, reason: string }] - Clarification triggers\n - workflows: [{ task: string, steps: string[], triggers?: string[], notes?: string }] - Multi-step tasks\n - quirks: [{ issue: string, workaround: string }] - Known issues\n - styleGuides: [{ prefer: string, never?: string, always?: string }] - SQL style rules\n - analogies: [{ concept: string[], relationship: string, insight?: string, therefore?: string, pitfall?: string }]\n </output_structure>\n\n <instructions>\n 1. Analyze the schema to infer domain, relationships, and sensitive columns.\n 2. Generate 3-10 teachables total across all categories, prioritizing:\n - guardrails for PII columns (email, ssn, phone, etc)\n - hints for status/enum columns\n - clarifications for ambiguous terms\n 3. Ground everything in the schema - do not invent tables/columns.\n 4. Only include categories that are relevant to this schema.\n </instructions>\n `,\n});\n\nexport interface GenerateToTeachingsOptions {\n model?: AgentModel;\n}\n\nexport async function toTeachings(\n input: { schema: string; context?: string },\n options?: GenerateToTeachingsOptions,\n): Promise<Teachables[]> {\n const { experimental_output: result } = await generate(\n teachablesAuthorAgent.clone({ model: options?.model }),\n [\n user(\n `Analyze this database schema and generate teachings that will help an AI generate accurate SQL queries.`,\n ),\n ],\n input,\n );\n\n const generated: GeneratedTeachable[] = [\n ...(result.terms?.map((t) => ({ type: 'term' as const, ...t })) ?? []),\n ...(result.hints?.map((h) => ({ type: 'hint' as const, ...h })) ?? []),\n ...(result.guardrails?.map((g) => ({ type: 'guardrail' as const, ...g })) ??\n []),\n ...(result.explains?.map((e) => ({ type: 'explain' as const, ...e })) ??\n []),\n ...(result.examples?.map((e) => ({ type: 'example' as const, ...e })) ??\n []),\n ...(result.clarifications?.map((c) => ({\n type: 'clarification' as const,\n ...c,\n })) ?? []),\n ...(result.workflows?.map((w) => ({ type: 'workflow' as const, ...w })) ??\n []),\n ...(result.quirks?.map((q) => ({ type: 'quirk' as const, ...q })) ?? []),\n ...(result.styleGuides?.map((s) => ({\n type: 'styleGuide' as const,\n ...s,\n })) ?? []),\n ...(result.analogies?.map((a) => ({ type: 'analogy' as const, ...a })) ??\n []),\n ];\n\n return toTeachables(generated);\n}\n", "import type { AgentModel } from '@deepagents/agent';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { toTeachings } from '../../agents/teachables.agent.ts';\nimport type { Teachables } from '../../teach/teachables.ts';\n\nexport interface TeachingsGeneratorOptions {\n context?: string;\n model?: AgentModel;\n}\n/**\n * TeachingsGenerator - Generate domain-specific teachings from database schema.\n *\n * Analyzes the schema to generate teachings that improve SQL generation accuracy.\n * Teachings include domain vocabulary, SQL patterns, guardrails, and examples\n * that help the SQL generator understand the domain and produce semantically\n * correct queries.\n */\nexport class TeachingsGenerator {\n /**\n * @param adapter - Database adapter for schema introspection\n * @param options - Generation options including context and model\n */\n constructor(\n private adapter: Adapter,\n private options?: TeachingsGeneratorOptions,\n ) {}\n\n /**\n * Generates domain-specific teachings by analyzing the database schema.\n * Retries on transient generation errors up to maxRetries attempts.\n * @param maxRetries - Maximum retry attempts for transient failures\n * @returns Array of teachings including vocabulary, patterns, and guardrails\n */\n async generate(maxRetries = 3): Promise<Teachables[]> {\n const schema = await this.adapter.introspect();\n\n let lastError: Error | undefined;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await toTeachings(\n {\n schema,\n context: this.options?.context,\n },\n { model: this.options?.model },\n );\n } catch (error) {\n lastError = error as Error;\n const isRetryable =\n lastError.message.includes('parse') ||\n lastError.message.includes('schema') ||\n lastError.message.includes('No object generated') ||\n lastError.name.includes('AI_');\n if (!isRetryable) {\n throw lastError;\n }\n }\n }\n\n throw lastError;\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAcO,IAAe,eAAf,MAAqE;AAAA,EAMhE,KAAK,UAAyD;AACtE,WAAO,MAAM,QAAQ,QAAQ,KACxB,iBAAiB,OAAwB;AACxC,YAAM;AAAA,IACR,GAAG,QAAQ,IACX,SAAS,QAAQ;AAAA,EACvB;AAAA,EAEO,UAAwB;AAC7B,WAAO,QAAQ,IAAI;AAAA,EACrB;AACF;AAKA,eAAsB,QACpB,UACc;AACd,QAAM,QAAa,CAAC;AACpB,mBAAiB,SAAS,SAAS,QAAQ,GAAG;AAC5C,UAAM,KAAK,GAAG,KAAK;AAAA,EACrB;AACA,SAAO;AACT;;;AC/BO,IAAM,mBAAN,cAA+B,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAKjD,YACU,UACA,UAAmC,CAAC,GAC5C;AACA,UAAM;AAHE;AACA;AAAA,EAGV;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,UAA2C;AAChD,qBAAiB,SAAS,KAAK,SAAS,QAAQ,GAAG;AACjD,YAAM,WAAW,MAAM,OAAO,CAAC,SAAS;AACtC,YAAI,KAAK,QAAQ,gBAAgB,SAAS,CAAC,KAAK,SAAS;AACvD,iBAAO;AAAA,QACT;AAEA,YAAI,KAAK,QAAQ,QAAQ,QAAQ;AAC/B,gBAAM,WAAW,KAAK,IAAI,YAAY;AACtC,gBAAM,WAAW,KAAK,QAAQ,OAAO;AAAA,YAAK,CAAC,MACzC,SAAS,SAAS,EAAE,YAAY,CAAC;AAAA,UACnC;AACA,cAAI,CAAC,SAAU,QAAO;AAAA,QACxB;AAEA,YAAI,KAAK,QAAQ,UAAU,CAAC,KAAK,QAAQ,OAAO,IAAI,GAAG;AACrD,iBAAO;AAAA,QACT;AAEA,eAAO;AAAA,MACT,CAAC;A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N,MAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9B,YACU,SACA,SACR;AAFQ;AACA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQH,MAAM,SAAS,aAAa,GAA0B;AACpD,UAAM,SAAS,MAAM,KAAK,QAAQ,WAAW;AAE7C,QAAI;AACJ,aAAS,UAAU,GAAG,UAAU,YAAY,WAAW;AACrD,UAAI;AACF,eAAO,MAAM;AAAA,UACX;AAAA,YACE;AAAA,YACA,SAAS,KAAK,SAAS;AAAA,UACzB;AAAA,UACA,EAAE,OAAO,KAAK,SAAS,MAAM;AAAA,QAC/B;AAAA,MACF,SAAS,OAAO;AACd,oBAAY;AACZ,cAAM,cACJ,UAAU,QAAQ,SAAS,OAAO,KAClC,UAAU,QAAQ,SAAS,QAAQ,KACnC,UAAU,QAAQ,SAAS,qBAAqB,KAChD,UAAU,KAAK,SAAS,KAAK;AAC/B,YAAI,CAAC,aAAa;AAChB,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM;AAAA,EACR;AACF;",
|
|
6
|
+
"names": ["getToolOrDynamicToolName", "isToolOrDynamicToolUIPart", "isToolOrDynamicToolUIPart", "getToolOrDynamicToolName", "groq", "dedent", "z", "agent", "generate", "user", "agent", "groq", "z", "dedent", "generate", "user", "groq", "dedent", "z", "agent", "generate", "user", "agent", "groq", "z", "dedent", "generate", "user", "generate", "user", "generate", "user", "groq", "dedent", "z", "agent", "generate", "user", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "z", "agent", "generate", "user", "term", "clarification", "tag", "agent", "groq", "z", "wrapLanguageModel", "defaultSettingsMiddleware", "user", "generate", "context", "persona", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "pLimit", "z", "agent", "generate", "toOutput", "user", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "z", "dedent", "pLimit", "toOutput", "generate", "user", "groq", "NoObjectGeneratedError", "NoOutputGeneratedError", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "pLimit", "pRetry", "z", "agent", "generate", "user", "dedent", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "z", "pLimit", "withRetry", "generate", "user", "pRetry", "context", "NoObjectGeneratedError", "NoOutputGeneratedError", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "z", "agent", "generate", "user", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "z", "dedent", "generate", "user", "groq", "defaultSettingsMiddleware", "wrapLanguageModel", "dedent", "z", "agent", "generate", "user", "z", "agent", "wrapLanguageModel", "groq", "defaultSettingsMiddleware", "dedent", "generate", "user"]
|
|
7
7
|
}
|