a
    dg0                     @   s   d dl Z d dl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 d dlmZmZ d dlmZ d dlmZ d d	lmZ e eZG d
d deZdS )    N)datetime)AnyDictListOptional)LLMChain) TimeWeightedVectorStoreRetriever)
BaseMemoryDocument)mock_now)BaseLanguageModel)PromptTemplatec                   @   sp  e Zd ZU dZeed< eed< dZeed< dZ	e
e ed< g Zee ed< d	Zeed
< dZeed< dZeed< dZeed< dZeed< dZeed< dZeed< dZeed< dZeed< dZeed< dZeed< eeddd Zeeee d!d"d#ZdReee d%d&d'Z dSee
e! ee d(d)d*Z"dTe
e! ee d+d,d-Z#eed.d/d0Z$eee d.d1d2Z%dUee
e! ee d3d4d5Z&dVee
e! ee d3d6d7Z'dWee
e! ee( d8d9d:Z)ee( ed;d<d=Z*dXe(eed?d@dAZ+ee( ed;dBdCZ,eedDdEdFZ-e.ee dGdHdIZ/e0ee1f e0eef dJdKdLZ2e0ee1f e0ee1f ddMdNdOZ3ddGdPdQZ4dS )YGenerativeAgentMemoryz Memory for the generative agent.llmmemory_retrieverFverboseNreflection_thresholdcurrent_plang333333?importance_weight        aggregate_importancei  max_tokens_limitqueriesqueries_keyZrecent_memories_tokenmost_recent_memories_token_key
add_memoryadd_memory_keyrelevant_memoriesrelevant_memories_keyZrelevant_memories_simplerelevant_memories_simple_keyZmost_recent_memoriesmost_recent_memories_keynownow_key
reflecting)promptreturnc                 C   s   t | j|| jdS )N)r   r$   r   )r   r   r   )selfr$    r'   }/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_experimental/generative_agents/memory.pychain1   s    zGenerativeAgentMemory.chain)textr%   c                 C   s,   t d|  }dd |D }dd |D S )z8Parse a newline-separated string into a list of strings.z\nc                 S   s   g | ]}|  r|qS r'   )strip.0liner'   r'   r(   
<listcomp>8       z5GenerativeAgentMemory._parse_list.<locals>.<listcomp>c                 S   s   g | ]}t d d| qS )z^\s*\d+\.\s* )resubr+   r,   r'   r'   r(   r/   9   r0   )r2   splitr+   )r*   linesr'   r'   r(   _parse_list4   s    z!GenerativeAgentMemory._parse_list2   )last_kr%   c                    sP   t d} jj| d }d fdd|D } |j|d} |S )zIReturn the 3 most salient high-level questions about recent observations.z{observations}

Given only the information above, what are the 3 most salient high-level questions we can answer about the subjects in the statements?
Provide each question on a new line.N
c                    s   g | ]}  |qS r'   _format_memory_detail)r-   or&   r'   r(   r/   E   r0   zCGenerativeAgentMemory._get_topics_of_reflection.<locals>.<listcomp>)observations)r   from_templater   memory_streamjoinr)   runr6   )r&   r8   r$   r>   Zobservation_strresultr'   r=   r(   _get_topics_of_reflection;   s    z/GenerativeAgentMemory._get_topics_of_reflection)topicr!   r%   c                    sR   t d} j||d}d fddt|D } |j||d} |S )zJGenerate 'insights' on a topic of reflection, based on pertinent memories.a~  Statements relevant to: '{topic}'
---
{related_statements}
---
What 5 high-level novel insights can you infer from the above statements that are relevant for answering the following question?
Do not include any insights that are not relevant to the question.
Do not repeat any insights that have already been made.

Question: {topic}

(example format: insight (because of 1, 5, 3))
r!   r9   c                    s(   g | ] \}} j ||d   ddqS )   z. prefixr:   )r-   imemoryr=   r'   r(   r/   ]   s   z@GenerativeAgentMemory._get_insights_on_topic.<locals>.<listcomp>)rE   related_statements)r   r?   fetch_memoriesrA   	enumerater)   rB   r6   )r&   rE   r!   r$   Zrelated_memoriesrL   rC   r'   r=   r(   _get_insights_on_topicJ   s    

z,GenerativeAgentMemory._get_insights_on_topic)r!   r%   c                 C   sZ   | j rtd g }|  }|D ]4}| j||d}|D ]}| j||d q6|| q |S )z7Reflect on recent observations and generate 'insights'.zCharacter is reflectingrF   )r   loggerinforD   rO   r   extend)r&   r!   Znew_insightsZtopicsrE   ZinsightsZinsightr'   r'   r(   pause_to_reflecth   s    
z&GenerativeAgentMemory.pause_to_reflect)memory_contentr%   c                 C   sf   t d}| |j|d }| jr6td|  t	d|}|r^t
|dd | j S dS dS )	2Score the absolute importance of the given memory.a  On the scale of 1 to 10, where 1 is purely mundane (e.g., brushing teeth, making bed) and 10 is extremely poignant (e.g., a break up, college acceptance), rate the likely poignancy of the following piece of memory. Respond with a single integer.
Memory: {memory_content}
Rating: rT   zImportance score: z	^\D*(\d+)rG   
   r   N)r   r?   r)   rB   r+   r   rP   rQ   r2   searchfloatgroupr   )r&   rT   r$   Zscorematchr'   r'   r(   _score_memory_importanceu   s    	z.GenerativeAgentMemory._score_memory_importancec                 C   sN   t d}| |j|d }| jr6td|  dd |dD }|S )rU   a  On the scale of 1 to 10, where 1 is purely mundane (e.g., brushing teeth, making bed) and 10 is extremely poignant (e.g., a break up, college acceptance), rate the likely poignancy of the following piece of memory. Always answer with only a list of numbers. If just given one memory still respond in a list. Memories are separated by semi colans (;)
Memories: {memory_content}
Rating: rV   zImportance scores: c                 S   s   g | ]}t |qS r'   )rY   )r-   xr'   r'   r(   r/      r0   zDGenerativeAgentMemory._score_memories_importance.<locals>.<listcomp>;)	r   r?   r)   rB   r+   r   rP   rQ   r4   )r&   rT   r$   ZscoresZscores_listr'   r'   r(   _score_memories_importance   s    z0GenerativeAgentMemory._score_memories_importance)rT   r!   r%   c                 C   s   |  |}|  jt|7  _|d}g }tt|D ]"}|t|| d|| id q6| jj	||d}| j
dur| j| j
kr| jsd| _| j|d d| _d	| _|S )
z6Add an observations or memories to the agent's memory.r^   
importancepage_contentmetadatacurrent_timeNTrF   r   F)r_   r   maxr4   rangelenappendr
   r   add_documentsr   r#   rS   )r&   rT   r!   Zimportance_scoresZmemory_listZ	documentsrJ   rC   r'   r'   r(   add_memories   s.    



z"GenerativeAgentMemory.add_memoriesc                 C   sx   |  |}|  j|7  _t|d|id}| jj|g|d}| jdurt| j| jkrt| jstd| _| j|d d| _d| _|S )	z3Add an observation or memory to the agent's memory.r`   ra   rd   NTrF   r   F)r\   r   r
   r   rj   r   r#   rS   )r&   rT   r!   Zimportance_scoreZdocumentrC   r'   r'   r(   r      s"    

z GenerativeAgentMemory.add_memory)observationr!   r%   c                 C   sN   |dur>t | | j|W  d   S 1 s20    Y  n| j|S dS )zFetch related memories.N)r   r   Zinvoke)r&   rl   r!   r'   r'   r(   rM      s    
,z$GenerativeAgentMemory.fetch_memories)r   r%   c                 C   s6   g }|D ]}| | j|dd qddd |D S )Nz- rH   r9   c                 S   s   g | ]
}| qS r'   r'   r-   memr'   r'   r(   r/      r0   z@GenerativeAgentMemory.format_memories_detail.<locals>.<listcomp>)ri   r;   rA   )r&   r   contentrn   r'   r'   r(   format_memories_detail   s    z,GenerativeAgentMemory.format_memories_detailr1   )rK   rI   r%   c                 C   s*   |j d d}| d| d|j  S )NZ
created_atz%B %d, %Y, %I:%M %p[z] )rc   strftimerb   r+   )r&   rK   rI   Zcreated_timer'   r'   r(   r;      s    z+GenerativeAgentMemory._format_memory_detailc                 C   s   d dd |D S )Nz; c                 S   s   g | ]}|j  qS r'   )rb   rm   r'   r'   r(   r/      r0   z@GenerativeAgentMemory.format_memories_simple.<locals>.<listcomp>)rA   )r&   r   r'   r'   r(   format_memories_simple   s    z,GenerativeAgentMemory.format_memories_simple)consumed_tokensr%   c                 C   sZ   g }| j jddd D ]8}|| jkr( qP|| j|j7 }|| jk r|| q| |S )z-Reduce the number of tokens in the documents.N)r   r@   r   r   Zget_num_tokensrb   ri   rs   )r&   rt   rC   docr'   r'   r(   _get_memories_until_limit   s    

z/GenerativeAgentMemory._get_memories_until_limit)r%   c                 C   s   g S )z3Input keys this memory class will load dynamically.r'   r=   r'   r'   r(   memory_variables   s    z&GenerativeAgentMemory.memory_variables)inputsr%   c                    sx   | j}| j |durP fdd|D }j|j|iS | j}|durtj	|iS i S )z9Return key-value pairs given the text input to the chain.Nc                    s$   g | ]}j | d D ]}|qqS )rF   )rM   )r-   queryrn   r!   r&   r'   r(   r/   	  s   z?GenerativeAgentMemory.load_memory_variables.<locals>.<listcomp>)
getr   r"   r   rp   r   rs   r   r    rw   )r&   ry   r   r   Zmost_recent_memories_tokenr'   r{   r(   load_memory_variables  s(    	z+GenerativeAgentMemory.load_memory_variables)ry   outputsr%   c                 C   s.   | | j}| | j}|r*| j||d dS )z-Save the context of this model run to memory.rF   N)r|   r   r"   r   )r&   ry   r~   rn   r!   r'   r'   r(   save_context  s    z"GenerativeAgentMemory.save_contextc                 C   s   dS )zClear memory contents.Nr'   r=   r'   r'   r(   clear&  s    zGenerativeAgentMemory.clear)r7   )N)N)N)N)N)r1   )5__name__
__module____qualname____doc__r   __annotations__r   r   boolr   r   rY   r   r   strr   r   r   intr   r   r   r   r   r    r"   r#   r   r   r)   staticmethodr6   rD   r   rO   rS   r\   r_   rk   r   r
   rM   rp   r;   rs   rw   propertyrx   r   r   r}   r   r   r'   r'   r'   r(   r      sj   
  $  
 "r   )loggingr2   r   typingr   r   r   r   Zlangchain.chainsr   Zlangchain.retrieversr   Zlangchain.schemar	   r
   Zlangchain.utilsr   Zlangchain_core.language_modelsr   Zlangchain_core.promptsr   	getLoggerr   rP   r   r'   r'   r'   r(   <module>   s   
