
    qi                         d Z ddlmZmZ ddlmZ ddlmZ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 ddlmZ  G d de      Zy# e$ r"Z ej.                  d	        ed
e       dZ[ww xY w)z,Langchain integration processor for Pipecat.    )OptionalUnion)logger)FrameLLMContextFrameLLMFullResponseEndFrameLLMFullResponseStartFrame	TextFrame)OpenAILLMContextFrame)FrameDirectionFrameProcessor)AIMessageChunk)RunnablezLIn order to use Langchain, you need to `pip install pipecat-ai[langchain]`. zMissing module: Nc                   ~     e Zd ZdZddedef fdZdefdZdede	f fd	Z
ed
eeef   defd       Zd
efdZ xZS )LangchainProcessora.  Processor that integrates Langchain runnables with Pipecat's frame pipeline.

    This processor takes LLM message frames, extracts the latest user message,
    and processes it through a Langchain runnable chain. The response is streamed
    back as text frames with appropriate response markers.
    chaintranscript_keyc                 L    t         |           || _        || _        d| _        y)zInitialize the Langchain processor.

        Args:
            chain: The Langchain runnable to use for processing messages.
            transcript_key: The key to use when passing input to the chain.
        N)super__init___chain_transcript_key_participant_id)selfr   r   	__class__s      Y/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/processors/frameworks/langchain.pyr   zLangchainProcessor.__init__'   s'     	-.2    participant_idc                     || _         y)zSet the participant ID for session tracking.

        Args:
            participant_id: The participant ID to use for session configuration.
        N)r   )r   r   s     r   set_participant_idz%LangchainProcessor.set_participant_id3   s      .r   frame	directionc                   K   t         |   ||       d{    t        |t        t        f      rt        j                  d|        t        |t              r|j                  j                  n|j                  j                         }|d   d   }| j                  |j                                d{    y| j                  ||       d{    y7 7 "7 	w)zProcess incoming frames and handle LLM message frames.

        Args:
            frame: The incoming frame to process.
            direction: The direction of frame flow in the pipeline.
        NzGot transcription frame content)r   process_frame
isinstancer   r   r   debugcontextmessagesget_messages_ainvokestrip
push_frame)r   r!   r"   r*   textr   s        r   r&   z LangchainProcessor.process_frame;   s      g#E9555eo/DEF LL3E7;< e%:; &&]]//1 
 !Y/D--

---//%333 	6 .3s4   CCBC4C5CCCCCr/   returnc                 X    | xt         d x\    | S  t        d x\   | j                  S  	 y)zExtract token value from various text types.

        Args:
            text: The text or message chunk to extract value from.

        Returns:
            The extracted string value.
          )strr   r%   )r/   s    r   __get_token_valuez$LangchainProcessor.__get_token_valueS   s3      !||# "r   c                   K   t        j                  d|        | j                  t                      d{    	 | j                  j                  | j                  |idd| j                  ii      2 3 d{   }t        | j                  |            }d|_
        | j                  |       d{    D7 7 A7 	6 nW# t        $ r t        j                  |  d       Y n4t        $ r)}| j                  d| |	       d{  7   Y d}~nd}~ww xY w| j                  t                      d{  7   y# | j                  t                      d{  7   w xY ww)
z5Invoke the Langchain runnable with the provided text.zInvoking chain with Nconfigurable
session_id)configTz! generator was closed prematurelyzUnknown error occurred: )	error_msg	exception)r   r(   r.   r	   r   astreamr   r   r
   $_LangchainProcessor__get_token_valueincludes_inter_frame_spacesGeneratorExitwarning	Exception
push_errorr   )r   r/   tokenr!   es        r   r,   zLangchainProcessor._ainvokee   s?    +D623oo79:::	=#{{22%%t,&t7K7K(LM  3   - -e "$"8"8"?@481ooe,,, 	;- -   	GNNdV#DEF 	Y//.Fqc,JVW/XXX	Y //"9";<<<$//"9";<<<s   5E!B8E!7C  4B>8B:9B><6C  2B<3C  8E!:B><C  >C  ?D:  !D!D: #D+DDD
D: DD: E!3D64E!:EEEE!)input)__name__
__module____qualname____doc__r   r4   r   r    r   r   r&   staticmethodr   r   r=   r,   __classcell__)r   s   @r   r   r      sr    
3h 
3 
3. .4 4> 40 c>&9 : s  "=3 =r   r   )rI   typingr   r   logurur   pipecat.frames.framesr   r   r   r	   r
   1pipecat.processors.aggregators.openai_llm_contextr   "pipecat.processors.frame_processorr   r   langchain_core.messagesr   langchain_core.runnablesr   ModuleNotFoundErrorrD   errorrA   r   r2   r   r   <module>rU      sp    3 "   T M,61W= W=  ,FLL_`
&qc*
++,s   A A-A((A-