o
    iP                     @  s  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	 d dl
mZmZmZ d dlmZmZmZ d dlmZmZ d dlZd dlm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 m!Z!m"Z"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/m0Z0 d	dl1m2Z2 ddlm3Z3m4Z4m5Z5 ddl6m7Z7m8Z8 eG dd dZ9eddG dd dZ:eddG dd de3Z;eG dd de5Z<ej=ej> ej? Z@G dd  d ZAd'd%d&ZBdS )(    )annotationsN)AsyncIteratorIterable)asynccontextmanager)InitVar	dataclassfield)datedatetime	timedelta)AnyLiteral)assert_never   )_utils)
RunContext)	UserError)BuiltinToolCallPartBuiltinToolReturnPartFilePartModelMessageModelRequestModelResponseModelResponsePartModelResponseStreamEventRetryPromptPartTextPartThinkingPartToolCallPartToolReturnPart)ModelProfileSpec)ModelSettings)ToolDefinition)RequestUsage   )ModelModelRequestParametersStreamedResponse)_estimate_string_tokens_estimate_usagec                   @  s   e Zd ZU dZded< dS )_WrappedTextOutputzUA private wrapper class to tag an output that came from the custom_output_text field.
str | NonevalueN)__name__
__module____qualname____doc____annotations__ r2   r2   ]/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/models/test.pyr*   (   s   
 r*   F)initc                   @  s$   e Zd ZU dZded< dddZdS )	_WrappedToolOutputzMA wrapper class to tag an output that came from the custom_output_args field.zdict[str, Any] | Noner,   
Any | Nonec                 C  s   t || _d S N)pydantic_coreto_jsonable_pythonr,   )selfr,   r2   r2   r3   __init__5   s   z_WrappedToolOutput.__init__N)r,   r6   )r-   r.   r/   r0   r1   r;   r2   r2   r2   r3   r5   /   s   
 r5   c                      s  e Zd ZU dZdZdZded< 	 dZded< 	 dZd	ed
< 	 dZ	ded< 	 e
dddZded< 	 e
dddZded< e
dddZded< dddddddd< fddZd=d$d%Ze	d>d?d)d*Zed@d+d,Zed@d-d.ZdAd2d3ZdBd5d6ZdCd8d9Zd=d:d;Z  ZS )D	TestModelag  A model specifically for testing purposes.

    This will (by default) call all tools in the agent, then return a tool response if possible,
    otherwise a plain response.

    How useful this model is will vary significantly.

    Apart from `__init__` derived by the `dataclass` decorator, all methods are private or match those
    of the base class.
    Falllist[str] | Literal['all']
call_toolsNr+   custom_output_textr6   custom_output_argsr   intseed)defaultr4   zModelRequestParameters | Nonelast_model_request_parameterstest)rD   reprstr_model_name_system)r?   r@   rA   rC   profilesettingsrK   ModelProfileSpec | NonerL   ModelSettings | Nonec                  s>   || _ || _|| _|| _d| _d| _d| _t j||d dS )z8Initialize TestModel with optional settings and profile.NrF   )rL   rK   )	r?   r@   rA   rC   rE   rI   rJ   superr;   )r:   r?   r@   rA   rC   rK   rL   	__class__r2   r3   r;   [   s   zTestModel.__init__messageslist[ModelMessage]model_settingsmodel_request_parametersr&   returnr   c                   s<   |  ||\}}|| _| |||}tg |||_|S r7   )prepare_requestrE   _requestr)   usage)r:   rR   rT   rU   model_responser2   r2   r3   requesto   s   zTestModel.requestrun_contextRunContext[Any] | NoneAsyncIterator[StreamedResponse]c                 C sB   |  ||\}}|| _| |||}t|| j||| jdV  d S )N)rU   rI   _structured_response	_messages_provider_name)rW   rE   rX   TestStreamedResponserI   rJ   )r:   rR   rT   rU   r\   rZ   r2   r2   r3   request_stream~   s   zTestModel.request_streamc                 C     | j S )zThe model name.rI   r:   r2   r2   r3   
model_name      zTestModel.model_namec                 C  rd   )zThe model provider.)rJ   rf   r2   r2   r3   system   rh   zTestModel.systemtool_defr"   r   c                 C  s   t |j| j S r7   )_JsonSchemaTestDataparameters_json_schemarC   generate)r:   rj   r2   r2   r3   gen_tool_args   s   zTestModel.gen_tool_args list[tuple[str, ToolDefinition]]c                   sL   | j dkrdd |jD S dd |jD   fdd| j D }dd |D S )	Nr=   c                 S     g | ]}|j |fqS r2   name.0rr2   r2   r3   
<listcomp>       z-TestModel._get_tool_calls.<locals>.<listcomp>c                 S  s   i | ]}|j |qS r2   rq   )rt   tr2   r2   r3   
<dictcomp>   s    z-TestModel._get_tool_calls.<locals>.<dictcomp>c                 3  s    | ]} | V  qd S r7   r2   )rt   rr   function_tools_lookupr2   r3   	<genexpr>   s    z,TestModel._get_tool_calls.<locals>.<genexpr>c                 S  rp   r2   rq   rs   r2   r2   r3   rv      rw   )r?   function_tools)r:   rU   tools_to_callr2   rz   r3   _get_tool_calls   s
   
zTestModel._get_tool_calls'_WrappedTextOutput | _WrappedToolOutputc                 C  s   | j d ur|jdksJ d| jd u sJ dt| j S | jd ur@|jd us*J d|jd }|j }r;t|| jiS t| jS |jrGtd S |jrNtd S td S )Ntoolz<Plain response not allowed, but `custom_output_text` is set.z>Cannot set both `custom_output_text` and `custom_output_args`.z:No output tools provided, but `custom_output_args` is set.r   )r@   output_moderA   r*   output_toolsouter_typed_dict_keyr5   allow_text_output)r:   rU   output_toolkr2   r2   r3   _get_output   s&   





zTestModel._get_outputc                   s  |j rtd|}||j}|r-tdd |D s-tfdd|D jdS |rg|d }t|t	s<J dd	d
 |j
D   rg fdd|D }|r`| fdd|D  t|jdS ttrj }d u ri }	|D ]}
t|
t	r|
j
D ]}t|tr|j|	|j< qqw|	rttt|	 gjdS ttdgjdS tt|gjdS |sJ dj}|jt|  }|d urtt|j|d|j dgjdS |}tt|j|d|j dgjdS )Nz)TestModel does not support built-in toolsc                 s  s    | ]}t |tV  qd S r7   )
isinstancer   )rt   mr2   r2   r3   r|      s    z%TestModel._request.<locals>.<genexpr>c                   s*   g | ]\}}t | |d | dqS )pyd_ai_tool_call_id__tool_call_idr   rn   rt   rr   argsrf   r2   r3   rv      s    z&TestModel._request.<locals>.<listcomp>)partsrg   z-Expected last message to be a `ModelRequest`.c                 S  s   h | ]
}t |tr|jqS r2   )r   r   	tool_name)rt   pr2   r2   r3   	<setcomp>   s    z%TestModel._request.<locals>.<setcomp>c                   s(   g | ]\}}| v rt ||qS r2   r   r   )new_retry_namesr:   r2   r3   rv      s    "c                   sN   g | ]#}|j  v rt|j ttrjd urjn|d|j  dqS )Nr   r   )rr   r   r   r5   r,   rn   )rt   r   r   output_wrapperr:   r2   r3   rv      s    


zsuccess (no tool calls)zNo output tools providedr   r   )builtin_toolsr   r   r   r   anyr   rI   r   r   r   extendr*   r,   r   contentr   r   r8   to_jsondecoderC   lenr   rr   rn   )r:   rR   rT   rU   
tool_callsr   last_messageretry_partsresponse_textoutputmessagepartrA   r   response_argsr2   r   r3   rX      s   









zTestModel._request)r?   r>   r@   r+   rA   r6   rC   rB   rK   rM   rL   rN   )rR   rS   rT   rN   rU   r&   rV   r   r7   )
rR   rS   rT   rN   rU   r&   r\   r]   rV   r^   rV   rH   )rj   r"   rV   r   )rU   r&   rV   ro   )rU   r&   rV   r   )r-   r.   r/   r0   __test__r?   r1   r@   rA   rC   r   rE   rI   rJ   r;   r[   r   rc   propertyrg   ri   rn   r   r   rX   __classcell__r2   r2   rP   r3   r<   9   sD   
 



r<   c                   @  s   e Zd ZU dZded< ded< ded< ded< eejd	d
Zded< dddZ	dddZ
edddZedddZedddZdS )rb   z-A structured response that streams test data.rH   rI   r   r_   zInitVar[Iterable[ModelMessage]]r`   ra   F)default_factoryr4   r
   
_timestampIterable[ModelMessage]c                 C  s   t || _d S r7   )r)   _usage)r:   r`   r2   r2   r3   __post_init__.  s   z"TestStreamedResponse.__post_init__rV   'AsyncIterator[ModelResponseStreamEvent]c           	      C sr  t | jjD ]\}}t|tr{|j}|d^ }}dd |D }|| t|dkrEt|dkrEt|d }|d | ||d  g}|  j	t
d7  _	| jj|dd}|d ur]|V  |D ]}|  j	t
|7  _	| jj||d}|d ury|V  q_qt|tr| jj||j|j|jdV  qt|ttB rJ d
t|j t|trJ dt|trJ dt| qd S )N c                 S  s   g | ]}| d qS )r   r2   )rt   wordr2   r2   r3   rv   6  rw   z<TestStreamedResponse._get_event_iterator.<locals>.<listcomp>r$   r    )vendor_part_idr   )r   r   r   r   Fz#Unexpected part type in TestModel: uK   This should be unreachable — we don't generate ThinkingPart on TestModel.uG   This should be unreachable — we don't generate FilePart on TestModel.)	enumerater_   r   r   r   r   splitappendr   r   _get_string_usage_parts_managerhandle_text_deltar   handle_tool_call_partr   r   r   r   r   typer-   r   r   r   )	r:   ir   textwords	last_wordmidmaybe_eventr   r2   r2   r3   _get_event_iterator1  sB   






z(TestStreamedResponse._get_event_iteratorc                 C  rd   )z#Get the model name of the response.re   rf   r2   r2   r3   rg   T  rh   zTestStreamedResponse.model_namec                 C  rd   )zGet the provider name.)ra   rf   r2   r2   r3   provider_nameY  rh   z"TestStreamedResponse.provider_namec                 C  rd   )z"Get the timestamp of the response.)r   rf   r2   r2   r3   	timestamp^  rh   zTestStreamedResponse.timestampN)r`   r   )rV   r   r   )rV   r
   )r-   r.   r/   r0   r1   r   r   now_utcr   r   r   r   rg   r   r   r2   r2   r2   r3   rb   $  s   
 

#rb   c                   @  sl   e Zd ZdZd d!ddZd"ddZd#ddZd$ddZd%ddZd&ddZ	d'ddZ
d(ddZd)ddZdS )*rk   zrGenerate data that matches a JSON schema.

    This tries to generate the minimal viable data for the schema.
    r   schema_utils.ObjectJsonSchemarC   rB   c                 C  s   || _ |di | _|| _d S )Nz$defs)r   getdefsrC   )r:   r   rC   r2   r2   r3   r;   m  s   
z_JsonSchemaTestData.__init__rV   dict[str, Any]c                 C  s   |  | jS )z"Generate data for the JSON schema.)_gen_anyr   rf   r2   r2   r3   rm   r  s   z_JsonSchemaTestData.generater   c           
      C  sL  | d }r	|S | d }r|| jt|  S | d }r)|| jt|  S | d }rAtdd|}| j| }| |S | d }rT| || jt|  S | d}	|	d	u ra|  S |	d
krj| |S |	dkrs| 	|S |	dkr|| 
|S |	dkrt| 
|S |	dkr|  S |	dkr| |S |	dkrd	S td|	 d)z"Generate data for any JSON Schema.constenumexamplesz$refz
^#/\$defs/r   anyOfr   NobjectstringintegernumberbooleanarraynullzUnknown type: z2, please submit a PR to extend JsonSchemaTestData!)r   rC   r   resubr   r   _char_object_gen_str_gen_int_genfloat	_bool_gen
_array_genNotImplementedError)
r:   r   r   r   r   refkeyjs_defany_oftype_r2   r2   r3   r   v  s<   






z_JsonSchemaTestData._gen_anyc           	      C  s   t |dg }i }|d }r%| D ]\}}||v r$| |||< q|d }rMd}||v r:|d7 }||v s2|du rF|  ||< |S | |||< |S )z'Generate data for a JSON Schema object.required
propertiesadditionalPropertiesadditionalProperty_T)setr   itemsr   r   )	r:   r   r   datar   r   r,   addition_propsadd_prop_keyr2   r2   r3   r     s"   z_JsonSchemaTestData._object_genrH   c                 C  sj   | d}|dur|  | S | ddkrdS | d }r1|dkr1tdd	d	t| jd
  S |  S )z,Generate a string from a JSON Schema string.	minLengthN	maxLengthr   r   formatr	   i  r$   )days)r   r   r	   r   rC   	isoformat)r:   r   min_lenfmtr2   r2   r3   r     s   
z_JsonSchemaTestData._str_genc                 C  s   | d}|du r| d}|dur|d }| d}|du r,| d}|dur,|d }|dur=|dur=|| j||   S |durF|| j S |durO|| j S | jS )z/Generate an integer from a JSON Schema integer.maximumNexclusiveMaximumr$   minimumexclusiveMinimum)r   rC   )r:   r   r   exc_maxr   exc_minr2   r2   r3   r     s"   





z_JsonSchemaTestData._int_genboolc                 C  s   t | jd S )z.Generate a boolean from a JSON Schema boolean.r   )r   rC   rf   r2   r2   r3   r     s   z_JsonSchemaTestData._bool_gen	list[Any]c           
      C  s   g }| d}| d }r$|D ]}|| | |r#|  jd7  _q| di }| dd}|t|krTt|t| D ]}|| | |rQ|  jd7  _q>|S |rv| d}	|	du se|	t|krv|| | |rv|  jd7  _|S )	z+Generate an array from a JSON Schema array.uniqueItemsprefixItemsr$   r   minItemsr   maxItemsN)r   r   r   rC   r   range)
r:   r   r   unique_itemsprefix_itemsitemitems_schema	min_itemsr   	max_itemsr2   r2   r3   r     s0   
	
z_JsonSchemaTestData._array_genc                 C  sX   t t}d}| j| }|dkr!|t|d |  7 }|| }|dks|t| j|  7 }|S )zOGenerate a character on the same principle as Excel columns, e.g. a-z, aa-az...r   r   r$   )r   _charsrC   )r:   charssremr2   r2   r3   r     s   
z_JsonSchemaTestData._charN)r   )r   r   rC   rB   )rV   r   )r   r   rV   r   )r   r   rV   r   )r   r   rV   rH   )r   r   rV   rB   )rV   r   )r   r   rV   r   r   )r-   r.   r/   r0   r;   rm   r   r   r   r   r   r   r   r2   r2   r2   r3   rk   g  s    


$



rk   r   rH   rV   r#   c                 C  s   t | }t|dS )N)output_tokens)r(   r#   )r   response_tokensr2   r2   r3   r      s   
r   )r   rH   rV   r#   )C
__future__r   _annotationsr   r   collections.abcr   r   
contextlibr   dataclassesr   r   r   r
   r	   r   typingr   r   r8   typing_extensionsr   r   r   _run_contextr   
exceptionsr   rR   r   r   r   r   r   r   r   r   r   r   r   r   r   profilesr    rL   r!   toolsr"   rY   r#   r%   r&   r'   functionr(   r)   r*   r5   r<   rb   ascii_lettersdigitspunctuationr  rk   r   r2   r2   r2   r3   <module>   sB    <	 k? 