
    BCh@                         d dl Z d dlmZmZmZmZ d dlmZ d dlZd dl	Z	d dl Z d dl
mZ d dlmZmZ  e j                  e      Z G d de      Zy)    N)DictAnyOptionalList)current_app)AIModelBase)with_redis_query_cachewith_redis_explain_cachec                        e Zd ZdZdZ fdZdeeef   defdZ	 e
       ddedeeef   ded	eeeef      deeef   f
d
       Z e       deeef   dededeeef   fd       Z xZS )ClaudeModelz6Claude model for SQL generation using direct API callsclaudec                    t         |           t        j                  j	                  d      | _        t        j                  j	                  dd      | _        d| _        d| _        | j
                  st        j                  d       y	 t        | _        d| _        t        j                  d	       y# t        $ r+}t        j                  d
t        |              Y d}~yd}~ww xY w)z5Initialize the Claude model with direct HTTP requestsCLAUDE_3_OPUS_API_KEYCLAUDE_3_OPUS_MODELzclaude-3-opus-20240229z%https://api.anthropic.com/v1/messagesFz^Claude API key not configured. Please set CLAUDE_3_OPUS_API_KEY in your environment variables.NTzJClaude API integration initialized successfully using direct HTTP requestsz+Error initializing Claude API integration: )super__init__r   configgetapi_keymodelapi_urlinitializedloggerwarningrequestsinfo	Exceptionstr)selfe	__class__s     (/var/www/html/app/models/claude_model.pyr   zClaudeModel.__init__   s    "))--.EF ''++,AC[\
>  ||NN{|	S$DM#DKKde 	SNNHQQRR	Ss   
'B2 2	C&;!C!!C&schema_datareturnc                    g }|sy|j                  dg       }t        |t              r|D ]  }|j                  dd      }|j                  dg       }|j                  d|        |j                  d       |D ]?  }|j                  dd      }|j                  dd	      }	g }
|j                  d
| d|	        A |j                  d        dj	                  |      S |j                  di       j                         D ]  \  }}|j                  di       }g }|j                         D ]  \  }}|j                  dd	      }	|j                  dd      }|j                  dd      }|j                  dd      }g }
|r|
j                  d       |r^|j                  di       j                  d      }|j                  di       j                  d      }|r|r|
j                  d| d| d       |s|
j                  d       dj	                  |
      }|r|j                  d
| d|	 d| d       |j                  d
| d|	          |j                  d|        |j                  d       |j                  |       d|v r|d   r|j                  d       |d   j                         D ]Y  \  }}dj	                  |j                  dg             }|j                  d d      }|rd!nd"}|j                  d
| d| d#| d       [ |j                  d        d$|v r|d$   r|j                  d%       |d$   D ]y  }|j                  d&      }|j                  d'      }|j                  d(      }|j                  d)      }|j                  d*d	      }|j                  d
| d+| d,| d+| d| d       { |j                  d       dj	                  |      S )-z%Format the schema data for the promptzNo schema data availabletablesnameUnknowncolumnszTable: zColumns:dataTypeunknownz    
	data_typeis_nullableTis_primary_keyFis_foreign_keyzPRIMARY KEY
referencestablecolumnzFOREIGN KEY REFERENCES ()zNOT NULLz,  (indexeszIndexes:	is_uniquezUNIQUE INDEXINDEXz on relationshipszRelationships:
from_tablefrom_columnto_table	to_columntype.z -> )r   
isinstancelistappendjoinitemsextend)r   r#   formatted_schemar&   r4   
table_namer)   r5   column_namer/   constraints
table_infoformatted_columnscolumn_infor0   
is_primary
is_foreign	ref_table
ref_columnconstraints_str
index_name
index_infocolumns_strr:   
index_typerelr=   r>   r?   r@   rel_types                                  r"   _format_schema_for_promptz%ClaudeModel._format_schema_for_prompt&   s    - 2. fd# ,"YYvy9
))Ir2 '''*(>? ''
3% LF"(**VY"?K &

:y AI"$K$++bQyk,JKL !''+,  99-.. '2ooh&C&I&I&K (	("J
 nnY3G ",3MMO M(['OOKC	)oomTB(__-=uE
(__-=uE
 &&}5 +b A E Eg NI!,r!B!F!Fx!PJ Z#**-DYKqQ[P\\]+^_"&&z2"&))K"8"%,,r+a	{"_L]]^-_`%,,r+a	{-KL+M. ##gj\$:;##J/##$56 J&:i+@ ''
3.8.C.I.I.K _*J
"&))JNN9b,I"JK *{E BI3<'J$++bBzl${m[\,]^	_ ##B'Q(	(V k)k/.J##$45"?3 p WW\2
!ggm477:.GGK0	77695 ''"ZL+d8*TUV_U``bckbllm(nop ##B'yy)**    promptdb_type	db_configc                 ,   | j                   sdd| j                  dS | j                  |      }d}|r&d}|j                         D ]  \  }}|d| d| dz  } d	| d
| d}	d| d| d| d| }
d| j                  dd}| j
                  d|	dd|
dgddd}	 | j                  j                  | j                  ||      }|j                  dk(  r|j                         }|j                  dg       }|r#|d   j                  dd      j                         nd}|r@|j                         j                  d      s!d|| j                   d | j
                   d!dd"S d|xs d#| j                   d | j
                   d!dd$S d%|j                   d&|j                   }t         j#                  |       d|| j                  dd$S # t$        $ rH}t         j#                  d't'        |              dd(t'        |       | j                  dd$cY d)}~S d)}~ww xY w)*z=Generate SQL query using Claude API with direct HTTP requestsF#Claude API not properly initialized)successerrorr   r-   zDatabase Configuration:
z- z: r.   z0You are an expert SQL developer specializing in z databases.
Your task is to convert natural language requests into correct and efficient SQL queries.
Follow these guidelines:
1. Generate only valid aj   SQL syntax.
2. Focus on writing efficient queries with proper joins and conditions.
3. Return ONLY the SQL query without explanations or markdown formatting.
4. If you cannot generate a valid query, explain why.
5. Use appropriate table aliases for readability.
6. Consider performance implications of your query design.
7. Respect the database schema provided.Database Type: z

Database Schema:
z

z2

Generate a SQL query for the following request:
application/json
2023-06-01zContent-Typez	x-api-keyzanthropic-version	assistantrolecontentuser  皙?r   messages
max_tokenstemperatureheadersjson   rk   r   text)zi cannotz	i'm sorryzsorry,Tr8   r7   )rb   	sql_queryr   http_successzFailed to generate SQL query)rb   rc   r   ry   Claude API error:  - z"Error generating SQL with Claude: zFailed to generate SQL query: N)r   
model_typer[   rG   r   r   r   postr   status_coderu   r   striplower
startswithrw   r   rc   r   r   )r   r]   r#   r^   r_   rI   db_config_infokeyvaluesystem_messageuser_messagert   dataresponseresultrk   rx   error_messager    s                      r"   generate_sqlzClaudeModel.generate_sql   s     >   99+F 8N'oo/ 8
UBse2eWB"778 NgY W  y !)	, +7) 4       /!-
 ZZ$@L9 
3	}})) * H ##s*! !**Y3BIGAJNN626<<>r	 Y__%6%A%ABf%g $(%.$(OO#4Btzzl!!D(,	  $)!*!L.L$(OO#4Btzzl!!D(,	  #5X5I5I4J#hmm_ ]]+$*!__$)	   	LL=c!fXFG 9#a&B %	 	s,   CG $G  AG 	H=HHHexplain_datarx   c                    | j                   sddg dS t        j                  |d      }d| d}d| d	| d
| d}d| j                  dd}| j                  d|dd|dgddd}	 | j
                  j                  | j                  ||      }	|	j                  dk(  r|	j                         }
|
j                  dg       }|r#|d   j                  dd      j                         nd}g }d}|j                  d      }d}d}|D ]%  j                         dj                         v rdv rt        fdt        d d!      D              rs	 j                  d      d"   j                         }|j                         D ]=  }|j                  d#      j                         s#t!        |j                  d#            } n j                         j#                  d$      rd%}|d%k(  sr1d   j                         rd&dd' v r|r|j%                  |       }|ss|d(z   z  }( |r|j%                  |       |s|g}d)|||| j&                   d*| j                   d+d,S d-|	j                   d.|	j(                   }t*        j-                  |       d|g dS #  Y xY w# t.        $ r=}t*        j-                  d/t1        |              dd0t1        |       g dcY d}~S d}~ww xY w)1zJAnalyze database explain plan and provide recommendations using Claude APIFra   )rb   rc   recommendations   )indentz?You are an expert database performance analyst specializing in aw   databases.
Your task is to analyze the execution plan of a SQL query and provide recommendations for optimization.
Follow these guidelines:
1. Focus on identifying performance bottlenecks in the execution plan.
2. Provide specific, actionable recommendations to improve query performance.
3. CAUTION: Return ONLY the SQL query without explanations or markdown formatting.
4. Consider indexes, join methods, table scans, and other relevant factors.
5. Explain why each recommendation would improve performance.
6. Rate the overall efficiency of the query on a scale of 1-10.
7. Structure your analysis in a clear, organized manner.rd   z

SQL Query:
z

Execution Plan:
z

Please analyze this execution plan and provide:
1. A summary of how the query is being executed
2. Identification of any performance bottlenecks
3. Specific recommendations for optimization
4. An overall efficiency rating (1-10)re   rf   rg   rh   ri   rl   rm   rn   ro   rs   rv   rk   r   rw   r-   r.   Nrating:c              3   8   K   | ]  }t        |      v   y wN)r   ).0ilines     r"   	<genexpr>z3ClaudeModel.analyze_explain_plan.<locals>.<genexpr>G  s     Gm[\ARVGms         z.,)recommendationr   	suggestedoptimizationr   z.    r,   Tr8   r7   )rb   performance_analysisr   efficiency_ratingr   rz   r{   z*Error analyzing explain plan with Claude: z Failed to analyze explain plan: )r   ru   dumpsr   r   r   r}   r   r~   r   r   splitr   anyrangeisdigitintr   rE   r|   rw   r   rc   r   r   )r   r   r^   rx   explain_textr   r   rt   r   r   r   rk   analysis_textr   r   linescurrent_sectioncurrent_recommendationrating_textwordr   r    r   s                         @r"   analyze_explain_planz ClaudeModel.analyze_explain_plan   sd     >#%  zz,q9 ]]d\e 	f9 	< +7) 4    '*  /!-
 ZZ$@L9 
X	}})) * H ##s*! !**Y3FM
vr : @ @ BSU #%$%! &++D1"&)-&! AD::<D  4::</C4KCGm`efgik`lGmDm!*.**S/"*=*C*C*EK(3(9(9(; *#'::d#3#;#;#=8;DJJt<L8M$5$)* zz|../qr*;  '*;;T!W__%6448;K5 / 6 67M N59232cDj@2;A@ *#**+AB ''4oO  $,9'6): $04::,a@  #5X5I5I4J#hmm_ ]]+$*') O! V  	LLEc!fXNO ;CF8D#% 	sW   'C$J$ AJ!J>'J$ &5J$ J$ !AJ$ &6J$ J!J$ $	K*-2K%K*%K*r   )__name__
__module____qualname____doc__r|   r   r   r   r   r[   r	   r   r   r
   r   __classcell__)r!   s   @r"   r   r      s    @JS*X+T#s(^ X+ X+t n3 nT#s(^ nc n^fgkloqtltgu^v n  CG  HK  MP  HP  CQ n n` Pc3h P# PZ] Pbfgjlogobp P  Pr\   r   )loggingtypingr   r   r   r   flaskr   ru   r   app.models.ai_model_baser   app.utils.redis_cacher	   r
   	getLoggerr   r   r    r\   r"   <module>r      s@     , ,     0 R			8	$v+ vr\   