o
    i+                     @   s   d Z ddlZddlmZ ddlmZmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZmZmZmZ ddlmZ dd	lmZ eG d
d dZG dd deZG dd deZG dd deZdS )z;OpenAI LLM service implementation with context aggregators.    N)	dataclass)AnyOptional)	NOT_GIVEN)FunctionCallCancelFrameFunctionCallInProgressFrameFunctionCallResultFrameUserImageRawFrame)LLMAssistantAggregatorParamsLLMAssistantContextAggregatorLLMUserAggregatorParamsLLMUserContextAggregator)OpenAILLMContext)BaseOpenAILLMServicec                   @   s6   e Zd ZU dZded< ded< dddZdd	d
ZdS )OpenAIContextAggregatorPaira  Pair of OpenAI context aggregators for user and assistant messages.

    .. deprecated:: 0.0.99
        `OpenAIContextAggregatorPair` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.

    Parameters:
        _user: User context aggregator for processing user messages.
        _assistant: Assistant context aggregator for processing assistant messages.
    OpenAIUserContextAggregator_user OpenAIAssistantContextAggregator
_assistantreturnc                 C      | j S )zmGet the user context aggregator.

        Returns:
            The user context aggregator instance.
        )r   self r   O/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/openai/llm.pyuser1      z OpenAIContextAggregatorPair.userc                 C   r   )zwGet the assistant context aggregator.

        Returns:
            The assistant context aggregator instance.
        )r   r   r   r   r   	assistant9   r   z%OpenAIContextAggregatorPair.assistantN)r   r   )r   r   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   r      s   
 
r   c                
       s|   e Zd ZdZejZddddddee dee deej dee f fdd	Z	e
 e d
dede
dedefddZ  ZS )OpenAILLMServicezOpenAI LLM service implementation.

    Provides a complete OpenAI LLM service with context aggregation support.
    Uses the BaseOpenAILLMService for core functionality and adds OpenAI-specific
    context aggregator creation.
    N)modelservice_tierparamssettingsr$   r%   r&   r'   c                   s   | j ddtttttdttddi d}|dur| dd ||_|dur/|s/|jtur/|p.|j}|dur`| d |s`|j|_|j|_|j|_|j|_|j	|_	|j
|_
|j|_t|jtr`|j|_|duri|| t jd||d| dS )	a  Initialize OpenAI LLM service.

        Args:
            model: The OpenAI model name to use. Defaults to "gpt-4.1".

                .. deprecated:: 0.0.105
                    Use ``settings=OpenAILLMService.Settings(model=...)`` instead.

            service_tier: Service tier to use (e.g., "auto", "flex", "priority").
            params: Input parameters for model configuration.

                .. deprecated:: 0.0.105
                    Use ``settings=OpenAILLMService.Settings(...)`` instead.

            settings: Runtime-updatable settings. When provided alongside deprecated
                parameters, ``settings`` values take precedence.
            **kwargs: Additional arguments passed to the parent BaseOpenAILLMService.
        zgpt-4.1NF)r$   system_instructionfrequency_penaltypresence_penaltyseedtemperaturetop_ptop_k
max_tokensmax_completion_tokensfilter_incomplete_user_turnsuser_turn_completion_configextrar$   r&   )r%   r'   r   )Settingsr   "_warn_init_param_moved_to_settingsr$   r%   r)   r*   r+   r,   r-   r/   r0   
isinstancer3   dictapply_updatesuper__init__)r   r$   r%   r&   r'   kwargsdefault_settings	__class__r   r   r:   L   sF   


zOpenAILLMService.__init__)user_paramsassistant_paramscontextr?   r@   r   c                C   s2   | |   t||d}t||d}t||dS )a  Create OpenAI-specific context aggregators.

        Creates a pair of context aggregators optimized for OpenAI's message format,
        including support for function calls, tool usage, and image handling.

        Args:
            context: The LLM context to create aggregators for.
            user_params: Parameters for user message aggregation.
            assistant_params: Parameters for assistant message aggregation.

        Returns:
            OpenAIContextAggregatorPair: A pair of context aggregators, one for
            the user and one for the assistant, encapsulated in an
            OpenAIContextAggregatorPair.

        .. deprecated:: 0.0.99
            `create_context_aggregator()` is deprecated and will be removed in a future version.
            Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
            See `OpenAILLMContext` docstring for migration guide.
        )r&   )r   r   )set_llm_adapterget_llm_adapterr   r   r   )r   rA   r?   r@   r   r   r   r   r   create_context_aggregator   s   z*OpenAILLMService.create_context_aggregator)r   r   r    r!   r   r4   r   strInputParamsr:   r   r
   r   r   rD   __classcell__r   r   r=   r   r#   B   s6    Mr#   c                   @   s   e Zd ZdZdS )r   a  OpenAI-specific user context aggregator.

    Handles aggregation of user messages for OpenAI LLM services.
    Inherits all functionality from the base LLMUserContextAggregator.

    .. deprecated:: 0.0.99
        `OpenAIUserContextAggregator` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    N)r   r   r    r!   r   r   r   r   r      s    r   c                   @   s^   e Zd ZdZdefddZdefddZdefddZ	d	e
d
e
defddZdefddZdS )r   a  OpenAI-specific assistant context aggregator.

    Handles aggregation of assistant messages for OpenAI LLM services,
    with specialized support for OpenAI's function calling format,
    tool usage tracking, and image message handling.

    .. deprecated:: 0.0.99
        `OpenAIAssistantContextAggregator` is deprecated and will be removed in a future version.
        Use the universal `LLMContext` and `LLMContextAggregatorPair` instead.
        See `OpenAILLMContext` docstring for migration guide.
    framec                    sJ   | j d|j|jt|jdddgd | j dd|jd d	S )
zHandle a function call in progress.

        Adds the function call to the context with an IN_PROGRESS status
        to track ongoing function execution.

        Args:
            frame: Frame containing function call progress information.
        r   )name	argumentsfunction)idrK   type)role
tool_callstoolIN_PROGRESS)rN   contenttool_call_idN)_contextadd_messagerS   function_namejsondumpsrJ   r   rH   r   r   r    handle_function_call_in_progress   s$   	
zAOpenAIAssistantContextAggregator.handle_function_call_in_progressc                    sP   |j rtj|j dd}| |j|j|I dH  dS | |j|jdI dH  dS )zHandle the result of a function call.

        Updates the context with the function call result, replacing any
        previous IN_PROGRESS status.

        Args:
            frame: Frame containing the function call result.
        F)ensure_asciiN	COMPLETED)resultrW   rX   _update_function_call_resultrV   rS   )r   rH   r]   r   r   r   handle_function_call_result   s   	
z<OpenAIAssistantContextAggregator.handle_function_call_resultc                    s   |  |j|jdI dH  dS )zHandle a cancelled function call.

        Updates the context to mark the function call as cancelled.

        Args:
            frame: Frame containing the function call cancellation information.
        	CANCELLEDN)r^   rV   rS   rY   r   r   r   handle_function_call_cancel	  s   
z<OpenAIAssistantContextAggregator.handle_function_call_cancelrV   rS   r]   c                    s<   | j jD ]}|d dkr|d r|d |kr||d< qd S )NrN   rP   rS   rR   )rT   messages)r   rV   rS   r]   messager   r   r   r^     s   z=OpenAIAssistantContextAggregator._update_function_call_resultc                    s@   |  |jj|jjdI dH  | jj|j|j|j|jj	d dS )a
  Handle a user image frame from a function call request.

        Marks the associated function call as completed and adds the image
        to the context for processing.

        Args:
            frame: Frame containing the user image and request context.
        r\   N)formatsizeimagetext)
r^   requestrV   rS   rT   add_image_frame_messagerd   re   rf   rA   rY   r   r   r   handle_user_image_frame   s   	

z8OpenAIAssistantContextAggregator.handle_user_image_frameN)r   r   r    r!   r   rZ   r   r_   r   ra   rE   r   r^   r	   rj   r   r   r   r   r      s     
r   )r!   rW   dataclassesr   typingr   r   openair   pipecat.frames.framesr   r   r   r	   +pipecat.processors.aggregators.llm_responser
   r   r   r   1pipecat.processors.aggregators.openai_llm_contextr    pipecat.services.openai.base_llmr   r   r#   r   r   r   r   r   r   <module>   s   "w