
    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 )DeepSeekModelz8DeepSeek model for SQL generation using direct API callsdeepseekc                    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)z7Initialize the DeepSeek model with direct HTTP requestsDEEPSEEK_API_KEYDEEPSEEK_MODELzdeepseek-chatz,https://api.deepseek.com/v1/chat/completionsFz[DeepSeek API key not configured. Please set DEEPSEEK_API_KEY in your environment variables.NTzLDeepSeek API integration initialized successfully using direct HTTP requestsz-Error initializing DeepSeek 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/deepseek_model.pyr   zDeepSeekModel.__init__   s    "))--.@A ''++,<oN
E  ||NNxy	U$DM#DKKfg 	UNNJ3q6(STT	U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'DeepSeekModel._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                 D   | 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d| j                   d}| j
                  d|	dd|
dgdd}	 | j                  j                  | j                  ||      }|j                  dk(  r|j                         }|j                  di g      d   j                  di       j                  dd      j                         }|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 DeepSeek API with direct HTTP requestsF%DeepSeek 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 as   SQL syntax.
2. Focus on writing efficient queries with proper joins and conditions.
3. CAUTION: 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Bearer zContent-TypeAuthorizationsystemrolecontentuser皙?r   messagestemperatureheadersjson   choicesr   messagerl   )zi cannotz	i'm sorryzsorry,Tr8   r7   )rb   	sql_queryr   http_successzFailed to generate SQL query)rb   rc   r   ry   DeepSeek API error:  - z$Error generating SQL with DeepSeek: zFailed to generate SQL query: N)r   
model_typer[   rG   r   r   r   postr   status_codert   r   striplower
startswithtextr   rc   r   r   )r   r]   r#   r^   r_   rI   db_config_infokeyvaluesystem_messageuser_messagers   dataresponseresultrx   error_messager    s                     r"   generate_sqlzDeepSeekModel.generate_sql   s     @   99+F 8N'oo/ 8
UBse2eWB"778 NgY W  y !)	, +7) 4       /&t||n5
 ZZ!n=L9 
2	}})) * H ##s*! #JJy2$7:>>y"MQQR[]_`ffh	 Y__%6%A%ABf%g $(%.$(OO#4Btzzl!!D(,	  $)!*!L.L$(OO#4Btzzl!!D(,	  #7x7K7K6LCPXP]P] _]+$*!__$)	   	LL?AxHI 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d| j                   d}| j                  d|dd|dgdd}	 | j
                  j                  | j                  ||      }	|	j                  dk(  r|	j                         }
|
j                  di g      d   j                  di       j                  dd      j                         }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)1zLAnalyze database explain plan and provide recommendations using DeepSeek APIFra   )rb   rc   recommendations   )indentz?You are an expert database performance analyst specializing in a$   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. Consider indexes, join methods, table scans, and other relevant factors.
4. Explain why each recommendation would improve performance.
5. Rate the overall efficiency of the query on a scale of 1-10.
6. 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   ri   rj   rm   rn   ro   rr   ru   rv   r   rw   rl   r-   r.   Nrating:c              3   8   K   | ]  }t        |      v   y wN)r   ).0ilines     r"   	<genexpr>z5DeepSeekModel.analyze_explain_plan.<locals>.<genexpr>@  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 DeepSeek: z Failed to analyze explain plan: )r   rt   dumpsr   r   r   r}   r   r~   r   r   splitr   anyrangeisdigitintr   rE   r|   r   r   rc   r   r   )r   r   r^   rx   explain_textr   r   rs   r   r   r   analysis_textr   r   linescurrent_sectioncurrent_recommendationrating_textwordr   r    r   s                        @r"   analyze_explain_planz"DeepSeekModel.analyze_explain_plan   sr     @#%  zz,q9 ]]d\e f9 < +7) 4    '*  /&t||n5
 ZZ!n=L9 
W	}})) * H ##s*! !'

9rd ;A > B B9b Q U UV_ac d j j l #%$%! &++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@  #7x7K7K6LCPXP]P] _]+$*') O! V  	LLGAxPQ ;CF8D#% 	sW   (C/J0 AJ)-J)
'J0 25J0 )J0 -AJ0 26J0 )J-+J0 0	K692K1+K61K6r   )__name__
__module____qualname____doc__r|   r   r   r   r   r[   r	   r   r   r
   r   __classcell__)r!   s   @r"   r   r      s    BJU*X+T#s(^ X+ X+t k3 kT#s(^ kc k^fgkloqtltgu^v k  CG  HK  MP  HP  CQ k kZ Lc3h L# LZ] Lbfgjlogobp L  Lr\   r   )loggingtypingr   r   r   r   flaskr   rt   r   app.models.ai_model_baser   app.utils.redis_cacher	   r
   	getLoggerr   r   r    r\   r"   <module>r      s@     , ,     0 R			8	$oK or\   