o
    i                  
   @   s   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 zddlmZ dd	lmZ W n eyV Z zed
 ede dZ[ww G dd deZdS )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                       s   e Zd ZdZ			ddee dee dee f fddZde	d	e
f 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  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.
    Nagentgraphgraph_exit_nodec                    sL   t    || _|| _|| _| js| jsJ d| jr"| js$J ddS dS )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__ `/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/processors/frameworks/strands_agents.pyr   (   s   
zStrandsAgentsProcessor.__init__frame	directionc                    st   t  ||I dH  t|ttfr/|j }|r-|d }| t|d 	 I dH  dS dS | 
||I dH  dS )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   r   r   r   C   s   
 z$StrandsAgentsProcessor.process_frametextc              
      s   t d|  d}zfz| t I dH  |  I dH  |  I dH  | jr| j|I dH }|r=|  I dH  d}z`|j	| j
 }t d|  | D ]K}t|dd}t|trd|v r|d D ]}t|tr~d|v r~| tt|d I dH  qe| |jjd	d
|jjdd
|jjdd
I dH  qPW n ty } zt d|  W Y d}~nnd}~ww | j|2 za3 dH W }	t|	trd|	v r| tt|	d I dH  |r|  I dH  d}t|	trd|	v rd|	d v rd|	d d v r|	d d d }
| |
d	d
|
dd
|
dd
I dH  q6 W n1 ty4   t |  d Y n  tyS } z| jd| |dI dH  W Y d}~nd}~ww W |ra|  I dH  d}|  I dH  | t I dH  dS |r|  I dH  d}|  I dH  | t I dH  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_errr.   r0   er   r   r   r"   S   s   




&zStrandsAgentsProcessor._ainvokereturnc                 C   s   dS )zCheck if this service can generate performance metrics.

        Returns:
            True as this service supports metrics generation.
        Tr   )r   r   r   r   can_generate_metrics   s   z+StrandsAgentsProcessor.can_generate_metricsprompt_tokenscompletion_tokenstotal_tokensc                    s$   t |||d}| |I d H  d S )N)rO   rP   rQ   )r	   start_llm_usage_metrics)r   rO   rP   rQ   tokensr   r   r   r<      s   z,StrandsAgentsProcessor._report_usage_metrics)NNN)__name__
__module____qualname____doc__r   r   r   r#   r   r   r   r   r"   boolrN   intr<   __classcell__r   r   r   r   r      s,    Gr   )rW   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   ModuleNotFoundErrorrL   errorr@   r   r   r   r   r   <module>   s     
