o
    U|%i*                     @   s   d Z ddlZddlmZmZmZ zddlmZ W n ey'   ddl	mZ Y nw ddl
mZ ddlmZmZmZ ddlmZ G dd	 d	eZdS )
z{GenAI LLM integration utilities for MySQL Connector/Python.

Provides MyLLM wrapper that issues ML_GENERATE calls via SQL.
    N)AnyListOptional)LLM)PrivateAttr)atomic_transactionexecute_sqlformat_value_sql)MySQLConnectionAbstractc                	       s   e Zd ZU dZe Zeed< G dd dZdef fddZ		dd	e
d
eee
  dede
fddZedefddZede
fddZ  ZS )MyLLMa  
    Custom Large Language Model (LLM) interface for MySQL HeatWave.

    This class wraps the generation functionality provided by HeatWave LLMs,
    exposing an interface compatible with common LLM APIs for text generation.
    It provides full support for generative queries and limited support for
    agentic queries.

    Attributes:
        _db_connection (MySQLConnectionAbstract):
            Underlying MySQL connector database connection.
    _db_connectionc                   @   s   e Zd ZdZdZdS )zMyLLM.ConfigaL  
        Pydantic config for the model.

        By default, LangChain (through Pydantic BaseModel) does not allow
        setting or storing undeclared attributes such as _db_connection.
        Setting extra = "allow" makes it possible to store extra attributes
        on the class instance, which is required for MyLLM.
        allowN)__name__
__module____qualname____doc__extra r   r   V/home/air/sos_test/back/venv/lib/python3.10/site-packages/mysql/ai/genai/generation.pyConfig@   s    	r   db_connectionc                    s   t    || _dS )aS  
        Initialize the MyLLM instance with an active MySQL database connection.

        Args:
            db_connection: A MySQL connection object used to run LLM queries.

        Notes:
            The db_connection is stored as a private attribute via object.__setattr__,
            which is compatible with Pydantic models.
        N)super__init__r   )selfr   	__class__r   r   r   L   s   

zMyLLM.__init__Npromptstopkwargsreturnc           
      K   s   |  }|dur||d< t|\}}t| j%}d| d}t|||g|R d t| d d }	W d   |	S 1 s?w   Y  |	S )ac  
        Generate a text completion from the LLM for a given input prompt.

        References:
            https://dev.mysql.com/doc/heatwave/en/mys-hwgenai-ml-generate.html
                A full list of supported options (specified by kwargs) can be found under "options"

        Args:
            prompt: The input prompt string for the language model.
            stop: Optional list of stop strings to support agentic and chain-of-thought
                  reasoning workflows.
            **kwargs: Additional keyword arguments providing generation options to
                      the LLM (these are serialized to JSON and passed to the HeatWave syscall).

        Returns:
            The generated model output as a string.
            (The actual completion does NOT include the input prompt.)

        Raises:
            DatabaseError:
                If provided options are invalid or unsupported.
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Implementation Notes:
            - Serializes kwargs into a SQL-compatible JSON string.
            - Calls the LLM stored procedure using a database cursor context.
            - Uses `sys.ML_GENERATE` on the server to produce the model output.
            - Expects the server response to be a JSON object with a 'text' key.
        Nstop_sequenceszSELECT sys.ML_GENERATE("%s", z);)paramsr   text)copyr	   r   r   r   jsonloadsfetchone)
r   r   r   r   optionsoptions_placeholderoptions_paramscursorgenerate_queryllm_responser   r   r   _call[   s   $
zMyLLM._callc                 C   s   ddiS )z
        Return a dictionary of params that uniquely identify this LLM instance.

        Returns:
            dict: Dictionary of identifier parameters (should include
                model_name for tracing/caching).
        
model_namemysql_heatwave_llmr   r   r   r   r   _identifying_params   s   
zMyLLM._identifying_paramsc                 C   s   dS )z
        Get the type name of this LLM implementation.

        Returns:
            A string identifying the LLM provider (used for logging or metrics).
        r/   r   r0   r   r   r   	_llm_type   s   zMyLLM._llm_type)N)r   r   r   r   r   r   r
   __annotations__r   r   strr   r   r   r-   propertydictr1   r2   __classcell__r   r   r   r   r   0   s&   
 

2r   )r   r$   typingr   r   r   #langchain_core.language_models.llmsr   ImportErrorlangchain.llms.basepydanticr   mysql.ai.utilsr   r   r	   mysql.connector.abstractsr
   r   r   r   r   r   <module>   s   