refactor: Replace PromptTemplates with AgentPromptTemplates across agents and remove obsolete templates module

This commit is contained in:
william.dias 2026-01-23 10:23:25 -03:00
parent 70a7a4a12b
commit ae33ee5bca
5 changed files with 25 additions and 68 deletions

View file

@ -1,7 +1,7 @@
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from sql_optimizer_team.tools.engine.model_selector import get_model
from sql_optimizer_team.tools.engine.prompt_tools.templates import PromptTemplates
from sql_optimizer_team.agents.prompts import AgentPromptTemplates
from sql_optimizer_team.tools.prompt_tools import supported_databases
from sql_optimizer_team.tools.sql_tools import load_sql_from_file, ensure_non_empty
import os
@ -31,7 +31,7 @@ conservative_analysis_agent = Agent(
"- Solicite banco e SQL se não estiverem presentes.",
"- Se o usuário fornecer um caminho de arquivo, use load_sql_from_file().",
"- Use a template oficial abaixo para a análise conservadora (sem reescrever a SQL).",
PromptTemplates.CONSERVATIVE_ANALYSIS.template.strip(),
AgentPromptTemplates.CONSERVATIVE_ANALYSIS.template.strip(),
"- NÃO reescreva a SQL em hipótese alguma.",
],
)

View file

@ -1,18 +1,14 @@
"""Prompt templates for SQL optimization.
"""Prompt templates used by Agno agents.
This module provides reusable prompt templates that can be customized
for different database types.
This module keeps the canonical prompts alongside the agents to ensure
all prompt content is owned and maintained by the agent layer.
"""
from string import Template
class PromptTemplates:
"""Collection of prompt templates for SQL optimization.
These templates use Python's string.Template for safe string substitution.
Templates can be customized per database type while maintaining consistency.
"""
class AgentPromptTemplates:
"""Collection of prompt templates for SQL optimization agents."""
SQL_TO_NATURAL = Template("""
You are an expert $database_name database analyst and performance specialist. Your task is to translate the SQL query below into a detailed, precise natural-language description that another agent will later use to reconstruct and optimize the query.
@ -76,7 +72,6 @@ class PromptTemplates:
Explanation:
""")
NATURAL_TO_SQL = Template("""
You are an expert $database_name SQL developer and query performance specialist.
Your task is to write an optimized SQL query based exclusively on the natural-language description provided below.
@ -138,19 +133,18 @@ class PromptTemplates:
Optimized SQL Query:
""")
CONSERVATIVE_ANALYSIS = Template("""
You are an expert $database_name database analyst and performance specialist.
Your task is to ANALYZE the SQL query below and provide SUGGESTIONS for improvement.
CRITICAL: You must NOT rewrite or modify the query. Only provide analysis and suggestions.
$database_name SQL Query:
```sql
$query
```
Query Complexity Information:
- Columns: $column_count
- Tables: $table_count
@ -158,31 +152,31 @@ class PromptTemplates:
- CASE statements: $case_count
- JOINs: $join_count
- Complexity Level: $complexity_level
Provide your analysis in the following structured format:
## PERFORMANCE ISSUES
List each performance issue found, with severity (CRITICAL/HIGH/MEDIUM/LOW):
- [SEVERITY] Issue description
- [SEVERITY] Issue description
## SUGGESTED INDEXES
List indexes that could improve this query:
- CREATE INDEX idx_name ON table(columns) -- Reason
## OPTIMIZATION SUGGESTIONS
List specific suggestions WITHOUT rewriting the query:
- Suggestion 1: Description of what could be improved and why
- Suggestion 2: Description of what could be improved and why
## RISK ASSESSMENT
- WITH (NOLOCK) usage: [Yes/No] - If yes, explain the risks
- Missing WHERE clause: [Yes/No] - If yes, explain the impact
- Implicit conversions: [Yes/No] - If yes, list them
## SUMMARY
Brief summary of the most important findings and priority order for addressing them.
Remember: DO NOT provide a rewritten query. Only analysis and suggestions.
""")
@ -190,17 +184,6 @@ class PromptTemplates:
def render_sql_to_natural(
cls, database_name: str, query: str, specific_features: str = "", analysis_requirements: str = ""
) -> str:
"""Render SQL-to-natural language prompt.
Args:
database_name: Name of database system
query: SQL query to explain
specific_features: Additional database-specific features to mention
analysis_requirements: Additional performance analysis requirements
Returns:
Rendered prompt string
"""
return cls.SQL_TO_NATURAL.substitute(
database_name=database_name,
query=query,
@ -212,17 +195,6 @@ class PromptTemplates:
def render_natural_to_sql(
cls, database_name: str, explanation: str, specific_requirements: str
) -> str:
"""Render natural-to-SQL prompt.
Args:
database_name: Name of database system
explanation: Natural language description
specific_requirements: Database-specific optimization requirements
Returns:
Rendered prompt string
"""
# Format requirements as bullet points
return cls.NATURAL_TO_SQL.substitute(
database_name=database_name,
explanation=explanation,
@ -243,21 +215,6 @@ class PromptTemplates:
join_count: int = 0,
complexity_level: str = "unknown",
) -> str:
"""Render conservative analysis prompt (no query rewriting).
Args:
database_name: Name of database system
query: SQL query to analyze
column_count: Number of columns in query
table_count: Number of tables in query
subquery_count: Number of subqueries
case_count: Number of CASE statements
join_count: Number of JOINs
complexity_level: Detected complexity level
Returns:
Rendered prompt string
"""
return cls.CONSERVATIVE_ANALYSIS.substitute(
database_name=database_name,
query=query,

View file

@ -2,7 +2,7 @@ from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from sql_optimizer_team.tools.engine.model_selector import get_model
from sql_optimizer_team.tools.core_tools import explain_query_core
from sql_optimizer_team.tools.engine.prompt_tools.templates import PromptTemplates
from sql_optimizer_team.agents.prompts import AgentPromptTemplates
from sql_optimizer_team.tools.prompt_tools import supported_databases
from sql_optimizer_team.tools.sql_tools import load_sql_from_file, ensure_non_empty
import os
@ -33,7 +33,7 @@ sql_analyst_agent = Agent(
"- Se o usuário fornecer um caminho de arquivo, use load_sql_from_file().",
"- Preferência: use explain_query_core(database_type, sql) para gerar a explicação via core de negócio.",
"- Use a template oficial abaixo para estruturar a explicação (SQL → natural).",
PromptTemplates.SQL_TO_NATURAL.template.strip(),
AgentPromptTemplates.SQL_TO_NATURAL.template.strip(),
"- Entregue apenas a explicação natural estruturada conforme a prompt; não reescreva a SQL.",
"- Identifique problemas críticos de performance conforme a prompt.",
],

View file

@ -2,7 +2,7 @@ from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from sql_optimizer_team.tools.engine.model_selector import get_model
from sql_optimizer_team.tools.core_tools import optimize_query_core
from sql_optimizer_team.tools.engine.prompt_tools.templates import PromptTemplates
from sql_optimizer_team.agents.prompts import AgentPromptTemplates
from sql_optimizer_team.tools.prompt_tools import supported_databases
from sql_optimizer_team.tools.sql_tools import load_sql_from_file, ensure_non_empty
import os
@ -32,7 +32,7 @@ sql_optimizer_agent = Agent(
"- Exija banco alvo e SQL antes de otimizar.",
"- Use optimize_query_core(database_type, sql) para executar o core de negócio.",
"- Use a template oficial abaixo para reescrever (natural → SQL) mantendo 100% da lógica.",
PromptTemplates.NATURAL_TO_SQL.template.strip(),
AgentPromptTemplates.NATURAL_TO_SQL.template.strip(),
"- Extraia e devolva SOMENTE optimized_query (sem explicações, sem markdown).",
"- Preserve 100% da lógica, colunas, aliases, filtros, joins e subqueries.",
],

View file

@ -7,7 +7,7 @@ reducing code duplication and ensuring consistency.
from abc import ABC, abstractmethod
from sql_optimizer_team.tools.engine.tools_api.prompt_tool import PromptGeneratorTool
from sql_optimizer_team.tools.engine.prompt_tools.templates import PromptTemplates
from sql_optimizer_team.agents.prompts import AgentPromptTemplates
class BasePromptGenerator(PromptGeneratorTool, ABC):
@ -70,7 +70,7 @@ class BasePromptGenerator(PromptGeneratorTool, ABC):
Returns:
Formatted prompt for LLM
"""
return PromptTemplates.render_sql_to_natural(
return AgentPromptTemplates.render_sql_to_natural(
database_name=self.get_database_name(),
query=query,
specific_features=self.get_specific_features(),
@ -86,7 +86,7 @@ class BasePromptGenerator(PromptGeneratorTool, ABC):
Returns:
Formatted prompt for LLM
"""
return PromptTemplates.render_natural_to_sql(
return AgentPromptTemplates.render_natural_to_sql(
database_name=self.get_database_name(),
explanation=explanation,
specific_requirements=self.get_specific_requirements(),