MCPcopy Create free account
hub / github.com/antvis/AVA / PythonDialect

Class PythonDialect

src/query/python.ts:9–70  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7import type { DataModel, ExecutionResult, LLMConfig, QueryDialect, TranslationResult } from '../types';
8
9export class PythonDialect implements QueryDialect {
10 readonly id = 'python';
11
12 // Bindings and result conversion are supplied by the Python engine.
13 // https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html
14 readonly rules = `Use Python 3 and pandas for analysis. pandas is available as pd. Input DataFrames are in tables, keyed by schema table name.
15CSV/JSON use tables['data']; Excel exposes every sheet as tables['SheetName'].
16For a single table, the DataFrame df is also available. For multiple sheets use tables explicitly.
17Assign the final output to result: a DataFrame, Series, list of records, record, or JSON scalar.
18DataFrame and Series indexes are not returned; use reset_index() when index values matter.
19Each execution starts from fresh input data; variables and mutations do not persist between calls.
20Do not read files, access the network, install packages, or print the answer.`;
21
22 constructor(
23 private readonly llmConfig: LLMConfig,
24 private readonly execute?: (code: string, signal?: AbortSignal) => Promise<ExecutionResult>
25 ) {}
26
27 async getDSL(query: string, dataModel: DataModel, signal?: AbortSignal): Promise<TranslationResult> {
28 const { text, usage, finishReason } = await generateText({
29 model: languageModel(this.llmConfig),
30 maxRetries: this.llmConfig.maxRetries ?? 3,
31 abortSignal: signal,
32 prompt: `You are a data analysis expert. Generate Python code to answer the question.
33
34Dataset Context:
35${stringifyDataModel(dataModel)}
36
37User Query: ${query}
38
39${this.rules}
40
41Return only executable Python code, without explanation or Markdown.`,
42 });
43 if (finishReason !== 'stop' && finishReason !== 'other') {
44 throw new Error(`Python generation did not complete (${finishReason})`);
45 }
46 const dsl = text.trim().match(/^```(?:python|py)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/i)?.[1] ?? text;
47 if (!dsl.trim()) throw new Error('Python generation returned empty code');
48 return { dsl, usage };
49 }
50
51 async validateDSL(code: string, signal?: AbortSignal): Promise<string> {
52 throwIfAborted(signal);
53 if (!code.trim()) throw new Error('Python query must contain code');
54 if (code.includes('\0')) throw new Error('Python query contains a NUL character');
55 // Compile in the execution environment without running the user's code or loading source data.
56 // https://docs.python.org/3/library/functions.html#compile
57 const script = `import json
58compile(json.loads(${JSON.stringify(JSON.stringify(code))}), '<ava-query>', 'exec')
59print('{"data":[],"schema":[],"rowCount":0}')
60`;
61 if (this.execute) {
62 await (signal ? this.execute(script, signal) : this.execute(script));
63 } else {
64 const { createPythonExecutor } = await import('../interpreter/python/util/execute');
65 await createPythonExecutor(30_000)(script, 64 * 1024, signal);
66 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected