
    qi                         d Z ddl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 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j0                  d
        ede       dZ[ww xY w)zStrands Agent integration for Pipecat.

This module provides integration with Strands Agents for handling conversational AI
interactions. It supports both single agent and multi-agent graphs.
    )Optional)logger)FrameLLMContextFrameLLMFullResponseEndFrameLLMFullResponseStartFrameLLMTextFrame)LLMTokenUsage)OpenAILLMContextFrame)FrameDirectionFrameProcessor)Agent)GraphzIIn order to use Strands Agents, you need to `pip install strands-agents`.zMissing module: Nc                        e Zd ZdZ	 	 	 ddee   dee   dee   f fdZde	de
f fdZd	efd
ZdefdZdededefdZ xZS )StrandsAgentsProcessora  Processor that integrates Strands Agents with Pipecat's frame pipeline.

    This processor takes LLM message frames, extracts the latest user message,
    and processes it through either a single Strands Agent or a multi-agent Graph.
    The response is streamed back as text frames with appropriate response markers.

    Supports both single agent streaming and graph-based multi-agent workflows.
    agentgraphgraph_exit_nodec                     t         |           || _        || _        || _        | j                  s| j                  sJ d       | j                  r| j                  sJ d       yy)a  Initialize the Strands Agents processor.

        Args:
            agent: The Strands Agent to use for single-agent processing.
            graph: The Strands multi-agent Graph to use for graph-based processing.
            graph_exit_node: The exit node name when using graph-based processing.

        Raises:
            AssertionError: If neither agent nor graph is provided, or if graph is
                          provided without a graph_exit_node.
        z&Either agent or graph must be providedz5graph_exit_node must be provided if graph is providedN)super__init__r   r   r   )selfr   r   r   	__class__s       ^/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/processors/frameworks/strands_agents.pyr   zStrandsAgentsProcessor.__init__(   s`    " 	

.zzTZZQ)QQ'::''`)``'     frame	directionc                 V  K   t         |   ||       d{    t        |t        t        f      rV|j
                  j                         }|r9|d   }| j                  t        |d         j                                d{    y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.
        Ncontent)r   process_frame
isinstancer   r   contextget_messages_ainvokestrstrip
push_frame)r   r   r   messageslast_messager   s        r   r!   z$StrandsAgentsProcessor.process_frameC   s      g#E9555eo/DEF}}113H'|mmCY(?$@$F$F$HIII  //%333 	6
 J3s4   B)B#A)B)B%B)B'B)%B)'B)textc           
        K   t        j                  d|        d}	 | j                  t                      d{    | j	                          d{    | j                          d{    | j                  r~| j                  j                  |       d{   }|r| j                          d{    d}	 |j                  | j                     }t        j                  d|        |j                         D ]  }t        |dd      }t        |t              rRd|v rN|d   D ]F  }t        |t              sd|v s| j                  t        t!        |d                      d{    H | j#                  |j$                  j&                  j)                  d	d
      |j$                  j&                  j)                  dd
      |j$                  j&                  j)                  dd
             d{     n| j.                  j1                  |      2 3 d{   }	t        |	t              rNd|	v rJ| j                  t        t!        |	d                      d{    |r| j                          d{    d}t        |	t              sxd|	v s}d|	d   v sd|	d   d   v s|	d   d   d   }
| j#                  |
j)                  d	d
      |
j)                  dd
      |
j)                  dd
             d{    |r| j                          d{    d}| j7                          d{    | j                  t9                      d{    y7 7 7 7 7 7 7 s# t*        $ r"}t        j,                  d|        Y d}~d}~ww xY w7 |7 =7 &7 6 # t2        $ r t        j,                  |  d       Y t*        $ r)}| j5                  d| |       d{  7   Y d}~d}~ww xY w7 7 7 # |r| j                          d{  7   d}| j7                          d{  7   | j                  t9                      d{  7   w xY ww)zInvoke the Strands agent with the provided text and stream results as Pipecat frames.

        Args:
            text: The user input text to process through the agent or graph.
        zInvoking Strands agent with: TNFzNode result: messager    r+   inputTokensr   outputTokenstotalTokensz-Failed to extract messages from GraphResult: dataeventmetadatausagez! generator was closed prematurelyzUnknown error occurred: )	error_msg	exception)r   debugr(   r   start_processing_metricsstart_ttfb_metricsr   invoke_asyncstop_ttfb_metricsresultsr   get_agent_resultsgetattrr"   dictr	   r&   _report_usage_metricsmetricsaccumulated_usageget	Exceptionwarningr   stream_asyncGeneratorExit
push_errorstop_processing_metricsr   )r   r+   ttfb_trackinggraph_resultnode_resultagent_resultr-   block	parse_errr2   r4   es               r   r%   zStrandsAgentsProcessor._ainvokeS   s     	4TF;<=	=//";"=>>>//111))+++zz%)ZZ%<%<T%BB 00222$)M`"."6"6t7K7K"LKLL=!>?(3(E(E(G "),	4"H%gt4g9M)0); \#-eT#:v*.//,s5QW=GY:Z*[$[$[\ #88(00BBFF}VWX(00BBFF~WXY(00BBFF}VWX  " $(::#:#:4#@  %!%.6U?"ool3uV};M.NOOO("&"8"8":::,1M #5$/#u,&%.8"eGnZ&@@$)'N:$>w$GE"&"<"< %		- ; %		.! < %		- ;#   ,,... %..000//"9";<<<y ?1+  C2 %\
 ! `NN%RS\R]#^__` P:! $A*  	GNNdV#DEF 	Y//.Fqc,JVW/XXX	Y /0<	 ,,... %..000//"9";<<<s  QN" MN" MN" *M+/N" MN" 4M5N" <A=M' :M' ?)M' (M!)BM' 1M$2M' 8N" N NN >N" NN" 5N6N" N" N" 
N" %AN" 6N7N" <QO9Q+O;, QO=QN" N" N" N" N" !M' $M' '	N0NN" NN" N N" N" N"  N" "!O6O? O6O1&O)'O1,O? 1O66O? 9Q;Q=Q?QPQ0P31!QQQQreturnc                      y)zCheck if this service can generate performance metrics.

        Returns:
            True as this service supports metrics generation.
        T )r   s    r   can_generate_metricsz+StrandsAgentsProcessor.can_generate_metrics   s     r   prompt_tokenscompletion_tokenstotal_tokensc                 ^   K   t        |||      }| j                  |       d {    y 7 w)N)rU   rV   rW   )r
   start_llm_usage_metrics)r   rU   rV   rW   tokenss        r   r@   z,StrandsAgentsProcessor._report_usage_metrics   s1      '/%

 **6222s   #-+-)NNN)__name__
__module____qualname____doc__r   r   r   r&   r   r   r   r!   r%   boolrT   intr@   __classcell__)r   s   @r   r   r      s     "&!%)-	aa a "#	a64 4> 4 E=3 E=Nd 3 3583HK3r   r   )r^   typingr   logurur   pipecat.frames.framesr   r   r   r   r	   pipecat.metrics.metricsr
   1pipecat.processors.aggregators.openai_llm_contextr   "pipecat.processors.frame_processorr   r   strandsr   strands.multiagent.graphr   ModuleNotFoundErrorrP   errorrD   r   rS   r   r   <module>rl      st       2 S M,.L3^ L3  ,FLL\]
&qc*
++,s   A
 
A1A,,A1