@deepagents/text2sql 0.20.0 → 0.23.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.
Files changed (39) hide show
  1. package/dist/index.js +655 -173
  2. package/dist/index.js.map +3 -3
  3. package/dist/lib/adapters/bigquery/bigquery-fk.d.ts +25 -0
  4. package/dist/lib/adapters/bigquery/bigquery-fk.d.ts.map +1 -0
  5. package/dist/lib/adapters/bigquery/constraint.bigquery.grounding.d.ts +3 -1
  6. package/dist/lib/adapters/bigquery/constraint.bigquery.grounding.d.ts.map +1 -1
  7. package/dist/lib/adapters/bigquery/index.d.ts.map +1 -1
  8. package/dist/lib/adapters/bigquery/index.js +356 -201
  9. package/dist/lib/adapters/bigquery/index.js.map +4 -4
  10. package/dist/lib/adapters/bigquery/indexes.bigquery.grounding.d.ts +6 -7
  11. package/dist/lib/adapters/bigquery/indexes.bigquery.grounding.d.ts.map +1 -1
  12. package/dist/lib/adapters/bigquery/info.bigquery.grounding.d.ts.map +1 -1
  13. package/dist/lib/adapters/bigquery/row-count.bigquery.grounding.d.ts +5 -7
  14. package/dist/lib/adapters/bigquery/row-count.bigquery.grounding.d.ts.map +1 -1
  15. package/dist/lib/adapters/bigquery/table.bigquery.grounding.d.ts +2 -0
  16. package/dist/lib/adapters/bigquery/table.bigquery.grounding.d.ts.map +1 -1
  17. package/dist/lib/adapters/bigquery/view.bigquery.grounding.d.ts +2 -2
  18. package/dist/lib/adapters/bigquery/view.bigquery.grounding.d.ts.map +1 -1
  19. package/dist/lib/adapters/groundings/context.d.ts +2 -0
  20. package/dist/lib/adapters/groundings/context.d.ts.map +1 -1
  21. package/dist/lib/adapters/groundings/index.js +2 -1
  22. package/dist/lib/adapters/groundings/index.js.map +2 -2
  23. package/dist/lib/adapters/mysql/index.js +2 -1
  24. package/dist/lib/adapters/mysql/index.js.map +2 -2
  25. package/dist/lib/adapters/postgres/index.js +2 -1
  26. package/dist/lib/adapters/postgres/index.js.map +2 -2
  27. package/dist/lib/adapters/spreadsheet/index.js +2 -1
  28. package/dist/lib/adapters/spreadsheet/index.js.map +2 -2
  29. package/dist/lib/adapters/sqlite/index.js +2 -1
  30. package/dist/lib/adapters/sqlite/index.js.map +2 -2
  31. package/dist/lib/adapters/sqlserver/index.js +2 -1
  32. package/dist/lib/adapters/sqlserver/index.js.map +2 -2
  33. package/dist/lib/agents/result-tools.d.ts.map +1 -1
  34. package/dist/lib/agents/sql.agent.d.ts.map +1 -1
  35. package/dist/lib/sql.d.ts +3 -3
  36. package/dist/lib/sql.d.ts.map +1 -1
  37. package/dist/lib/synthesis/index.js +220 -109
  38. package/dist/lib/synthesis/index.js.map +3 -3
  39. package/package.json +8 -7
@@ -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/exceptions.ts", "../../../src/lib/agents/question.agent.ts", "../../../src/lib/agents/sql.agent.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/synthesis/synthesizers/teachings-generator.ts", "../../../src/lib/agents/teachables.agent.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 #messages: UIMessage[];\n #options: MessageExtractorOptions;\n\n /**\n * @param messages - Chat history to extract pairs from\n * @param options - Extraction configuration\n */\n constructor(messages: UIMessage[], options: MessageExtractorOptions = {}) {\n super();\n this.#messages = messages;\n this.#options = options;\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 {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\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}\n\nconst contextResolverSchema = z.object({\n question: z\n .string()\n .describe(\n 'A standalone natural language question that the SQL query answers',\n ),\n});\n\n/**\n * Resolves a SQL query with conversation context into a standalone question.\n */\nexport async function resolveContext(params: {\n conversation: string;\n sql: string;\n introspection?: string;\n}): Promise<{ question: string }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `context-resolver-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'context_resolver',\n role: 'You are an expert at understanding conversational context and generating clear, standalone questions from multi-turn conversations.',\n objective:\n 'Transform context-dependent messages into standalone questions that fully capture user intent',\n }),\n ...(params.introspection\n ? [fragment('database_schema', params.introspection)]\n : []),\n fragment('conversation', params.conversation),\n fragment('sql', params.sql),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n fragment(\n 'examples',\n dedent`\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 `,\n ),\n user('Generate a standalone question for this SQL query.'),\n );\n\n const resolverOutput = structuredOutput({\n model: groq('openai/gpt-oss-20b'),\n context,\n schema: contextResolverSchema,\n });\n\n return resolverOutput.generate();\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 protected messages: UIMessage[];\n protected adapter: Adapter;\n protected options: BaseContextualExtractorOptions;\n\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: BaseContextualExtractorOptions = {},\n ) {\n super();\n this.messages = messages;\n this.adapter = adapter;\n this.options = options;\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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 output = await resolveContext({\n conversation: formatConversation(item.conversationContext),\n sql: item.sql,\n introspection,\n });\n\n yield [\n {\n question: output.question,\n sql: item.sql,\n context: item.conversationContext,\n success: item.success,\n },\n ];\n }\n }\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 {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\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 outputSchema = z.object({\n question: z\n .string()\n .describe('A natural language question that the SQL query answers'),\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.#adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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 context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `sql-to-question-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'sql_to_question',\n role: 'You are an expert at understanding SQL queries and generating clear, natural language questions that describe what the query retrieves.',\n objective:\n 'Generate clear, natural language questions that describe what SQL queries retrieve',\n }),\n fragment('database_schema', introspection),\n fragment('sql', sql),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n fragment(\n 'examples',\n dedent`\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 `,\n ),\n user('Generate a natural language question for this SQL query.'),\n );\n\n const sqlToQuestionOutput = structuredOutput({\n model: groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n const output = await sqlToQuestionOutput.generate();\n\n yield [\n {\n question: 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 {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n formatConversation,\n resolveContext,\n} from './base-contextual-extractor.ts';\n\nexport type SegmentedContextExtractorOptions = BaseContextualExtractorOptions;\n\nconst topicChangeSchema = 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\n/**\n * Detects if a new message represents a topic change from the prior context.\n */\nasync function detectTopicChange(params: {\n context: string;\n newMessage: string;\n}): Promise<{ isTopicChange: boolean; reason: string }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `topic-change-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'topic_change_detector',\n role: 'You are an expert at understanding conversational flow and detecting topic changes.',\n objective: 'Detect significant topic changes in database conversations',\n }),\n fragment('conversation_context', params.context || '(no prior context)'),\n fragment('new_message', params.newMessage),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n fragment(\n 'examples',\n dedent`\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 `,\n ),\n user('Determine if this is a topic change.'),\n );\n\n const topicOutput = structuredOutput({\n model: groq('openai/gpt-oss-20b'),\n context,\n schema: topicChangeSchema,\n });\n\n return topicOutput.generate();\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 detectTopicChange({\n context: formatConversation(contextSnapshot),\n newMessage: text,\n });\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 * 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 output = await resolveContext({\n conversation: formatConversation([...contextSnapshot, `User: ${text}`]),\n sql: '', // No SQL yet, just resolving the question\n });\n\n return output.question;\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport type { ExtractedPair } from '../types.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n formatConversation,\n resolveContext,\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 extractor.toPairs(); // 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 output = await resolveContext({\n conversation: formatConversation(last.conversationContext),\n sql: last.sql,\n introspection,\n });\n\n yield [\n {\n question: 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';\nimport type { ContextFragment } from '@deepagents/context';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { UnanswerableSQLError } from '../../agents/exceptions.ts';\nimport {\n type QuestionComplexity,\n generateQuestions,\n} from '../../agents/question.agent.ts';\nimport { type ToSqlResult, toSql } from '../../agents/sql.agent.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?: ContextFragment[];\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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: string, // TODO: This was Awaited<ReturnType<Adapter['introspect']>> - needs update when synthesis uses fragments\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 // TODO: Update to use schemaFragments instead of introspection string\n return await toSql({\n input: question,\n adapter: this.adapter,\n fragments: 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", "const sqlValidationMarker = Symbol('SQLValidationError');\nconst unanswerableSqlMarker = Symbol('UnanswerableSQLError');\n\n/**\n * Error thrown when SQL validation fails.\n */\nexport class SQLValidationError extends Error {\n [sqlValidationMarker]: true;\n\n constructor(message: string) {\n super(message);\n this.name = 'SQLValidationError';\n this[sqlValidationMarker] = true;\n }\n\n static isInstance(error: unknown): error is SQLValidationError {\n return (\n error instanceof SQLValidationError && error[sqlValidationMarker] === true\n );\n }\n}\n\n/**\n * Error thrown when the question cannot be answered with the given schema.\n */\nexport class UnanswerableSQLError extends Error {\n [unanswerableSqlMarker]: true;\n\n constructor(message: string) {\n super(message);\n this.name = 'UnanswerableSQLError';\n this[unanswerableSqlMarker] = true;\n }\n\n static isInstance(error: unknown): error is UnanswerableSQLError {\n return (\n error instanceof UnanswerableSQLError &&\n error[unanswerableSqlMarker] === true\n );\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n guardrail,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nexport type QuestionComplexity =\n | 'simple'\n | 'moderate'\n | 'complex'\n | 'high complex';\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\nconst outputSchema = 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\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 context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `question-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'question_generator',\n role: 'You are a synthetic data generator specializing in creating realistic natural language questions that users might ask about a database.',\n objective:\n 'Generate diverse, realistic natural language questions that match the specified complexity level',\n }),\n fragment('database_schema', introspection || ''),\n fragment(\n 'complexity',\n { level: complexity },\n complexityInstructions[complexity],\n ),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n guardrail({\n rule: 'Questions MUST ONLY reference tables and columns that exist in the schema above',\n }),\n guardrail({\n rule: 'Before generating each question, verify that ALL entities (tables, columns, relationships) you reference are explicitly listed in the schema',\n }),\n guardrail({\n rule: 'DO NOT invent or assume tables/columns that are not explicitly shown in the schema',\n }),\n guardrail({\n rule: 'Use natural language without SQL keywords like SELECT, WHERE, etc.',\n }),\n guardrail({\n rule: 'All questions must match the specified complexity level',\n }),\n user(\n prompt ??\n `Generate ${count} questions at ${complexity} complexity given db schema.`,\n ),\n );\n\n const questionOutput = structuredOutput({\n model: model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n return questionOutput.generate();\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 dedent from 'dedent';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n type ContextFragment,\n InMemoryContextStore,\n fragment,\n persona,\n policy,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport { SQLValidationError, UnanswerableSQLError } from './exceptions.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 /** Context fragments (schema + instructions/teachings) */\n fragments: ContextFragment[];\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/** Temperature progression for retries: deterministic first, then increasingly exploratory */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\nconst SQL_AGENT_ROLE = 'Expert SQL query generator.';\nconst SQL_AGENT_OBJECTIVE = 'Generate precise SQL grounded in provided schema.';\n\nconst SQL_AGENT_POLICIES: ContextFragment[] = [\n fragment(\n 'schema_mapping',\n policy({\n rule: 'Translate natural language into precise SQL grounded in available schema entities.',\n }),\n // policy({\n // rule: 'Before returning an error, perform a schema-grounded self-check: identify core intent, draft best-effort SQL, then verify it uses only existing tables/columns.',\n // }),\n // policy({\n // rule: 'Return unanswerable only if that self-check confirms no valid SQL can express the required intent without inventing schema elements.',\n // }),\n // policy({\n // rule: 'Prefer a best-effort valid SQL query when entities can be reasonably inferred from table or column names.',\n // }),\n // policy({\n // rule: 'Use lexical normalization (singular/plural, paraphrases, role synonyms, and minor wording differences) to align question terms with schema names.',\n // }),\n // policy({\n // rule: 'Decompose noun phrases into core entity and qualifiers, and map the core entity first.',\n // }),\n // policy({\n // rule: 'Do not require every descriptive word to map to a separate schema field when the core entity match is unambiguous.',\n // }),\n // policy({\n // rule: 'For phrases like \"X of Y\", treat Y as contextual (non-blocking) when Y has no mapped schema field and the question does not ask to filter/group/select by Y explicitly.',\n // }),\n // policy({\n // rule: 'Treat unmatched qualifiers as blockers only when they are restrictive constraints (specific values, comparisons, or conditions that change row eligibility).',\n // }),\n // hint('Preserve schema spelling exactly, including typos in column names.'),\n ),\n // fragment(\n // 'unanswerable_gate',\n // workflow({\n // task: 'Unanswerable decision',\n // steps: [\n // 'Identify the core intent (metric/projection and required filters).',\n // 'Attempt schema-grounded mapping for the core intent before considering error.',\n // 'If a valid SELECT can answer the core intent without inventing schema entities, return SQL.',\n // 'Return unanswerable only when required information cannot be mapped to any available table or column.',\n // ],\n // }),\n // policy({\n // rule: 'Do not reject a question as unanswerable when requested information can be derived by filtering, joining, grouping, counting, set operations, or sorting on available columns.',\n // }),\n // ),\n // fragment(\n // 'query_shape_preferences',\n // hint(\n // 'Prefer explicit INNER JOINs over LEFT JOINs unless the question requires unmatched rows.',\n // ),\n // hint(\n // 'Prefer direct joins over dropping join constraints or using weaker alternatives.',\n // ),\n // hint('Use DISTINCT only when uniqueness is explicitly requested.'),\n // hint(\n // 'For superlatives over grouped entities (most/least/highest/lowest by group), prefer GROUP BY with ORDER BY aggregate and LIMIT 1.',\n // ),\n // hint(\n // 'For average/count conditions per entity, prefer GROUP BY with HAVING aggregate predicates over row-level WHERE predicates.',\n // ),\n // hint(\n // 'For \"both\" conditions across two criteria, prefer INTERSECT when selecting shared values.',\n // ),\n // hint(\n // 'For \"A or B\" retrieval across criteria, prefer UNION when combining two qualifying sets.',\n // ),\n // hint(\n // 'For \"never\" constraints against related records, prefer NOT IN or EXCEPT against the disqualifying set.',\n // ),\n // hint(\n // 'Use equality predicates for exact values unless the question asks for pattern matching.',\n // ),\n // hint(\n // 'Keep numeric literals unquoted when they are purely numeric tokens in the question.',\n // ),\n // ),\n // fragment(\n // 'sql_minimality',\n // guardrail({\n // rule: 'Never hallucinate tables or columns.',\n // reason: 'Schema fidelity is required.',\n // action: 'Use only available schema entities.',\n // }),\n // guardrail({\n // rule: 'Prefer the minimal query over transformed expressions.',\n // reason:\n // 'Unnecessary transformations reduce correctness and add avoidable complexity.',\n // action:\n // 'Do not add date parsing, substring extraction, derived projections, or extra selected columns unless explicitly requested or required by schema mismatch.',\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 async function toSql(options: ToSqlOptions): Promise<ToSqlResult> {\n const { maxRetries = 3 } = options;\n\n return withRetry(\n async (attemptNumber, errors, attempts) => {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `sql-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'Freya',\n role: SQL_AGENT_ROLE,\n objective: SQL_AGENT_OBJECTIVE,\n // role: `You are a data science expert that provides well-reasoned and detailed responses.`,\n // objective: `Your task is to understand the schema and generate a valid SQL query to answer the question. You first think about the reasoning process as an internal monologue and then provide the user with the answer.`,\n }),\n ...SQL_AGENT_POLICIES,\n ...options.fragments,\n );\n\n // Add user message(s)\n if (errors.length) {\n const lastError = errors.at(-1);\n context.set(\n user(dedent`\n Answer the following question with the SQL code. Use the piece of evidence and base your answer on the database schema.\nGiven the question, the evidence and the database schema, return the SQL script that addresses the question.\n\nQuestion: ${options.input}\n`),\n UnanswerableSQLError.isInstance(lastError)\n ? user(\n `<retry_instruction>Your previous response marked the task as unanswerable. Re-evaluate using best-effort schema mapping. If the core intent is answerable with existing tables/columns, return SQL. Return error only when required core intent cannot be mapped without inventing schema elements.</retry_instruction>`,\n )\n : user(\n `<validation_error>Your previous SQL query had the following error: ${lastError?.message}. Please fix the query.</validation_error>`,\n ),\n );\n } else {\n context.set(\n user(dedent`\n Answer the following question with the SQL code. Use the piece of evidence and base your answer on the database schema.\nGiven the question, the evidence and the database schema, return the SQL script that addresses the question.\n\nQuestion: ${options.input}\n`),\n );\n }\n\n // Create structured output with schema\n const temperature =\n RETRY_TEMPERATURES[attemptNumber - 1] ??\n RETRY_TEMPERATURES[RETRY_TEMPERATURES.length - 1];\n const baseModel = options.model ?? groq('openai/gpt-oss-20b');\n const model = wrapLanguageModel({\n model: baseModel,\n middleware: defaultSettingsMiddleware({ settings: { temperature } }),\n });\n // console.log(await context.render(new XmlRenderer()));\n const sqlOutput = structuredOutput({\n model: model,\n context,\n schema: z.object({\n result: z.union([\n z.object({\n sql: z\n .string()\n .describe('The SQL query that answers the question'),\n reasoning: z\n .string()\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 }),\n });\n\n const { result: output } = await sqlOutput.generate();\n\n const finalizeSql = async (rawSql: string): Promise<ToSqlResult> => {\n const sql = options.adapter.format(extractSql(rawSql));\n\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\n // Handle error responses (question is unanswerable with given schema)\n if ('error' in output) {\n context.set(\n user(\n '<best_effort_fallback>Do not return unanswerable. Produce the best valid SQL query that answers the core intent using only available schema entities.</best_effort_fallback>',\n ),\n );\n const forcedSqlOutput = structuredOutput({\n model,\n context,\n schema: z.object({\n sql: z\n .string()\n .describe(\n 'Best-effort SQL query that answers the core intent using only available schema entities.',\n ),\n reasoning: z\n .string()\n .describe('Reasoning steps for best-effort schema mapping.'),\n }),\n });\n\n try {\n const forced = await forcedSqlOutput.generate();\n return await finalizeSql(forced.sql);\n } catch (error) {\n if (\n SQLValidationError.isInstance(error) ||\n APICallError.isInstance(error) ||\n JSONParseError.isInstance(error) ||\n TypeValidationError.isInstance(error) ||\n NoObjectGeneratedError.isInstance(error) ||\n NoOutputGeneratedError.isInstance(error) ||\n NoContentGeneratedError.isInstance(error)\n ) {\n throw error;\n }\n throw new UnanswerableSQLError(output.error);\n }\n }\n\n return await finalizeSql(output.sql);\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\nfunction isModelUnavailableError(error: unknown): boolean {\n if (!APICallError.isInstance(error)) {\n return false;\n }\n\n const message = error.message.toLowerCase();\n const responseBody = (error.responseBody ?? '').toLowerCase();\n const is404ModelError =\n error.statusCode === 404 &&\n (message.includes('model') || responseBody.includes('model_not_found'));\n const errorCode =\n typeof error.data === 'object' &&\n error.data !== null &&\n 'error' in error.data &&\n typeof error.data.error === 'object' &&\n error.data.error !== null &&\n 'code' in error.data.error &&\n typeof error.data.error.code === 'string'\n ? error.data.error.code.toLowerCase()\n : undefined;\n\n return (\n is404ModelError ||\n errorCode === 'model_not_found' ||\n responseBody.includes('\"code\":\"model_not_found\"') ||\n (message.includes('model') &&\n message.includes('does not exist or you do not have access to it'))\n );\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 // Retry one time when the model marks query as unanswerable to recover from false positives.\n if (UnanswerableSQLError.isInstance(context.error)) {\n return false;\n // return context.attemptNumber === 0;\n }\n // Don't retry if the selected model is unavailable\n if (isModelUnavailableError(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 // 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", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n guardrail,\n persona as personaFragment,\n structuredOutput,\n user,\n} from '@deepagents/context';\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\nconst paraphraserOutputSchema = z.object({\n paraphrases: z\n .array(\n z.string().describe('A paraphrased version of the original question'),\n )\n .min(1)\n .describe('List of paraphrased questions that would produce the same SQL'),\n});\n\n/**\n * Generates paraphrased versions of a question while preserving SQL equivalence.\n */\nasync function paraphraseQuestion(params: {\n question: string;\n sql: string;\n count: number;\n persona?: Persona;\n model?: AgentModel;\n}): Promise<{ paraphrases: string[] }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `paraphraser-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n const personaInstruction = params.persona\n ? dedent`\n <persona role=\"${params.persona.role}\">\n ${params.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 params.persona?.styles && params.persona.styles.length > 0\n ? dedent`\n <communication_styles>\n Generate paraphrases using these communication styles: ${params.persona.styles.join(', ')}\n\n Style definitions:\n ${params.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 context.set(\n personaFragment({\n name: 'question_paraphraser',\n role: 'You are a linguistic expert specializing in paraphrasing database questions. Your task is to generate alternative phrasings of questions that preserve the exact same semantic meaning - they must all produce the identical SQL query.',\n objective:\n 'Generate paraphrased versions of questions that preserve exact semantic meaning and produce identical SQL',\n }),\n fragment('original_question', params.question),\n fragment(\n 'reference_sql',\n params.sql,\n 'This SQL shows what the question is really asking - all paraphrases must ask for exactly this',\n ),\n ...(personaInstruction ? [fragment('persona', personaInstruction)] : []),\n ...(styleInstruction\n ? [fragment('communication_styles', styleInstruction)]\n : []),\n fragment(\n 'task',\n dedent`\n Generate exactly ${params.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 ${params.persona?.styles?.length ? '6. Apply the specified communication styles to create diverse phrasings' : ''}\n `,\n ),\n guardrail({ rule: 'NEVER change what data is being requested' }),\n guardrail({\n rule: 'NEVER add filters, aggregations, or conditions not in the original',\n }),\n guardrail({\n rule: 'NEVER remove any specificity from the original question',\n }),\n guardrail({\n rule: 'All paraphrases must be answerable by the exact same SQL query',\n }),\n user(\n `Paraphrase this question ${params.count} times: \"${params.question}\"`,\n ),\n );\n\n const paraphraserOutput = structuredOutput({\n model: params.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: paraphraserOutputSchema,\n });\n\n return paraphraserOutput.generate();\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 result = await paraphraseQuestion({\n question: pair.question,\n sql: pair.sql,\n count: this.options.count,\n persona: this.options.persona,\n model: this.options.model,\n });\n\n return result.paraphrases.map((paraphrase: string) => ({\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 { NoObjectGeneratedError, NoOutputGeneratedError } from 'ai';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n guardrail,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { UnanswerableSQLError } from '../../agents/exceptions.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\nconst evolverOutputSchema = z.object({\n evolvedQuestion: z\n .string()\n .describe('The evolved, more complex version of the original question'),\n});\n\n/**\n * Evolves a simple question into a more complex version using a specific technique.\n */\nasync function evolveQuestion(params: {\n question: string;\n sql: string;\n schema: string;\n technique: DepthTechnique;\n techniqueInstruction: string;\n model?: AgentModel;\n}): Promise<{ evolvedQuestion: string }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `evolver-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'question_evolver',\n role: 'You are an expert at evolving simple database questions into more complex ones. Your task is to take a basic question and transform it into a more sophisticated version that requires advanced SQL techniques to answer.',\n objective:\n 'Transform simple questions into complex versions requiring advanced SQL techniques',\n }),\n fragment('original_question', params.question),\n fragment(\n 'original_sql',\n params.sql,\n '(This shows what the original question required)',\n ),\n fragment('database_schema', params.schema),\n fragment(\n 'technique',\n { name: params.technique },\n params.techniqueInstruction,\n ),\n fragment(\n 'task',\n dedent`\n Evolve the original question using the \"${params.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 `,\n ),\n guardrail({\n rule: 'The evolved question MUST require more complex SQL than the original',\n }),\n guardrail({\n rule: 'Do not ask for data that does not exist in the schema',\n }),\n guardrail({\n rule: 'Keep the question grounded in the same domain as the original',\n }),\n guardrail({ rule: 'Make sure the question is clear and unambiguous' }),\n user(\n `Evolve this question using \"${params.technique}\": \"${params.question}\"`,\n ),\n );\n\n const evolverOutput = structuredOutput({\n model: params.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: evolverOutputSchema,\n });\n\n return evolverOutput.generate();\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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 output = await withRetry(() =>\n evolveQuestion({\n question: pair.question,\n sql: pair.sql,\n schema: introspection,\n technique,\n techniqueInstruction: techniqueInstructions[technique],\n model: this.options?.model,\n }),\n );\n\n const evolvedQuestion = output.evolvedQuestion;\n try {\n // TODO: Update to use schemaFragments instead of introspection string\n const sqlResult = await toSql({\n input: evolvedQuestion,\n adapter: this.adapter,\n fragments: [],\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 dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n type ContextFragment,\n InMemoryContextStore,\n XmlRenderer,\n fragment,\n guardrail,\n persona as personaFragment,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\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\nconst outputSchema = 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\n/**\n * Generate personas by analyzing database schema.\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 *\n * @param schemaFragments - Schema fragments from adapter.introspect()\n * @param options - Generation options including count and model\n * @returns Array of personas with roles and perspectives\n */\nexport async function generatePersonas(\n schemaFragments: ContextFragment[],\n options?: PersonaGeneratorOptions,\n): Promise<Persona[]> {\n const schema = new XmlRenderer().render(schemaFragments);\n const count = options?.count ?? 5;\n\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `persona-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n personaFragment({\n name: 'persona_generator',\n role: 'You are an expert at understanding database schemas and inferring who would use them.',\n objective:\n 'Generate realistic personas representing users who would query this database',\n }),\n fragment('database_schema', schema),\n fragment(\n 'task',\n dedent`\n Analyze the database schema and generate realistic personas representing\n the different types of users 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 `,\n ),\n fragment(\n 'example',\n dedent`\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 `,\n ),\n guardrail({\n rule: 'Only generate personas relevant to the actual schema provided',\n }),\n guardrail({\n rule: 'Do not invent tables or data that do not exist in the schema',\n }),\n guardrail({\n rule: 'Ensure perspectives are specific to the domain, not generic',\n }),\n user(\n `Generate exactly ${count} distinct personas who would query this database.`,\n ),\n );\n\n const personaOutput = structuredOutput({\n model: options?.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n const output = await personaOutput.generate();\n return output.personas;\n}\n", "import type { AgentModel } from '@deepagents/agent';\nimport { type ContextFragment, XmlRenderer } from '@deepagents/context';\n\nimport { toTeachings } from '../../agents/teachables.agent.ts';\n\nexport interface TeachingsGeneratorOptions {\n context?: string;\n model?: AgentModel;\n maxRetries?: number;\n}\n\n/**\n * Generate domain-specific teachings from database schema.\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 *\n * @param schemaFragments - Schema fragments from adapter.introspect()\n * @param options - Generation options including context, model, and maxRetries\n * @returns Array of teachings including vocabulary, patterns, and guardrails\n */\nexport async function generateTeachings(\n schemaFragments: ContextFragment[],\n options?: TeachingsGeneratorOptions,\n): Promise<ContextFragment[]> {\n const schema = new XmlRenderer().render(schemaFragments);\n const maxRetries = options?.maxRetries ?? 3;\n\n let lastError: Error | undefined;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await toTeachings(\n { schema, context: options?.context },\n { model: 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", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n type ContextFragment,\n InMemoryContextStore,\n analogy,\n clarification,\n example,\n explain,\n fragment,\n guardrail,\n hint,\n persona,\n quirk,\n structuredOutput,\n styleGuide,\n term,\n user,\n workflow,\n} from '@deepagents/context';\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 concepts: 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\nexport interface GenerateToTeachingsOptions {\n model?: AgentModel;\n}\n\nexport async function toTeachings(\n input: { schema: string; context?: string },\n options?: GenerateToTeachingsOptions,\n): Promise<ContextFragment[]> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `teachables-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'teachables-author',\n role: 'You design \"fragments\" for a Text2SQL system. Fragments become structured XML instructions.',\n objective:\n 'Choose only high-impact items that improve accuracy, safety, or clarity for this database',\n }),\n fragment('database_schema', input.schema),\n ...(input.context ? [fragment('additional_context', input.context)] : []),\n fragment(\n 'output_structure',\n dedent`\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: [{ concepts: string[], relationship: string, insight?: string, therefore?: string, pitfall?: string }]\n `,\n ),\n fragment(\n 'task',\n dedent`\n 1. Analyze the schema to infer domain, relationships, and sensitive columns.\n 2. Generate 3-10 fragments 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 `,\n ),\n user(\n `Analyze this database schema and generate fragments that will help an AI generate accurate SQL queries.`,\n ),\n );\n\n const teachablesOutput = structuredOutput({\n model: options?.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n const result = await teachablesOutput.generate();\n\n const fragments: ContextFragment[] = [];\n\n // Convert generated output to ContextFragments\n result.terms?.forEach((t) => fragments.push(term(t.name, t.definition)));\n result.hints?.forEach((h) => fragments.push(hint(h.text)));\n result.guardrails?.forEach((g) =>\n fragments.push(\n guardrail({ rule: g.rule, reason: g.reason, action: g.action }),\n ),\n );\n result.explains?.forEach((e) =>\n fragments.push(\n explain({\n concept: e.concept,\n explanation: e.explanation,\n therefore: e.therefore,\n }),\n ),\n );\n result.examples?.forEach((e) =>\n fragments.push(\n example({ question: e.question, answer: e.answer, note: e.note }),\n ),\n );\n result.clarifications?.forEach((c) =>\n fragments.push(\n clarification({ when: c.when, ask: c.ask, reason: c.reason }),\n ),\n );\n result.workflows?.forEach((w) =>\n fragments.push(\n workflow({\n task: w.task,\n steps: w.steps,\n triggers: w.triggers,\n notes: w.notes,\n }),\n ),\n );\n result.quirks?.forEach((q) =>\n fragments.push(quirk({ issue: q.issue, workaround: q.workaround })),\n );\n result.styleGuides?.forEach((s) =>\n fragments.push(\n styleGuide({ prefer: s.prefer, never: s.never, always: s.always }),\n ),\n );\n result.analogies?.forEach((a) =>\n fragments.push(\n analogy({\n concepts: a.concepts,\n relationship: a.relationship,\n insight: a.insight,\n therefore: a.therefore,\n pitfall: a.pitfall,\n }),\n ),\n );\n\n return fragments;\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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AK,MAAM,EAAE,OAAO,EAAE,OAAO,YAAY,EAAE,WAAW,CAAC,CAAC;AAAA,EACpE;AACA,SAAO,aAAa;AAAA,IAAQ,CAAC,MAC3B,UAAU;AAAA,MACR,WAAW,EAAE,QAAQ,EAAE,QAAQ,OAAO,EAAE,OAAO,QAAQ,EAAE,OAAO,CAAC;AAAA,IACnE;AAAA,EACF;AACA,SAAO,WAAW;AAAA,IAAQ,CAAC,MACzB,UAAU;AAAA,MACR,QAAQ;AAAA,QACN,UAAU,EAAE;AAAA,QACZ,cAAc,EAAE;AAAA,QAChB,SAAS,EAAE;AAAA,QACX,WAAW,EAAE;AAAA,QACb,SAAS,EAAE;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;;;ADnNA,eAAsB,kBACpB,iBACA,SAC4B;AAC5B,QAAM,SAAS,IAAIK,aAAY,EAAE,OAAO,eAAe;AACvD,QAAM,aAAa,SAAS,cAAc;AAE1C,MAAI;AACJ,WAAS,UAAU,GAAG,UAAU,YAAY,WAAW;AACrD,QAAI;AACF,aAAO,MAAM;AAAA,QACX,EAAE,QAAQ,SAAS,SAAS,QAAQ;AAAA,QACpC,EAAE,OAAO,SAAS,MAAM;AAAA,MAC1B;AAAA,IACF,SAAS,OAAO;AACd,kBAAY;AACZ,YAAM,cACJ,UAAU,QAAQ,SAAS,OAAO,KAClC,UAAU,QAAQ,SAAS,QAAQ,KACnC,UAAU,QAAQ,SAAS,qBAAqB,KAChD,UAAU,KAAK,SAAS,KAAK;AAC/B,UAAI,CAAC,aAAa;AAChB,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM;AACR;",
6
- "names": ["getToolOrDynamicToolName", "isToolOrDynamicToolUIPart", "isToolOrDynamicToolUIPart", "getToolOrDynamicToolName", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "z", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "dedent", "user", "structuredOutput", "groq", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "z", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "dedent", "user", "structuredOutput", "groq", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "outputSchema", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "fragment", "ContextEngine", "InMemoryContextStore", "persona", "user", "dedent", "groq", "structuredOutput", "z", "persona", "groq", "dedent", "pLimit", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "structuredOutput", "user", "z", "ContextEngine", "InMemoryContextStore", "dedent", "fragment", "guardrail", "user", "structuredOutput", "groq", "pLimit", "groq", "NoObjectGeneratedError", "NoOutputGeneratedError", "dedent", "pLimit", "pRetry", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "persona", "structuredOutput", "user", "dedent", "z", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "guardrail", "user", "structuredOutput", "groq", "pLimit", "withRetry", "pRetry", "NoObjectGeneratedError", "NoOutputGeneratedError", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "personaFragment", "structuredOutput", "user", "outputSchema", "z", "ContextEngine", "InMemoryContextStore", "personaFragment", "fragment", "dedent", "guardrail", "user", "structuredOutput", "groq", "XmlRenderer", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "persona", "structuredOutput", "user", "outputSchema", "XmlRenderer"]
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 #messages: UIMessage[];\n #options: MessageExtractorOptions;\n\n /**\n * @param messages - Chat history to extract pairs from\n * @param options - Extraction configuration\n */\n constructor(messages: UIMessage[], options: MessageExtractorOptions = {}) {\n super();\n this.#messages = messages;\n this.#options = options;\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 {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\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}\n\nconst contextResolverSchema = z.object({\n question: z\n .string()\n .describe(\n 'A standalone natural language question that the SQL query answers',\n ),\n});\n\n/**\n * Resolves a SQL query with conversation context into a standalone question.\n */\nexport async function resolveContext(params: {\n conversation: string;\n sql: string;\n introspection?: string;\n}): Promise<{ question: string }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `context-resolver-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'context_resolver',\n role: 'You are an expert at understanding conversational context and generating clear, standalone questions from multi-turn conversations.',\n objective:\n 'Transform context-dependent messages into standalone questions that fully capture user intent',\n }),\n ...(params.introspection\n ? [fragment('database_schema', params.introspection)]\n : []),\n fragment('conversation', params.conversation),\n fragment('sql', params.sql),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n fragment(\n 'examples',\n dedent`\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 `,\n ),\n user('Generate a standalone question for this SQL query.'),\n );\n\n const resolverOutput = structuredOutput({\n model: groq('openai/gpt-oss-20b'),\n context,\n schema: contextResolverSchema,\n });\n\n return resolverOutput.generate();\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 protected messages: UIMessage[];\n protected adapter: Adapter;\n protected options: BaseContextualExtractorOptions;\n\n constructor(\n messages: UIMessage[],\n adapter: Adapter,\n options: BaseContextualExtractorOptions = {},\n ) {\n super();\n this.messages = messages;\n this.adapter = adapter;\n this.options = options;\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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 output = await resolveContext({\n conversation: formatConversation(item.conversationContext),\n sql: item.sql,\n introspection,\n });\n\n yield [\n {\n question: output.question,\n sql: item.sql,\n context: item.conversationContext,\n success: item.success,\n },\n ];\n }\n }\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 {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\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 outputSchema = z.object({\n question: z\n .string()\n .describe('A natural language question that the SQL query answers'),\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.#adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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 context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `sql-to-question-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'sql_to_question',\n role: 'You are an expert at understanding SQL queries and generating clear, natural language questions that describe what the query retrieves.',\n objective:\n 'Generate clear, natural language questions that describe what SQL queries retrieve',\n }),\n fragment('database_schema', introspection),\n fragment('sql', sql),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n fragment(\n 'examples',\n dedent`\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 `,\n ),\n user('Generate a natural language question for this SQL query.'),\n );\n\n const sqlToQuestionOutput = structuredOutput({\n model: groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n const output = await sqlToQuestionOutput.generate();\n\n yield [\n {\n question: 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 {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n formatConversation,\n resolveContext,\n} from './base-contextual-extractor.ts';\n\nexport type SegmentedContextExtractorOptions = BaseContextualExtractorOptions;\n\nconst topicChangeSchema = 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\n/**\n * Detects if a new message represents a topic change from the prior context.\n */\nasync function detectTopicChange(params: {\n context: string;\n newMessage: string;\n}): Promise<{ isTopicChange: boolean; reason: string }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `topic-change-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'topic_change_detector',\n role: 'You are an expert at understanding conversational flow and detecting topic changes.',\n objective: 'Detect significant topic changes in database conversations',\n }),\n fragment('conversation_context', params.context || '(no prior context)'),\n fragment('new_message', params.newMessage),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n fragment(\n 'examples',\n dedent`\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 `,\n ),\n user('Determine if this is a topic change.'),\n );\n\n const topicOutput = structuredOutput({\n model: groq('openai/gpt-oss-20b'),\n context,\n schema: topicChangeSchema,\n });\n\n return topicOutput.generate();\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 detectTopicChange({\n context: formatConversation(contextSnapshot),\n newMessage: text,\n });\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 * 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 output = await resolveContext({\n conversation: formatConversation([...contextSnapshot, `User: ${text}`]),\n sql: '', // No SQL yet, just resolving the question\n });\n\n return output.question;\n }\n}\n", "import type { UIMessage } from 'ai';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport type { ExtractedPair } from '../types.ts';\nimport {\n BaseContextualExtractor,\n type BaseContextualExtractorOptions,\n formatConversation,\n resolveContext,\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 extractor.toPairs(); // 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 output = await resolveContext({\n conversation: formatConversation(last.conversationContext),\n sql: last.sql,\n introspection,\n });\n\n yield [\n {\n question: 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';\nimport type { ContextFragment } from '@deepagents/context';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { UnanswerableSQLError } from '../../agents/exceptions.ts';\nimport {\n type QuestionComplexity,\n generateQuestions,\n} from '../../agents/question.agent.ts';\nimport { type ToSqlResult, toSql } from '../../agents/sql.agent.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?: ContextFragment[];\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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: string, // TODO: This was Awaited<ReturnType<Adapter['introspect']>> - needs update when synthesis uses fragments\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 // TODO: Update to use schemaFragments instead of introspection string\n return await toSql({\n input: question,\n adapter: this.adapter,\n fragments: 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", "const sqlValidationMarker = Symbol('SQLValidationError');\nconst unanswerableSqlMarker = Symbol('UnanswerableSQLError');\n\n/**\n * Error thrown when SQL validation fails.\n */\nexport class SQLValidationError extends Error {\n [sqlValidationMarker]: true;\n\n constructor(message: string) {\n super(message);\n this.name = 'SQLValidationError';\n this[sqlValidationMarker] = true;\n }\n\n static isInstance(error: unknown): error is SQLValidationError {\n return (\n error instanceof SQLValidationError && error[sqlValidationMarker] === true\n );\n }\n}\n\n/**\n * Error thrown when the question cannot be answered with the given schema.\n */\nexport class UnanswerableSQLError extends Error {\n [unanswerableSqlMarker]: true;\n\n constructor(message: string) {\n super(message);\n this.name = 'UnanswerableSQLError';\n this[unanswerableSqlMarker] = true;\n }\n\n static isInstance(error: unknown): error is UnanswerableSQLError {\n return (\n error instanceof UnanswerableSQLError &&\n error[unanswerableSqlMarker] === true\n );\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n guardrail,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nexport type QuestionComplexity =\n | 'simple'\n | 'moderate'\n | 'complex'\n | 'high complex';\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\nconst outputSchema = 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\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 context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `question-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'question_generator',\n role: 'You are a synthetic data generator specializing in creating realistic natural language questions that users might ask about a database.',\n objective:\n 'Generate diverse, realistic natural language questions that match the specified complexity level',\n }),\n fragment('database_schema', introspection || ''),\n fragment(\n 'complexity',\n { level: complexity },\n complexityInstructions[complexity],\n ),\n fragment(\n 'task',\n dedent`\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 `,\n ),\n guardrail({\n rule: 'Questions MUST ONLY reference tables and columns that exist in the schema above',\n }),\n guardrail({\n rule: 'Before generating each question, verify that ALL entities (tables, columns, relationships) you reference are explicitly listed in the schema',\n }),\n guardrail({\n rule: 'DO NOT invent or assume tables/columns that are not explicitly shown in the schema',\n }),\n guardrail({\n rule: 'Use natural language without SQL keywords like SELECT, WHERE, etc.',\n }),\n guardrail({\n rule: 'All questions must match the specified complexity level',\n }),\n user(\n prompt ??\n `Generate ${count} questions at ${complexity} complexity given db schema.`,\n ),\n );\n\n const questionOutput = structuredOutput({\n model: model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n return questionOutput.generate();\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 dedent from 'dedent';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n type ContextFragment,\n InMemoryContextStore,\n example,\n fragment,\n guardrail,\n hint,\n persona,\n policy,\n structuredOutput,\n user,\n workflow,\n} from '@deepagents/context';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport { SQLValidationError, UnanswerableSQLError } from './exceptions.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 /** Context fragments (schema + instructions/teachings) */\n fragments: ContextFragment[];\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/** Temperature progression for retries: deterministic first, then increasingly exploratory */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\nconst SQL_AGENT_ROLE = 'Expert SQL query generator.';\nconst SQL_AGENT_OBJECTIVE = 'Generate precise SQL grounded in provided schema.';\n\nconst SQL_AGENT_POLICIES: ContextFragment[] = [\n fragment(\n 'schema_mapping',\n policy({\n rule: 'Translate natural language into precise SQL grounded in available schema entities.',\n }),\n hint('Preserve schema spelling exactly, including typos in column names.'),\n ),\n fragment(\n 'projection_minimality',\n policy({\n rule: 'Return only columns requested by the question; do not add helper columns unless explicitly requested.',\n }),\n policy({\n rule: 'For requests of the form \"X sorted/ordered by Y\", project X only unless Y is explicitly requested as an output field.',\n }),\n policy({\n rule: 'Prefer selecting schema columns directly without derived expressions when direct selection answers the request.',\n }),\n hint(\n 'Do not include ORDER BY, GROUP BY, or JOIN helper columns in SELECT output unless the question explicitly asks for them.',\n ),\n policy({\n rule: 'Use DISTINCT only when uniqueness is explicitly requested (for example distinct/unique/different/no duplicates).',\n }),\n hint(\n 'Do not infer DISTINCT from generic wording such as \"some\", plural nouns, or entity-set phrasing; for transactional/attendance-style tables, default to raw rows unless uniqueness is explicitly requested.',\n ),\n ),\n fragment(\n 'date_transform_safety',\n policy({\n rule: 'Do not assume VARCHAR/TEXT values are parseable dates. Avoid date extraction functions on text columns by default.',\n }),\n policy({\n rule: 'Use date-part extraction only when both conditions hold: the question explicitly asks for transformation and schema values require transformation to produce that unit.',\n }),\n hint(\n 'Do not apply SUBSTR, STRFTIME, DATE_PART, YEAR, or similar extraction functions unless the question explicitly asks for transformation and schema values require it.',\n ),\n hint(\n 'If a column already represents the requested concept (for example a stored year-like value), use the column as-is.',\n ),\n ),\n fragment(\n 'sql_minimality',\n guardrail({\n rule: 'Never hallucinate tables or columns.',\n reason: 'Schema fidelity is required.',\n action: 'Use only available schema entities.',\n }),\n guardrail({\n rule: 'Avoid unnecessary transformations and derived projections.',\n reason:\n 'Extra transformations frequently change semantics and reduce correctness.',\n action:\n 'Do not add date parsing, substring extraction, or derived columns unless explicitly required by the question or schema.',\n }),\n ),\n fragment(\n 'preflight_checklist',\n workflow({\n task: 'Final SQL preflight before returning output',\n steps: [\n 'Verify selected columns match the question and remove unrequested helper projections.',\n 'If aggregate values are used only for ranking/filtering, keep them out of SELECT unless explicitly requested.',\n 'Prefer raw schema columns over derived expressions when raw columns already satisfy the request.',\n 'If a candidate query uses STRFTIME, SUBSTR, DATE_PART, YEAR, or similar extraction on text-like columns, remove that transformation unless explicitly required by the question.',\n 'Return only schema-grounded SQL using existing tables and columns.',\n ],\n }),\n ),\n fragment(\n 'set_semantics',\n policy({\n rule: 'For questions asking where both condition A and condition B hold over an attribute, compute the intersection of qualifying sets for that attribute.',\n }),\n policy({\n rule: 'Do not force the same entity instance to satisfy both conditions unless the question explicitly requests the same person/row/entity.',\n }),\n hint(\n 'Prefer INTERSECT (or logically equivalent set-based shape) over requiring the same physical row/entity to satisfy both conditions unless explicitly requested.',\n ),\n hint(\n 'When two conditions describe different row groups whose shared attribute is requested, build each group separately and intersect the attribute values.',\n ),\n hint(\n 'Do not collapse cross-group conditions into a single-row AND predicate when the intent is shared values across groups.',\n ),\n policy({\n rule: 'If two predicates on the same field cannot both be true for one row, do not combine them with AND; use set operations across separate filtered subsets when shared values are requested.',\n }),\n ),\n fragment(\n 'predicate_column_alignment',\n policy({\n rule: 'Match literal values to semantically compatible columns. Do not compare descriptive names to identifier columns.',\n }),\n hint(\n 'When a filter value is a descriptive label (for example a department name), join through the lookup table and filter on its name/title column, not on *_id columns.',\n ),\n hint(\n 'When relation roles are explicit in wording (for example host/home/source/destination), prefer foreign keys with matching role qualifiers over generic similarly named columns.',\n ),\n policy({\n rule: 'When multiple foreign-key candidates exist, select the column whose qualifier best matches the relationship described in the question.',\n }),\n policy({\n rule: 'For hosting/held semantics, prefer host_* relationship columns when available over generic *_id alternatives.',\n }),\n hint(\n 'Interpret wording like \"held/hosted a competition or event\" as a hosting relationship and map to host_* foreign keys when present.',\n ),\n policy({\n rule: 'Do not compare descriptive labels or names to *_id columns; join to the table containing the descriptive field and filter there.',\n }),\n policy({\n rule: 'Keep numeric identifiers unquoted when used as numeric equality filters unless schema indicates text identifiers.',\n }),\n policy({\n rule: 'When filtering by a descriptive label value and a related table exposes a corresponding *_name or title column, join to that table and filter on the descriptive column.',\n }),\n ),\n fragment(\n 'ordering_semantics',\n policy({\n rule: 'Respect explicit sort direction terms. If direction is not specified, use ascending order unless a superlative intent (most/least/highest/lowest) implies direction.',\n }),\n policy({\n rule: 'When ranking categories by frequency, use COUNT for ordering but keep output focused on requested category fields unless counts are explicitly requested.',\n }),\n policy({\n rule: 'Do not use DESC unless descending direction is explicit or a superlative intent requires descending ranking.',\n }),\n policy({\n rule: 'For \"most common/frequent <attribute>\" requests, return the attribute value(s) only; use counts only for ordering/filtering unless the question explicitly asks to return counts.',\n }),\n hint(\n 'Use DESC with LIMIT 1 for \"most/highest/largest\"; use ASC with LIMIT 1 for \"least/lowest/smallest\".',\n ),\n ),\n fragment(\n 'negative_membership_queries',\n policy({\n rule: 'For requests asking entities that did not participate/host/appear in related records, prefer NOT IN or NOT EXISTS against the related foreign-key set.',\n }),\n hint(\n 'Map role-bearing relationship columns carefully (for example host_* foreign keys for hosting relationships) instead of generic IDs when role wording is explicit.',\n ),\n hint(\n 'For \"never had/never exceeded\" conditions over history tables, exclude entities via NOT IN/NOT EXISTS against the disqualifying entity-id set (often built with GROUP BY/HAVING MAX(...)).',\n ),\n ),\n fragment(\n 'join_completeness',\n policy({\n rule: 'Preserve entity-restricting joins implied by the question. Do not widen results by querying only a broader attribute table when a subset entity table is available.',\n }),\n policy({\n rule: 'If an entity term in the question maps to a table, keep that table in query scope and join to attribute tables rather than dropping the entity table.',\n }),\n hint(\n 'If the question targets a specific entity group, include that entity table and its join conditions even when selected columns come from a related table.',\n ),\n hint(\n 'When the question names an entity type and a relation table links to that entity via *_id, include the entity table in scope instead of counting only relation rows.',\n ),\n hint(\n 'Prefer INNER JOIN by default; use LEFT JOIN only when the question explicitly requests including unmatched rows or zero-related entities.',\n ),\n ),\n fragment(\n 'aggregation_exactness',\n policy({\n rule: 'Preserve requested aggregation semantics exactly: use COUNT(*) by default for total rows, use COUNT(DISTINCT ...) only when uniqueness is explicitly requested, and group by stable entity keys when computing per-entity aggregates.',\n }),\n policy({\n rule: 'For questions asking which entity has lowest/highest average of a metric, compute AVG(metric) per entity (GROUP BY entity) and rank those aggregates.',\n }),\n hint(\n 'For \"how many <entities>\" questions over relation records, default to COUNT(*) on qualifying rows unless explicit uniqueness language is present.',\n ),\n ),\n fragment(\n 'query_shape_examples',\n example({\n question:\n 'List categories ordered by how many records belong to each category.',\n answer:\n 'SELECT category FROM records GROUP BY category ORDER BY COUNT(*)',\n }),\n example({\n question:\n 'Show labels shared by rows with metric > 100 and rows with metric < 10.',\n answer:\n 'SELECT label FROM records WHERE metric > 100 INTERSECT SELECT label FROM records WHERE metric < 10',\n }),\n example({\n question: 'List locations that have not hosted any event.',\n answer:\n 'SELECT location_name FROM locations WHERE location_id NOT IN (SELECT host_location_id FROM events)',\n }),\n example({\n question: 'List the most common category across records.',\n answer:\n 'SELECT category FROM records GROUP BY category ORDER BY COUNT(*) DESC LIMIT 1',\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 async function toSql(options: ToSqlOptions): Promise<ToSqlResult> {\n const { maxRetries = 3 } = options;\n\n return withRetry(\n async (attemptNumber, errors, attempts) => {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `sql-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'Freya',\n role: SQL_AGENT_ROLE,\n objective: SQL_AGENT_OBJECTIVE,\n // role: `You are a data science expert that provides well-reasoned and detailed responses.`,\n // objective: `Your task is to understand the schema and generate a valid SQL query to answer the question. You first think about the reasoning process as an internal monologue and then provide the user with the answer.`,\n }),\n ...SQL_AGENT_POLICIES,\n ...options.fragments,\n );\n\n // Add user message(s)\n if (errors.length) {\n const lastError = errors.at(-1);\n context.set(\n user(dedent`\n Answer the following question with the SQL code. Use the piece of evidence and base your answer on the database schema.\nGiven the question, the evidence and the database schema, return the SQL script that addresses the question.\n\nQuestion: ${options.input}\n`),\n UnanswerableSQLError.isInstance(lastError)\n ? user(\n `<retry_instruction>Your previous response marked the task as unanswerable. Re-evaluate using best-effort schema mapping. If the core intent is answerable with existing tables/columns, return SQL. Return error only when required core intent cannot be mapped without inventing schema elements.</retry_instruction>`,\n )\n : user(\n `<validation_error>Your previous SQL query had the following error: ${lastError?.message}. Please fix the query.</validation_error>`,\n ),\n );\n } else {\n context.set(\n user(dedent`\n Answer the following question with the SQL code. Use the piece of evidence and base your answer on the database schema.\nGiven the question, the evidence and the database schema, return the SQL script that addresses the question.\n\nQuestion: ${options.input}\n`),\n );\n }\n\n // Create structured output with schema\n const temperature =\n RETRY_TEMPERATURES[attemptNumber - 1] ??\n RETRY_TEMPERATURES[RETRY_TEMPERATURES.length - 1];\n const baseModel = options.model ?? groq('openai/gpt-oss-20b');\n const model = wrapLanguageModel({\n model: baseModel,\n middleware: defaultSettingsMiddleware({ settings: { temperature } }),\n });\n const sqlOutput = structuredOutput({\n model: model,\n context,\n schema: z.object({\n result: z.union([\n z.object({\n sql: z\n .string()\n .describe('The SQL query that answers the question'),\n reasoning: z\n .string()\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 }),\n });\n\n const { result: output } = await sqlOutput.generate();\n\n const finalizeSql = async (rawSql: string): Promise<ToSqlResult> => {\n const sql = options.adapter.format(extractSql(rawSql));\n\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\n // Handle error responses (question is unanswerable with given schema)\n if ('error' in output) {\n context.set(\n user(\n '<best_effort_fallback>Do not return unanswerable. Produce the best valid SQL query that answers the core intent using only available schema entities.</best_effort_fallback>',\n ),\n );\n const forcedSqlOutput = structuredOutput({\n model,\n context,\n schema: z.object({\n sql: z\n .string()\n .describe(\n 'Best-effort SQL query that answers the core intent using only available schema entities.',\n ),\n reasoning: z\n .string()\n .describe('Reasoning steps for best-effort schema mapping.'),\n }),\n });\n\n try {\n const forced = await forcedSqlOutput.generate();\n return await finalizeSql(forced.sql);\n } catch (error) {\n if (\n SQLValidationError.isInstance(error) ||\n APICallError.isInstance(error) ||\n JSONParseError.isInstance(error) ||\n TypeValidationError.isInstance(error) ||\n NoObjectGeneratedError.isInstance(error) ||\n NoOutputGeneratedError.isInstance(error) ||\n NoContentGeneratedError.isInstance(error)\n ) {\n throw error;\n }\n throw new UnanswerableSQLError(output.error);\n }\n }\n\n return await finalizeSql(output.sql);\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\nfunction isModelUnavailableError(error: unknown): boolean {\n if (!APICallError.isInstance(error)) {\n return false;\n }\n\n const message = error.message.toLowerCase();\n const responseBody = (error.responseBody ?? '').toLowerCase();\n const is404ModelError =\n error.statusCode === 404 &&\n (message.includes('model') || responseBody.includes('model_not_found'));\n const errorCode =\n typeof error.data === 'object' &&\n error.data !== null &&\n 'error' in error.data &&\n typeof error.data.error === 'object' &&\n error.data.error !== null &&\n 'code' in error.data.error &&\n typeof error.data.error.code === 'string'\n ? error.data.error.code.toLowerCase()\n : undefined;\n\n return (\n is404ModelError ||\n errorCode === 'model_not_found' ||\n responseBody.includes('\"code\":\"model_not_found\"') ||\n (message.includes('model') &&\n message.includes('does not exist or you do not have access to it'))\n );\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 // Retry one time when the model marks query as unanswerable to recover from false positives.\n if (UnanswerableSQLError.isInstance(context.error)) {\n return false;\n // disable retryng here will also disable the forced sql generation fallback.\n // return context.attemptNumber === 0;\n }\n // Don't retry if the selected model is unavailable\n if (isModelUnavailableError(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 // 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", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n guardrail,\n persona as personaFragment,\n structuredOutput,\n user,\n} from '@deepagents/context';\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\nconst paraphraserOutputSchema = z.object({\n paraphrases: z\n .array(\n z.string().describe('A paraphrased version of the original question'),\n )\n .min(1)\n .describe('List of paraphrased questions that would produce the same SQL'),\n});\n\n/**\n * Generates paraphrased versions of a question while preserving SQL equivalence.\n */\nasync function paraphraseQuestion(params: {\n question: string;\n sql: string;\n count: number;\n persona?: Persona;\n model?: AgentModel;\n}): Promise<{ paraphrases: string[] }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `paraphraser-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n const personaInstruction = params.persona\n ? dedent`\n <persona role=\"${params.persona.role}\">\n ${params.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 params.persona?.styles && params.persona.styles.length > 0\n ? dedent`\n <communication_styles>\n Generate paraphrases using these communication styles: ${params.persona.styles.join(', ')}\n\n Style definitions:\n ${params.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 context.set(\n personaFragment({\n name: 'question_paraphraser',\n role: 'You are a linguistic expert specializing in paraphrasing database questions. Your task is to generate alternative phrasings of questions that preserve the exact same semantic meaning - they must all produce the identical SQL query.',\n objective:\n 'Generate paraphrased versions of questions that preserve exact semantic meaning and produce identical SQL',\n }),\n fragment('original_question', params.question),\n fragment(\n 'reference_sql',\n params.sql,\n 'This SQL shows what the question is really asking - all paraphrases must ask for exactly this',\n ),\n ...(personaInstruction ? [fragment('persona', personaInstruction)] : []),\n ...(styleInstruction\n ? [fragment('communication_styles', styleInstruction)]\n : []),\n fragment(\n 'task',\n dedent`\n Generate exactly ${params.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 ${params.persona?.styles?.length ? '6. Apply the specified communication styles to create diverse phrasings' : ''}\n `,\n ),\n guardrail({ rule: 'NEVER change what data is being requested' }),\n guardrail({\n rule: 'NEVER add filters, aggregations, or conditions not in the original',\n }),\n guardrail({\n rule: 'NEVER remove any specificity from the original question',\n }),\n guardrail({\n rule: 'All paraphrases must be answerable by the exact same SQL query',\n }),\n user(\n `Paraphrase this question ${params.count} times: \"${params.question}\"`,\n ),\n );\n\n const paraphraserOutput = structuredOutput({\n model: params.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: paraphraserOutputSchema,\n });\n\n return paraphraserOutput.generate();\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 result = await paraphraseQuestion({\n question: pair.question,\n sql: pair.sql,\n count: this.options.count,\n persona: this.options.persona,\n model: this.options.model,\n });\n\n return result.paraphrases.map((paraphrase: string) => ({\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 { NoObjectGeneratedError, NoOutputGeneratedError } from 'ai';\nimport dedent from 'dedent';\nimport pLimit from 'p-limit';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n fragment,\n guardrail,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport type { Adapter } from '../../adapters/adapter.ts';\nimport { UnanswerableSQLError } from '../../agents/exceptions.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\nconst evolverOutputSchema = z.object({\n evolvedQuestion: z\n .string()\n .describe('The evolved, more complex version of the original question'),\n});\n\n/**\n * Evolves a simple question into a more complex version using a specific technique.\n */\nasync function evolveQuestion(params: {\n question: string;\n sql: string;\n schema: string;\n technique: DepthTechnique;\n techniqueInstruction: string;\n model?: AgentModel;\n}): Promise<{ evolvedQuestion: string }> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `evolver-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'question_evolver',\n role: 'You are an expert at evolving simple database questions into more complex ones. Your task is to take a basic question and transform it into a more sophisticated version that requires advanced SQL techniques to answer.',\n objective:\n 'Transform simple questions into complex versions requiring advanced SQL techniques',\n }),\n fragment('original_question', params.question),\n fragment(\n 'original_sql',\n params.sql,\n '(This shows what the original question required)',\n ),\n fragment('database_schema', params.schema),\n fragment(\n 'technique',\n { name: params.technique },\n params.techniqueInstruction,\n ),\n fragment(\n 'task',\n dedent`\n Evolve the original question using the \"${params.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 `,\n ),\n guardrail({\n rule: 'The evolved question MUST require more complex SQL than the original',\n }),\n guardrail({\n rule: 'Do not ask for data that does not exist in the schema',\n }),\n guardrail({\n rule: 'Keep the question grounded in the same domain as the original',\n }),\n guardrail({ rule: 'Make sure the question is clear and unambiguous' }),\n user(\n `Evolve this question using \"${params.technique}\": \"${params.question}\"`,\n ),\n );\n\n const evolverOutput = structuredOutput({\n model: params.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: evolverOutputSchema,\n });\n\n return evolverOutput.generate();\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 // TODO: Update to use fragments and render them\n // const schemaFragments = await this.adapter.introspect();\n // const introspection = new XmlRenderer().render(schemaFragments);\n const introspection = '' as any; // Placeholder - synthesis needs to be updated to use fragments\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 output = await withRetry(() =>\n evolveQuestion({\n question: pair.question,\n sql: pair.sql,\n schema: introspection,\n technique,\n techniqueInstruction: techniqueInstructions[technique],\n model: this.options?.model,\n }),\n );\n\n const evolvedQuestion = output.evolvedQuestion;\n try {\n // TODO: Update to use schemaFragments instead of introspection string\n const sqlResult = await toSql({\n input: evolvedQuestion,\n adapter: this.adapter,\n fragments: [],\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 dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n type ContextFragment,\n InMemoryContextStore,\n XmlRenderer,\n fragment,\n guardrail,\n persona as personaFragment,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\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\nconst outputSchema = 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\n/**\n * Generate personas by analyzing database schema.\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 *\n * @param schemaFragments - Schema fragments from adapter.introspect()\n * @param options - Generation options including count and model\n * @returns Array of personas with roles and perspectives\n */\nexport async function generatePersonas(\n schemaFragments: ContextFragment[],\n options?: PersonaGeneratorOptions,\n): Promise<Persona[]> {\n const schema = new XmlRenderer().render(schemaFragments);\n const count = options?.count ?? 5;\n\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `persona-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n personaFragment({\n name: 'persona_generator',\n role: 'You are an expert at understanding database schemas and inferring who would use them.',\n objective:\n 'Generate realistic personas representing users who would query this database',\n }),\n fragment('database_schema', schema),\n fragment(\n 'task',\n dedent`\n Analyze the database schema and generate realistic personas representing\n the different types of users 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 `,\n ),\n fragment(\n 'example',\n dedent`\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 `,\n ),\n guardrail({\n rule: 'Only generate personas relevant to the actual schema provided',\n }),\n guardrail({\n rule: 'Do not invent tables or data that do not exist in the schema',\n }),\n guardrail({\n rule: 'Ensure perspectives are specific to the domain, not generic',\n }),\n user(\n `Generate exactly ${count} distinct personas who would query this database.`,\n ),\n );\n\n const personaOutput = structuredOutput({\n model: options?.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n const output = await personaOutput.generate();\n return output.personas;\n}\n", "import type { AgentModel } from '@deepagents/agent';\nimport { type ContextFragment, XmlRenderer } from '@deepagents/context';\n\nimport { toTeachings } from '../../agents/teachables.agent.ts';\n\nexport interface TeachingsGeneratorOptions {\n context?: string;\n model?: AgentModel;\n maxRetries?: number;\n}\n\n/**\n * Generate domain-specific teachings from database schema.\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 *\n * @param schemaFragments - Schema fragments from adapter.introspect()\n * @param options - Generation options including context, model, and maxRetries\n * @returns Array of teachings including vocabulary, patterns, and guardrails\n */\nexport async function generateTeachings(\n schemaFragments: ContextFragment[],\n options?: TeachingsGeneratorOptions,\n): Promise<ContextFragment[]> {\n const schema = new XmlRenderer().render(schemaFragments);\n const maxRetries = options?.maxRetries ?? 3;\n\n let lastError: Error | undefined;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await toTeachings(\n { schema, context: options?.context },\n { model: 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", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { type AgentModel } from '@deepagents/agent';\nimport {\n ContextEngine,\n type ContextFragment,\n InMemoryContextStore,\n analogy,\n clarification,\n example,\n explain,\n fragment,\n guardrail,\n hint,\n persona,\n quirk,\n structuredOutput,\n styleGuide,\n term,\n user,\n workflow,\n} from '@deepagents/context';\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 concepts: 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\nexport interface GenerateToTeachingsOptions {\n model?: AgentModel;\n}\n\nexport async function toTeachings(\n input: { schema: string; context?: string },\n options?: GenerateToTeachingsOptions,\n): Promise<ContextFragment[]> {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `teachables-gen-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'teachables-author',\n role: 'You design \"fragments\" for a Text2SQL system. Fragments become structured XML instructions.',\n objective:\n 'Choose only high-impact items that improve accuracy, safety, or clarity for this database',\n }),\n fragment('database_schema', input.schema),\n ...(input.context ? [fragment('additional_context', input.context)] : []),\n fragment(\n 'output_structure',\n dedent`\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: [{ concepts: string[], relationship: string, insight?: string, therefore?: string, pitfall?: string }]\n `,\n ),\n fragment(\n 'task',\n dedent`\n 1. Analyze the schema to infer domain, relationships, and sensitive columns.\n 2. Generate 3-10 fragments 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 `,\n ),\n user(\n `Analyze this database schema and generate fragments that will help an AI generate accurate SQL queries.`,\n ),\n );\n\n const teachablesOutput = structuredOutput({\n model: options?.model ?? groq('openai/gpt-oss-20b'),\n context,\n schema: outputSchema,\n });\n\n const result = await teachablesOutput.generate();\n\n const fragments: ContextFragment[] = [];\n\n // Convert generated output to ContextFragments\n result.terms?.forEach((t) => fragments.push(term(t.name, t.definition)));\n result.hints?.forEach((h) => fragments.push(hint(h.text)));\n result.guardrails?.forEach((g) =>\n fragments.push(\n guardrail({ rule: g.rule, reason: g.reason, action: g.action }),\n ),\n );\n result.explains?.forEach((e) =>\n fragments.push(\n explain({\n concept: e.concept,\n explanation: e.explanation,\n therefore: e.therefore,\n }),\n ),\n );\n result.examples?.forEach((e) =>\n fragments.push(\n example({ question: e.question, answer: e.answer, note: e.note }),\n ),\n );\n result.clarifications?.forEach((c) =>\n fragments.push(\n clarification({ when: c.when, ask: c.ask, reason: c.reason }),\n ),\n );\n result.workflows?.forEach((w) =>\n fragments.push(\n workflow({\n task: w.task,\n steps: w.steps,\n triggers: w.triggers,\n notes: w.notes,\n }),\n ),\n );\n result.quirks?.forEach((q) =>\n fragments.push(quirk({ issue: q.issue, workaround: q.workaround })),\n );\n result.styleGuides?.forEach((s) =>\n fragments.push(\n styleGuide({ prefer: s.prefer, never: s.never, always: s.always }),\n ),\n );\n result.analogies?.forEach((a) =>\n fragments.push(\n analogy({\n concepts: a.concepts,\n relationship: a.relationship,\n insight: a.insight,\n therefore: a.therefore,\n pitfall: a.pitfall,\n }),\n ),\n );\n\n return fragments;\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;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ADnNA,eAAsB,kBACpB,iBACA,SAC4B;AAC5B,QAAM,SAAS,IAAIE,aAAY,EAAE,OAAO,eAAe;AACvD,QAAM,aAAa,SAAS,cAAc;AAE1C,MAAI;AACJ,WAAS,UAAU,GAAG,UAAU,YAAY,WAAW;AACrD,QAAI;AACF,aAAO,MAAM;AAAA,QACX,EAAE,QAAQ,SAAS,SAAS,QAAQ;AAAA,QACpC,EAAE,OAAO,SAAS,MAAM;AAAA,MAC1B;AAAA,IACF,SAAS,OAAO;AACd,kBAAY;AACZ,YAAM,cACJ,UAAU,QAAQ,SAAS,OAAO,KAClC,UAAU,QAAQ,SAAS,QAAQ,KACnC,UAAU,QAAQ,SAAS,qBAAqB,KAChD,UAAU,KAAK,SAAS,KAAK;AAC/B,UAAI,CAAC,aAAa;AAChB,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM;AACR;",
6
+ "names": ["getToolOrDynamicToolName", "isToolOrDynamicToolUIPart", "isToolOrDynamicToolUIPart", "getToolOrDynamicToolName", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "z", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "dedent", "user", "structuredOutput", "groq", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "z", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "dedent", "user", "structuredOutput", "groq", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "outputSchema", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "persona", "structuredOutput", "user", "fragment", "guardrail", "ContextEngine", "InMemoryContextStore", "persona", "user", "dedent", "groq", "structuredOutput", "z", "persona", "groq", "dedent", "pLimit", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "structuredOutput", "user", "z", "ContextEngine", "InMemoryContextStore", "dedent", "fragment", "guardrail", "user", "structuredOutput", "groq", "pLimit", "groq", "NoObjectGeneratedError", "NoOutputGeneratedError", "dedent", "pLimit", "pRetry", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "persona", "structuredOutput", "user", "dedent", "z", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "guardrail", "user", "structuredOutput", "groq", "pLimit", "withRetry", "pRetry", "NoObjectGeneratedError", "NoOutputGeneratedError", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "fragment", "guardrail", "personaFragment", "structuredOutput", "user", "outputSchema", "z", "ContextEngine", "InMemoryContextStore", "personaFragment", "fragment", "dedent", "guardrail", "user", "structuredOutput", "groq", "XmlRenderer", "groq", "dedent", "z", "ContextEngine", "InMemoryContextStore", "example", "fragment", "guardrail", "hint", "persona", "structuredOutput", "user", "workflow", "outputSchema", "XmlRenderer"]
7
7
  }