
    qi+                         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mZ dd
lmZ e G d d             Z G d de      Z G d de      Z G d de      Zy)z;OpenAI LLM service implementation with context aggregators.    N)	dataclass)AnyOptional)	NOT_GIVEN)FunctionCallCancelFrameFunctionCallInProgressFrameFunctionCallResultFrameUserImageRawFrame)LLMAssistantAggregatorParamsLLMAssistantContextAggregatorLLMUserAggregatorParamsLLMUserContextAggregator)OpenAILLMContext)BaseOpenAILLMServiceOpenAILLMSettings)_warn_deprecated_paramc                   6    e Zd ZU dZded<   ded<   d	dZd
dZy)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
_assistantc                     | j                   S )zmGet the user context aggregator.

        Returns:
            The user context aggregator instance.
        )r   selfs    M/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/openai/llm.pyuserz OpenAIContextAggregatorPair.user2   s     zz    c                     | j                   S )zwGet the assistant context aggregator.

        Returns:
            The assistant context aggregator instance.
        )r   r   s    r   	assistantz%OpenAIContextAggregatorPair.assistant:   s     r   N)returnr   )r!   r   )__name__
__module____qualname____doc____annotations__r   r     r   r   r   r       s    
 )(22r   r   c            
            e Zd ZdZddddddee   dee   deej                     dee   f fdZ	 e
        e       d	d
ede
dedefdZ x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                   t        ddt        t        t        t        t        dt        t        ddi       }|t        dt         d       ||_        |$|s"|j                  t        ur|xs |j                  }|t        dt                |s|j
                  |_        |j                  |_        |j                  |_        |j                  |_        |j                  |_	        |j                  |_
        |j                  |_        t        |j                  t              r|j                  |_        ||j                  |       t!        | D  d||d| y)	a  Initialize OpenAI LLM service.

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

                .. deprecated:: 0.0.105
                    Use ``settings=OpenAILLMSettings(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=OpenAILLMSettings(...)`` 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'   )r   r   r   r*   r+   r0   r1   r2   r3   r4   r6   r7   
isinstancer:   dictapply_updatesuper__init__)r   r*   r+   r,   r-   kwargsdefault_settings	__class__s          r   r?   zOpenAILLMService.__init__K   sA   8 -#'&! "+).(,
" "7,=wG%*" h63F3Fi3W'>6+>+>L "8->?5;5M5M 24:4K4K 1(. %/5/A/A ,)/ &.4.?.? +9?9U9U 6fllD1-3\\$* ))(3Xl=MXQWXr   )user_paramsassistant_paramscontextrC   rD   r!   c                    |j                  | j                                t        ||      }t        ||      }t	        ||      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   rE   rC   rD   r   r    s         r   create_context_aggregatorz*OpenAILLMService.create_context_aggregator   sC    6 	 4 4 67 +7;G4WEUV	*)LLr   )r"   r#   r$   r%   r   strr   InputParamsr   r?   r   r   r   r   rI   __classcell__)rB   s   @r   r)   r)   C   s      $&*=A04GY }GY sm	GY
 -99:GY ,-GYZ 0G/H9U9W!M!!M -	!M
 7!M 
%!Mr   r)   c                       e Zd ZdZy)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   r   c                   T    e Zd ZdZdefdZdefdZdefdZ	de
de
defd	Zdefd
Zy)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                   K   | j                   j                  d|j                  |j                  t	        j
                  |j                        dddgd       | j                   j                  dd|j                  d       y	w)
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)idrS   type)role
tool_callstoolIN_PROGRESS)rV   contenttool_call_idN)_contextadd_messager[   function_namejsondumpsrR   r   rO   s     r    handle_function_call_in_progresszAOpenAIAssistantContextAggregator.handle_function_call_in_progress   s      	!!# $00$)$7$7)-EOO)D% !+		
 	!!( % 2 2	
s   BBc                 (  K   |j                   rOt        j                  |j                         }| j                  |j                  |j
                  |       d{    y| j                  |j                  |j
                  d       d{    y7 57 w)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.
        N	COMPLETED)resultr_   r`   _update_function_call_resultr^   r[   )r   rO   re   s      r   handle_function_call_resultz<OpenAIAssistantContextAggregator.handle_function_call_result   s}      <<ZZ-F33E4G4GI[I[]cddd33##U%7%7   es$   ABB/BB	BBc                 n   K   | j                  |j                  |j                  d       d{    y7 w)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)rf   r^   r[   ra   s     r   handle_function_call_cancelz<OpenAIAssistantContextAggregator.handle_function_call_cancel  s3      //!3!3[
 	
 	
s   +535r^   r[   re   c                 |   K   | j                   j                  D ]  }|d   dk(  s|d   s|d   |k(  s||d<   ! y w)NrV   rX   r[   rZ   )r\   messages)r   r^   r[   re   messages        r   rf   z=OpenAIAssistantContextAggregator._update_function_call_result  sL      }}-- 	,G6)N+N+|;%+	"	,s   "<<<<c                 8  K   | j                  |j                  j                  |j                  j                  d       d{    | j                  j                  |j                  |j                  |j                  |j                  j                         y7 Vw)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.
        rd   N)formatsizeimagetext)
rf   requestr^   r[   r\   add_image_frame_messagero   rp   rq   rE   ra   s     r   handle_user_image_framez8OpenAIAssistantContextAggregator.handle_user_image_frame  s{      //MM'')C)C[
 	
 	
 	--<<++&&	 	. 	
	
s   ?BBABN)r"   r#   r$   r%   r   rb   r	   rg   r   rj   rJ   r   rf   r
   ru   r'   r   r   r   r      sY    

<W 
@7N "

7N 

	, 	,03	,=@	,
3D 
r   r   )r%   r_   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   pipecat.services.settingsr   r   r)   r   r   r'   r   r   <module>r~      s    B  !      O T <   DrM+ rMj	": 	 h
'D h
r   