o
    h'                     @  sd   d dl mZ d dlZd dlZd dlZd dlZd dlmZ ddlm	Z	 ddl
mZ G dd	 d	eZdS )
    )annotationsN)Path   )TResponseInputItem   )
SessionABCc                   @  sj   e Zd ZdZ			d%d&ddZd'ddZd(ddZd)d*ddZd+ddZd,dd Z	d-d!d"Z
d-d#d$ZdS ).SQLiteSessionzSQLite-based implementation of session storage.

    This implementation stores conversation history in a SQLite database.
    By default, uses an in-memory database that is lost when the process ends.
    For persistent storage, provide a file path.
    :memory:agent_sessionsagent_messages
session_idstrdb_path
str | Pathsessions_tablemessages_tablec                 C  s   || _ || _|| _|| _t | _t | _t	|dk| _
| j
r6tjddd| _| jd | | j dS tjt	| jdd}|d | | |  dS )a  Initialize the SQLite session.

        Args:
            session_id: Unique identifier for the conversation session
            db_path: Path to the SQLite database file. Defaults to ':memory:' (in-memory database)
            sessions_table: Name of the table to store session metadata. Defaults to
                'agent_sessions'
            messages_table: Name of the table to store message data. Defaults to 'agent_messages'
        r	   Fcheck_same_threadPRAGMA journal_mode=WALN)r   r   r   r   	threadinglocal_localLock_lockr   _is_memory_dbsqlite3connect_shared_connectionexecute_init_db_for_connectionclose)selfr   r   r   r   	init_conn r#   ]/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/memory/sqlite_session.py__init__   s   



zSQLiteSession.__init__returnsqlite3.Connectionc                 C  sl   | j r| jS t| jdstjt| jdd| j_| jj	d t
| jjtjs2J dt| jj | jjS )zGet a database connection.
connectionFr   r   z!Expected sqlite3.Connection, got )r   r   hasattrr   r   r   r   r   r(   r   
isinstance
Connectiontyper!   r#   r#   r$   _get_connection:   s   
zSQLiteSession._get_connectionconnNonec                 C  sX   | d| j d | d| j d| j d | d| j d| j d |  dS )	z9Initialize the database schema for a specific connection.z(
            CREATE TABLE IF NOT EXISTS z (
                session_id TEXT PRIMARY KEY,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        a   (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                message_data TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (session_id) REFERENCES zJ (session_id)
                    ON DELETE CASCADE
            )
        z,
            CREATE INDEX IF NOT EXISTS idx_z_session_id
            ON z" (session_id, created_at)
        N)r   r   r   commit)r!   r/   r#   r#   r$   r   L   s(   
z%SQLiteSession._init_db_for_connectionNlimit
int | Nonelist[TResponseInputItem]c                   s     fdd}t |I dH S )aO  Retrieve the conversation history for this session.

        Args:
            limit: Maximum number of items to retrieve. If None, retrieves all items.
                   When specified, returns the latest N items in chronological order.

        Returns:
            List of input items representing the conversation history
        c               
     s     } jr
jnt V  d u r!| dj djf}n| dj dj f}| } d ur=t	t
|}g }|D ]\}zt|}|| W qA tjyZ   Y qAw |W  d    S 1 sgw   Y  d S )Nz2
                        SELECT message_data FROM zr
                        WHERE session_id = ?
                        ORDER BY created_at ASC
                    z
                        WHERE session_id = ?
                        ORDER BY created_at DESC
                        LIMIT ?
                        )r.   r   r   r   r   r   r   r   fetchalllistreversedjsonloadsappendJSONDecodeError)r/   cursorrowsitemsmessage_dataitemr2   r!   r#   r$   _get_items_syncy   s8   



$z0SQLiteSession.get_items.<locals>._get_items_syncNasyncio	to_thread)r!   r2   rB   r#   rA   r$   	get_itemsn   s   *zSQLiteSession.get_itemsr>   c                   s,    sdS  fdd}t |I dH  dS )zAdd new items to the conversation history.

        Args:
            items: List of input items to add to the history
        Nc                    s     } jr
jnt ; | dj djf fdd D }| dj	 d| | dj djf | 
  W d    d S 1 sLw   Y  d S )	Nz+
                    INSERT OR IGNORE INTO z) (session_id) VALUES (?)
                c                   s   g | ]
} j t|fqS r#   )r   r8   dumps).0r@   r-   r#   r$   
<listcomp>   s    zDSQLiteSession.add_items.<locals>._add_items_sync.<locals>.<listcomp>z!
                    INSERT INTO z: (session_id, message_data) VALUES (?, ?)
                z
                    UPDATE zq
                    SET updated_at = CURRENT_TIMESTAMP
                    WHERE session_id = ?
                )r.   r   r   r   r   r   r   r   executemanyr   r1   )r/   r?   r>   r!   r#   r$   _add_items_sync   s.   
	"z0SQLiteSession.add_items.<locals>._add_items_syncrC   )r!   r>   rL   r#   rK   r$   	add_items   s
   !zSQLiteSession.add_itemsTResponseInputItem | Nonec                   s    fdd}t |I dH S )zRemove and return the most recent item from the session.

        Returns:
            The most recent item if it exists, None if the session is empty
        c               	     s      }  jr
 jnt J | d j d j d jf}| }| 	  |rO|d }zt
|}|W W  d    S  t
jyN   Y W d    d S w 	 W d    d S 1 s[w   Y  d S )Nz!
                    DELETE FROM zI
                    WHERE id = (
                        SELECT id FROM z
                        WHERE session_id = ?
                        ORDER BY created_at DESC
                        LIMIT 1
                    )
                    RETURNING message_data
                    r   )r.   r   r   r   r   r   r   r   fetchoner1   r8   r9   r;   )r/   r<   resultr?   r@   r-   r#   r$   _pop_item_sync   s0   

$z.SQLiteSession.pop_item.<locals>._pop_item_syncNrC   )r!   rQ   r#   r-   r$   pop_item   s    zSQLiteSession.pop_itemc                   s"    fdd}t |I dH  dS )z!Clear all items for this session.c                    s~      }  jr
 jnt ' | d j d jf | d j d jf | 	  W d    d S 1 s8w   Y  d S )NzDELETE FROM z WHERE session_id = ?)
r.   r   r   r   r   r   r   r   r   r1   )r/   r-   r#   r$   _clear_session_sync   s   
"z8SQLiteSession.clear_session.<locals>._clear_session_syncNrC   )r!   rS   r#   r-   r$   clear_session   s   zSQLiteSession.clear_sessionc                 C  sB   | j rt| dr| j  dS dS t| jdr| jj  dS dS )zClose the database connection.r   r(   N)r   r)   r   r    r   r(   r-   r#   r#   r$   r      s   
zSQLiteSession.close)r	   r
   r   )r   r   r   r   r   r   r   r   )r&   r'   )r/   r'   r&   r0   )N)r2   r3   r&   r4   )r>   r4   r&   r0   )r&   rN   )r&   r0   )__name__
__module____qualname____doc__r%   r.   r   rF   rM   rR   rT   r    r#   r#   r#   r$   r      s    

%
"
7
,
)r   )
__future__r   rD   r8   r   r   pathlibr   r>   r   sessionr   r   r#   r#   r#   r$   <module>   s    