Files
ai-app-sql/services/gemini.ts

59 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { GoogleGenAI } from "@google/genai";
import { SqlGenerationRequest } from "../types";
const generateSqlPrompt = (data: SqlGenerationRequest): string => {
return `
你是一名世界级的数据库架构师和SQL专家。请根据以下提供的信息编写一个精确、高效的 SQL 查询语句。
### 1. 目标数据库类型
**${data.databaseType}**
(请严格遵守该数据库的方言规范,包括引号使用、函数名称、分页语法、字符串连接方式等)
### 2. 业务表结构与字段说明
${data.tableStructure}
### 3. 字典表信息 (用于代码转义)
${data.dictionaryData}
### 4. 查询需求
${data.requirement}
### 任务要求:
1. **自动关联**:根据表结构和字典表,自动构建 JOIN 语句。
2. **字典翻译**需求中提到的字段如果需要字典翻译例如政治面貌、国籍等请务必关联字典表取出对应的中文名称Label/Value
3. **输出格式**:只返回一段纯净的 SQL 代码,不需要 markdown 标记(如 \`\`\`sql不需要解释文字。
4. **命名规范**使用清晰的表别名Alias例如 main_table 为 t1, dict_table 为 d1 等。
5. **语法兼容**:针对 **${data.databaseType}** 进行优化。例如:
- 如果是 Oracle请注意字段通常大写使用双引号处理特殊列名日期处理使用 TO_DATE/TO_CHAR。
- 如果是 MySQL使用反引号 (\`) 处理列名。
- 如果是 SQL Server使用 [] 处理列名,注意 TOP 语法。
`;
};
export const generateSql = async (requestData: SqlGenerationRequest): Promise<string> => {
try {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
// Using gemini-2.5-flash for speed and good reasoning capabilities on coding tasks
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: generateSqlPrompt(requestData),
config: {
thinkingConfig: { thinkingBudget: 0 }, // Disable thinking for faster direct response
temperature: 0.2, // Lower temperature for more deterministic code generation
}
});
let sql = response.text || '';
// Clean up potential markdown formatting if the model adds it despite instructions
sql = sql.replace(/^```sql\n/, '').replace(/^```\n/, '').replace(/\n```$/, '');
return sql.trim();
} catch (error) {
console.error("Error generating SQL:", error);
throw new Error("生成 SQL 失败,请检查 API Key 或网络连接。");
}
};