Ë
    òÏjà%  ã                  ó¤  — d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
 ddlmZmZmZ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 dd
lmZmZ ddlmZmZm Z  ddl!m"Z"m#Z#m$Z$m%Z% ddl&m'Z'm(Z( erddlm)Z)m*Z* ddl+m,Z, dZ- ed¬«       G d„ d«      «       Z. G d„ de«      Z/ G d„ de«      Z0 e«        G d„ dee0   «      «       Z1d d„Z2d!d„Z3d"d„Z4g d¢Z5y)#zJExperimental model-routing middleware powered by the OpenAI Decisions API.é    )Úannotations)ÚMapping)Ú	dataclass)ÚTYPE_CHECKINGÚAnyÚcast)ÚAgentMiddlewareÚ
AgentStateÚContextTÚModelRequestÚModelResponseÚ	ResponseTÚTracePolicyÚomit_payload)Úinit_chat_model)Úbeta)ÚBaseChatModel)ÚHumanMessageÚconvert_to_openai_messages)ÚNotRequiredÚ	TypedDictÚoverride)ÚChoiceÚDecisionRequestÚDecisionResponseÚOpenAIDecisions)Úadecide_with_text_fallbackÚdecide_with_text_fallback)Ú	AwaitableÚCallable)ÚRuntimeÚmodel_routeT)Úfrozenc                  ó&   — e Zd ZU dZded<   ded<   y)ÚModelChoicezêA model available to the router and the criterion for selecting it.

    Args:
        model: LangChain model instance or model string accepted by `init_chat_model`.
        criteria: Description of the tasks suited to the model.
    zstr | BaseChatModelÚmodelÚstrÚcriteriaN©Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__© ó    úe/var/www/html/gaurav-v2/venv/lib/python3.12/site-packages/langchain_openai/middleware/model_router.pyr%   r%   ,   s   … ñð ÓØ„Mr0   r%   c                  ó4   — e Zd ZU dZded<   	 ded<   	 ded<   y)	Ú
ModelRoutez·Routing answer stored in agent state under `model_route`.

    A plain mapping rather than a `ChoiceAnswer`, so checkpointers can persist it
    without registering custom types.
    r'   Úchoicezdict[str, float]ÚprobabilitiesÚfloatÚ
confidenceNr)   r/   r0   r1   r3   r3   9   s#   … ñð ƒKØ%à#Ó#Ø-àÓØJr0   r3   c                  ó   — e Zd ZU dZded<   y)Ú_ModelRouterStatez/Agent state used to persist the routing answer.zNotRequired[ModelRoute | None]r"   Nr)   r/   r0   r1   r9   r9   J   s   … Ù9à/Ô/r0   r9   c                  óÈ   — e Zd ZdZeZ ee¬«      Z	 	 	 	 	 	 	 	 	 dd„Z	e
	 	 	 	 	 	 dd„«       Ze
	 	 	 	 	 	 dd„«       Ze
	 	 	 	 	 	 dd„«       Ze
	 	 	 	 	 	 dd„«       Zdd„Zdd	„Zy
)ÚOpenAIModelRouterMiddlewareaM  Select an agent's model with an OpenAI Decisions `Choice` question.

    Classifies the latest human message once before each agent run, stores the
    answer as a `ModelRoute` in agent state under `model_route`, and uses the selected
    route for every model call in the run. Keeping the complete answer makes
    probabilities and confidence available in state and traces.

    The message text and base64 images are classified. Hosted image URLs, files,
    and audio are replaced with placeholders such as `[image omitted]`. If a request
    with images is rejected (HTTP 400 or 413), routing is retried once with every
    image replaced.

    When no route is selected, because the model refused or the state has no human
    message, `model_route` is set to `None` and model calls use the agent's own
    model. API errors propagate and terminate the run.

    !!! warning

        This middleware is experimental. Its API may change without notice.

    Args:
        choices: Named model choices, each containing a LangChain model or model
            string and the criterion for selecting it.
        instructions: Routing question sent to the Decisions API.
        model: Decisions model name, or a configured `OpenAIDecisions` instance.

    ??? example "Route agent calls by task"

        ```python
        from langchain.agents import create_agent
        from langchain_openai.middleware import (
            ModelChoice,
            OpenAIModelRouterMiddleware,
        )

        router = OpenAIModelRouterMiddleware(
            choices={
                "fast": ModelChoice(
                    model="openai:gpt-6-luna",
                    criteria="Simple, well-scoped tasks.",
                ),
                "powerful": ModelChoice(
                    model="openai:gpt-6-sol",
                    criteria="Complex tasks requiring deeper reasoning.",
                ),
            },
            instructions="Choose the least costly model suited to the task.",
            model="gpt-6-luna",
        )
        agent = create_agent("openai:gpt-6-luna", middleware=[router])
        ```
    )Úprocess_inputsc          	     ó  — |sd}t        |«      ‚|j                  «       sd}t        |«      ‚t        ||j                  «       D ��ci c]  \  }}||j                  “Œ c}}¬«      | _        |j                  «       D ��ci c]A  \  }}|t        |j                  t        «      rt        |j                  «      n|j                  “ŒC c}}| _
        t        |t        «      rt        |¬«      | _        y|| _        yc c}}w c c}}w )ay  Initialize the model router.

        Args:
            choices: Named model choices and the criterion for selecting each.
            instructions: Routing question sent to the Decisions API.
            model: Decisions model name, or a configured `OpenAIDecisions` instance.

        Raises:
            ValueError: If `choices` is empty or `instructions` is blank.
        z1`choices` must contain at least one model choice.z!`instructions` must not be empty.)ÚinstructionsÚchoices©r&   N)Ú
ValueErrorÚstripr   Úitemsr(   ÚquestionÚ
isinstancer&   r'   r   Úmodelsr   Ú	decisions)Úselfr?   r>   r&   ÚmsgÚrouter4   s          r1   Ú__init__z$OpenAIModelRouterMiddleware.__init__‹   së   € ñ" ØEˆCÜ˜S“/Ð!Ø×!Ñ!Ô#Ø5ˆCÜ˜S“/Ð!ÜØ%ØAHÇÁÄÔQÁ±°°v�U˜FŸO™OÑ+ÀÒQô
ˆŒð ")§¡¤ô	
ñ "1‘��vð Ü˜&Ÿ,™,¬Ô,ô # 6§<¡<Ô0à—‘ñð "1ò	
ˆŒô -7°u¼cÔ,BŒO %Ô(ð 	�ØHMð 	�ùó Rùó
s   ÁC7Á>AC=c                óv   — | j                  |«      }|sddiS t        | j                  |«      }dt        |«      iS )z6Classify the latest task and store the routing answer.r"   N)Ú_decision_requestsr   rG   Ú_route©rH   ÚstateÚruntimeÚrequestsÚresponses        r1   Úbefore_agentz(OpenAIModelRouterMiddleware.before_agent°   sB   € ð
 ×*Ñ*¨5Ó1ˆÙØ! 4Ð(Ð(Ü,¨T¯^©^¸XÓFˆØœv hÓ/Ð0Ð0r0   c              ƒ  ó’   K  — | j                  |«      }|sddiS t        | j                  |«      ƒ d{  –—† }dt        |«      iS 7 Œ­w)zEClassify the latest task asynchronously and store the routing answer.r"   N)rM   r   rG   rN   rO   s        r1   Úabefore_agentz)OpenAIModelRouterMiddleware.abefore_agent»   sO   è ø€ ð
 ×*Ñ*¨5Ó1ˆÙØ! 4Ð(Ð(Ü3°D·N±NÀHÓM×MˆØœv hÓ/Ð0Ð0ð Nús   ‚1A³A´Ac                ó0   —  || j                  |«      «      S )z5Route a synchronous model call to the selected model.©Ú_routed©rH   ÚrequestÚhandlers      r1   Úwrap_model_callz+OpenAIModelRouterMiddleware.wrap_model_callÆ   s   € ñ �t—|‘| GÓ,Ó-Ð-r0   c              ƒ  óL   K  —  || j                  |«      «      ƒ d{  –—† S 7 Œ­w)z7Route an asynchronous model call to the selected model.NrX   rZ   s      r1   Úawrap_model_callz,OpenAIModelRouterMiddleware.awrap_model_callÏ   s"   è ø€ ñ ˜TŸ\™\¨'Ó2Ó3×3Ð3Ð3ús   ‚$�"ž$c                ó  — t        d„ t        |d   «      D «       d«      }|€g S t        |d¬«      }t        |d¬«      }|j                  |j                  k(  r|gn||g}|D �cg c]  }|t        | j
                  idœ‘Œ c}S c c}w )zFReturn requests to try in order: with images (if any), then text only.c              3  óB   K  — | ]  }t        |t        «      sŒ|–— Œ y ­w)N)rE   r   )Ú.0Úms     r1   Ú	<genexpr>zAOpenAIModelRouterMiddleware._decision_requests.<locals>.<genexpr>Ý   s   è ø€ ÐSÑ3�1´zÀ!Ä\Õ7RŒQÑ3ùs   ‚˜ÚmessagesNF)Úkeep_imagesT)ÚinputÚ	questions)ÚnextÚreversedÚ	_routableÚcontentÚ_QUESTION_NAMErD   )rH   rP   ÚmessageÚ	text_onlyÚwith_imagesÚinputsrc   s          r1   rM   z.OpenAIModelRouterMiddleware._decision_requestsÚ   s£   € äÙSœ  zÑ!2Ô3ÓSØó
ˆð ˆ?ØˆIÜ˜g°5Ô9ˆ	Ü °TÔ:ˆð ×"Ñ" i×&7Ñ&7Ò7ð ‰Kà˜yÐ)ð 	ñ QWó
ÙPVÈ1�a¤~°t·}±}Ð&EÓFÐPVñ
ð 	
ùò 
s   Á"Bc                ó˜   — t        d|j                  j                  d«      «      }|€|S |j                  | j                  |d      ¬«      S )NúModelRoute | Noner"   r4   r@   )r   rP   Úgetr   rF   )rH   r[   rJ   s      r1   rY   z#OpenAIModelRouterMiddleware._routedí   sI   € ÜÐ(¨'¯-©-×*;Ñ*;¸MÓ*JÓKˆØˆ=ØˆNØ×Ñ d§k¡k°%¸±/Ñ&BÐÓCÐCr0   N)r?   zMapping[str, ModelChoice]r>   r'   r&   zstr | OpenAIDecisionsÚreturnÚNone)rP   r9   rQ   zRuntime[ContextT]ru   údict[str, Any])r[   úModelRequest[ContextT]r\   z<Callable[[ModelRequest[ContextT]], ModelResponse[ResponseT]]ru   úModelResponse[ResponseT])r[   rx   r\   zGCallable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]]ru   ry   )rP   r9   ru   zlist[DecisionRequest])r[   rx   ru   rx   )r*   r+   r,   r-   r9   Ústate_schemar   r   Útrace_policyrK   r   rT   rV   r]   r_   rM   rY   r/   r0   r1   r;   r;   P   s  „ ñ3ðj %€LÙ¨lÔ;€LØ7ð#
ð +ð#
ð ð	#
ð
 %ð#
ð 
ó#
ðJ ð1Ø&ð1Ø1Bð1à	ò1ó ð1ð ð1Ø&ð1Ø1Bð1à	ò1ó ð1ð ð.à'ð.ð Nð.ð 
"ò	.ó ð.ð ð4à'ð4ð
ð4ð 
"ò4ó ð4ó
ô&Dr0   r;   c          	     ó2  — t        | j                  t        «      r| S | j                  D �cg c]N  }t        |t        «      s!|j                  d«      dk(  s|rt	        |«      r|ndd|j                  dd«      › d�dœ‘ŒP }}| j                  d|i¬«      S c c}w )zAKeep text (and base64 images if requested); replace other blocks.ÚtypeÚtextÚ[rl   z	 omitted])r}   r~   )Úupdate)rE   rl   r'   rt   Ú_is_base64_imageÚ
model_copy)rn   rf   Úblockrl   s       r1   rk   rk   ô   s¬   € ä�'—/‘/¤3Ô'Øˆð —_’_óñ %ˆEô	 �eœSÔ!Ø�9‰9�VÓ Ò&ÙÔ,¨UÔ3ñ 	ð ¨¨%¯)©)°F¸IÓ*FÐ)GÀyÐ&QÑRñ		Sð
 %ð ð ð ×Ñ i°Ð%9ÐÓ:Ð:ùòs   «ABc                ó"  — | j                  d«      dvry	 t        t        | g¬«      «      d   d   }t        |t        «      r"|j                  di «      j                  dd	«      nd	}|j                  d
«      S # t        t        t
        f$ r Y yw xY w)Nr}   >   ÚimageÚ	image_urlF)rl   rl   r   r†   ÚurlÚ zdata:)	rt   r   r   rA   ÚKeyErrorÚ	TypeErrorrE   ÚdictÚ
startswith)rƒ   Úpartr‡   s      r1   r�   r�     sŽ   € Ø‡y�y�ÓÐ 6Ñ6ØðÜ)¬,À¸wÔ*GÓHÈÑSÐTUÑVˆô 7AÀÄtÔ6Lˆ$�(‰(�; Ó
#×
'Ñ
'¨¨rÔ
2ÐRT€CØ�>‰>˜'Ó"Ð"øô œ¤)Ð,ò Ùðús   –A7 Á7BÂBc                ó  — | j                   j                  t        «      }|€y t        |j                  «      |j
                  j                  «       D ��ci c]  \  }}t        |«      |“Œ c}}|j                  dœS c c}}w )N)r4   r5   r7   )r?   rt   rm   r'   r4   r5   rC   r7   )rS   ÚanswerÚkÚvs       r1   rN   rN     sq   € Ø×Ñ×!Ñ!¤.Ó1€FØ€~Øä�f—m‘mÓ$Ø06×0DÑ0D×0JÑ0JÔ0LÔMÑ0L©¨¨1œ#˜a›& !™)Ð0LÒMØ×'Ñ'ñð ùãMs   ÁA;)r%   r3   r;   N)rn   r   rf   Úboolru   r   )rƒ   rw   ru   r’   )rS   r   ru   rs   )6r-   Ú
__future__r   Úcollections.abcr   Údataclassesr   Útypingr   r   r   Ú!langchain.agents.middleware.typesr	   r
   r   r   r   r   r   r   Úlangchain.chat_modelsr   Úlangchain_core._apir   Úlangchain_core.language_modelsr   Úlangchain_core.messagesr   r   Útyping_extensionsr   r   r   Úlangchain_openai.decisionsr   r   r   r   Ú%langchain_openai.middleware._fallbackr   r   r   r    Úlanggraph.runtimer!   rm   r%   r3   r9   r;   rk   r�   rN   Ú__all__r/   r0   r1   Ú<module>r¡      sÒ   ðÙ På "å #Ý !ß +Ñ +÷	÷ 	ó 	õ 2Ý $Ý 8ß Lß >Ñ >÷ó ÷ñ
 ß3å)à€ñ �$Ô÷	ð 	ó ð	ôK�ô Kô"0˜
ô 0ñ ƒô`D /Ð2CÑ"Dó `Dó ð`DóF;ó#óò G�r0   