
    =Qju                     d    d dl mZ d dlmZ d dlmZ d dlmZmZ de	e   de	e
   fdZdede
fd	Zy
)   )LLMGenerationError)reply_system_prompt)get_provider)ChatMessageSuggestResponseRequesthistoryreturnc                    g }| D ]  }|j                   rd|j                    d|j                   n|j                  }|r)|d   d   |j                  k(  r|d   dxx   d|z   z  cc<   b|j                  |j                  |d        |S )a  Collapse consecutive same-role turns into one message.

    OpenAI tolerates back-to-back "user" messages in the list; Anthropic's Messages
    API rejects them outright (it requires strict user/assistant alternation). Since
    conversation_history is built from an external source (an inbox thread) rather
    than turn-by-turn by this service, it can't be assumed to already alternate -
    merging here keeps every provider implementation equally usable instead of only
    working by accident with whichever one tolerates the input.
    [z] rolecontent
)r   r   )	timestampr   r   append)r   mergedmessager   s       8/var/www/html/meridian/meridian-ai/app/services/reply.py_to_alternating_messagesr      s     F F@G@Q@QAg''(7??*;<W^WfWffRj(GLL82Jy!TG^3!MM7<<GDEF M    payloadc                     t        | j                  | j                        }t        | j                        }	 t               j                  ||      S # t        $ r}t        dt        |            |d }~ww xY w)N)trip_contextnum_suggestionszFailed to suggest a response)
r   r   r   r   conversation_historyr   complete_json	Exceptionr   str)r   system_promptmessagesexcs       r   suggest_responser"      sr    '))//M ((D(DEHT~++M8DD T !?SJPSSTs   A 	A6A11A6N)
exceptionsr   promptsr   providers.factoryr   schemasr   r   listdictr   r"    r   r   <module>r*      sD    + ) , 9d;&7 DJ (
T4 
T 
Tr   