
    Fd#                        d dl mZ d dlZd dlZd dlmZmZ d dlmZ erd dl	m
Z
 d dlmZ d dl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mZ d dlmZ e G d d                      ZdS )    )annotationsN)	dataclassfield)TYPE_CHECKING)Agent)Config)extract_json_from_response)ChatSequenceMessageMessageRoleMessageType)OPEN_AI_CHAT_MODELS)count_string_tokenscreate_chat_completion)PROMPT_SUMMARY_FILE_NAMESUMMARY_FILE_NAME)loggerc                      e Zd ZU ded<    ee          Zded<   dZded<   d	Zd
ed<   d&dZ	d Z
d Z	 d'd(dZd)dZd*dZd'd+d!Zd,d"Zd-d$Zd% ZdS ).MessageHistoryr   agent)default_factorylist[Message]messageszI was createdstrsummaryr   intlast_trimmed_indexic                    | j         |         S N)r   )selfr   s     RC:\Users\Administrator\Downloads\Auto-GPT-master\autogpt\memory\message_history.py__getitem__zMessageHistory.__getitem__   s    }Q    c                *    t          | j                  S r    )iterr   r!   s    r"   __iter__zMessageHistory.__iter__    s    DM"""r$   c                *    t          | j                  S r    )lenr   r'   s    r"   __len__zMessageHistory.__len__#   s    4=!!!r$   Nroler   contenttypeMessageType | Nonec                J    |                      t          |||                    S r    )appendr   )r!   r,   r-   r.   s       r"   addzMessageHistory.add&   s"     {{74$77888r$   messager   c                6    | j                             |          S r    )r   r1   )r!   r3   s     r"   r1   zMessageHistory.append.   s    }##G,,,r$   current_message_chainconfigr   returntuple[Message, list[Message]]c                     fdt                     D             }fd|D             }|s                                 g fS                      ||          }|d         } j                            |           _        ||fS )a6  
        Returns a list of trimmed messages: messages which are in the message history
        but not in current_message_chain.

        Args:
            current_message_chain (list[Message]): The messages currently in the context.
            config (Config): The config to use.

        Returns:
            Message: A message with the new running summary after adding the trimmed messages.
            list[Message]: A list of messages that are in full_message_history with an index higher than last_trimmed_index and absent from current_message_chain.
        c                0    g | ]\  }}|j         k    |S  )r   ).0r   msgr!   s      r"   
<listcomp>z0MessageHistory.trim_messages.<locals>.<listcomp>A   s1     
 
 
AsT5L1L1LC1L1L1Lr$   c                    g | ]}|v|	S r;   r;   )r<   r=   r5   s     r"   r>   z0MessageHistory.trim_messages.<locals>.<listcomp>F   s+     %
 %
 %
36K+K+KC+K+K+Kr$   )
new_eventsr6   )	enumeratesummary_messageupdate_running_summaryr   indexr   )r!   r5   r6   new_messagesnew_messages_not_in_chainnew_summary_messagelast_messages   ``     r"   trim_messageszMessageHistory.trim_messages1   s     
 
 
 
'oo
 
 

%
 %
 %
 %
'%
 %
 %
! ) 	.''))2--"990 : 
 

 14"&-"5"5l"C"C"$===r$   list[Message] | Nonec              #    K   |p| j         }t          dt          |          dz
            D ]}||         }|j        dk    r|dk    r||dz
           j        dk    r||dz
           nd}||dz            }	 t          |j                  i k    s
J d            |j        dk    sJ |||fV  # t          $ r2}t          j	        d| d	||dz
  |d
z                        Y d}~d}~ww xY wdS )z
        Yields:
            Message: a message containing user input
            Message: a message from the AI containing a proposed action
            Message: the message containing the result of the AI's proposed action
        r      ai_responseuserNz&AI response is not a valid JSON objectaction_resultz!Invalid item in message history: z; Messages:    )
r   ranger*   r.   r,   r	   r-   AssertionErrorr   debug)r!   r6   r   r   
ai_messageuser_messageresult_messageerrs           r"   	per_cyclezMessageHistory.per_cycleW   sj      ,t}q#h--!+,, 	 	A!!J-//#$q55Xa!e_-AV-K-KQQU  &a!e_N
.z/ABBbHHH; IHH%*o===="J>>>>>!   \\\RSTURUVWXYVYRYIZ\\       	 	s   56B,,
C(6(C##C(c                2    t          dd| j                   S )Nsystemz2This reminds you of these events from your past: 
)r   r   r'   s    r"   rC   zMessageHistory.summary_messages   s$    P$,PP
 
 	
r$   r@   c                Z   |s|                                  S t          j        |          }|D ]}|j                                        dk    rd|_        	 t          |j                  }d|v r|d= t          j        |          |_        \# t          j	        $ rB}t          j        d|            |j        rt          j        |j                    Y d}~d}~ww xY w|j                                        dk    rd|_        |j        dk    r|                    |           d	}t          j        |j                  j        }t%          t'          | j                  |j                  }g }	d
}
|D ]}t%          t'          |          |j                  }|
|z   ||z
  |z
  k    rC|                     |	|           t%          t'          | j                  |j                  }|g}	|}
v|	                    |           |
|z  }
|	r|                     |	|           |                                  S )ae  
        This function takes a list of dictionaries representing new events and combines them with the current summary,
        focusing on key and potentially important information to remember. The updated summary is returned in a message
        formatted in the 1st person past tense.

        Args:
            new_events (List[Dict]): A list of dictionaries containing the latest events to be added to the summary.

        Returns:
            str: A message containing the updated summary of actions, formatted in the 1st person past tense.

        Example:
            new_events = [{"event": "entered the kitchen."}, {"event": "found a scrawled note with the number 7"}]
            update_running_summary(new_events)
            # Returns: "This reminds you of these events from your past: 
I entered the kitchen and found a scrawled note saying 7."
        	assistantyouthoughtszError: Invalid JSON: Nr[   zyour computerrO   d   r   )rC   copydeepcopyr,   lowerr	   r-   jsondumpsJSONDecodeErrorr   error
debug_moderemover   getfast_llm_model
max_tokensr   r   r   summarize_batchr1   )r!   r@   r6   eventcontent_dicteprompt_template_lengthrl   summary_tlengthbatchbatch_tlengthevent_tlengths               r"   rD   z%MessageHistory.update_running_summaryy   sj   &  	*''))) ]:..
   	) 	)Ez!![00"
9#=em#L#LL!\11(4$(J|$<$<EMM+ 9 9 9L!<!<!<===( 9%78889
 !!##x//,

 v%%!!%((( "%(,V-BCCN
-c$,.?.?AVWW   	/ 	/E/E

F<QRRM -55GH H $$UF333"5%%v'<# #  -U###. 	0  ///##%%%s   4B		C8CCc                   d| j          d|pd d}t          j        |j        t	          d|          g          }| j        j                            | j        j        | j        j	        | j        j
        |                                t                     t          ||          j        | _         | j        j                            | j        j        | j        j	        | j        j
        | j         t                     d S )Na  Your task is to create a concise running summary of actions and information results in the provided text, focusing on key and potentially important information to remember.

You will receive the current summary and your latest actions. Combine them, adding relevant key information from the latest development in 1st person past tense and keeping the summary concise.

Summary So Far:
"""
z
"""

Latest Development:
"""
zNothing new happened.z
"""
rO   )r   r
   	for_modelrk   r   r   log_cycle_handler	log_cycleai_name
created_atcycle_countrawr   r   r-   r   )r!   new_events_batchr6   prompts       r"   rm   zMessageHistory.summarize_batch   s       ,,   '!GFF$;$;#<
 
 	
$..JJ!J"JJLL$	
 	
 	
 .ff==E
$..JJ!J"L	
 	
 	
 	
 	
r$   )r   r   r    )r,   r   r-   r   r.   r/   )r3   r   )r5   r   r6   r   r7   r8   )r6   r   r   rK   )r7   r   )r@   r   r6   r   r7   r   )__name__
__module____qualname____annotations__r   listr   r   r   r#   r(   r+   r2   r1   rJ   rY   rC   rD   rm   r;   r$   r"   r   r      s.        LLL#eD999H9999"G""""       # # #" " " $(	9 9 9 9 9- - - -$> $> $> $>L    8
 
 
 
Q& Q& Q& Q&f#
 #
 #
 #
 #
r$   r   )
__future__r   ra   rd   dataclassesr   r   typingr   autogpt.agentr   autogpt.configr   autogpt.json_utils.utilitiesr	   autogpt.llm.baser
   r   r   r   autogpt.llm.providers.openair   autogpt.llm.utilsr   r   autogpt.log_cycle.log_cycler   r   autogpt.logsr   r   r;   r$   r"   <module>r      sQ   " " " " " "   ( ( ( ( ( ( ( (             $###### ! ! ! ! ! ! C C C C C C L L L L L L L L L L L L < < < < < < I I I I I I I I S S S S S S S S       Z
 Z
 Z
 Z
 Z
 Z
 Z
 Z
 Z
 Z
r$   