ó
    °"³jÑ;  ã                  óª  • S r SSKJr  SSKrSSKJrJr  SSKJ	r	  SSKJ
r
Jr  SSKJr  SSKJr  SS	KJr  S
SKJrJrJrJr  S
SKJr  S
SKJr  S
SKJrJr  Sr      SS jrSSSS.           SS jjr SSSS.           SS jjr!SSSS.           SS jjr"SSSS.           SS jjr#      SS jr$\
 " S S5      5       r%g)aR  Methods for making imperative requests to language models with minimal abstraction.

These methods allow you to make requests to LLMs where the only abstraction is input and output schema
translation so you can use all models with the same API.

These methods are thin wrappers around [`Model`][pydantic_ai.models.Model] implementations.
é    )ÚannotationsN)ÚIteratorÚSequence)ÚAbstractAsyncContextManager)Ú	dataclassÚfield)Údatetime)ÚTracebackType)ÚRequestUsageé   )ÚagentÚmessagesÚmodelsÚsettings)ÚSyncStreamBridge)Úrun_until_complete)ÚStreamedResponseÚinstrumented)Úmodel_requestÚmodel_request_syncÚmodel_request_streamÚmodel_request_stream_syncÚStreamedResponseSyncc                ó  • UR                   b  U$ [        U 5       He  n[        U[        R                  5      (       d  M$  UR
                  c  M3  [        R                  " U[        R                  " UR
                  S9/S9s  $    U$ )a.  Populate instruction_parts from message history if not already set.

When using the direct API, users set `instructions` on `ModelRequest` but may not set
`instruction_parts` on `ModelRequestParameters`. This bridges the gap so models that
read `instruction_parts` directly still see the instructions.
)Úcontent)Úinstruction_parts)	r   ÚreversedÚ
isinstancer   ÚModelRequestÚinstructionsÚdataclassesÚreplaceÚInstructionPart)ÚmsgsÚmodel_request_parametersÚmessages      ÚO/home/mande/repo/quber/.venv/lib/python3.13/site-packages/pydantic_ai/direct.pyÚ_ensure_instruction_partsr(   "   sw   € ð  ×1Ñ1Ñ=Ø'Ð'Ü˜D–>ˆÜ�gœx×4Ñ4×5Ó5¸'×:NÑ:NÓ:ZÜ×&Ò&Ø(Ü#+×#;Ò#;ÀG×DXÑDXÑ#YÐ"Zñò ñ "ð $Ð#ó    ©Úmodel_settingsr%   Ú
instrumentc             ƒ  óº   #   • [        X5      n[        X=(       d    [        R                  " 5       5      nUR	                  [        U5      UU5      I Sh  v•N $  N7f)a  Make a non-streamed request to a model.

```py title="model_request_example.py"
from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request


async def main():
    model_response = await model_request(
        'anthropic:claude-haiku-4-5',
        [ModelRequest.user_text_prompt('What is the capital of France?')]  # (1)!
    )
    print(model_response)
    '''
    ModelResponse(
        parts=[TextPart(content='The capital of France is Paris.')],
        usage=RequestUsage(input_tokens=56, output_tokens=7),
        model_name='claude-haiku-4-5',
        timestamp=datetime.datetime(...),
    )
    '''
```

1. See [`ModelRequest.user_text_prompt`][pydantic_ai.messages.ModelRequest.user_text_prompt] for details.

Args:
    model: The model to make a request to. We allow `str` here since the actual list of allowed models changes frequently.
    messages: Messages to send to the model
    model_settings: optional model settings
    model_request_parameters: optional model request parameters
    instrument: Whether to instrument the request with OpenTelemetry/Logfire, if `None` the value from
        [`logfire.instrument_pydantic_ai`][logfire.Logfire.instrument_pydantic_ai] is used.

Returns:
    The model response and token usage associated with the request.
N)Ú_prepare_modelr(   r   ÚModelRequestParametersÚrequestÚlist©Úmodelr   r+   r%   r,   Úmodel_instanceÚmrps          r'   r   r   7   sT   é € ôX $ EÓ6€NÜ
# H×.iÌ&×JgÒJgÓJiÓ
j€CØ×'Ñ'ÜˆX‹ØØó÷ ð ñ ùs   ‚AAÁAÁAc          
     ó@   • [        [        U [        U5      UUUS95      $ )aº  Make a Synchronous, non-streamed request to a model.

This is a convenience method that wraps [`model_request`][pydantic_ai.direct.model_request] with
`loop.run_until_complete(...)`. You therefore can't use this method inside async code or if there's an active event loop.

```py title="model_request_sync_example.py"
from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_sync

model_response = model_request_sync(
    'anthropic:claude-haiku-4-5',
    [ModelRequest.user_text_prompt('What is the capital of France?')]  # (1)!
)
print(model_response)
'''
ModelResponse(
    parts=[TextPart(content='The capital of France is Paris.')],
    usage=RequestUsage(input_tokens=56, output_tokens=7),
    model_name='claude-haiku-4-5',
    timestamp=datetime.datetime(...),
)
'''
```

1. See [`ModelRequest.user_text_prompt`][pydantic_ai.messages.ModelRequest.user_text_prompt] for details.

Args:
    model: The model to make a request to. We allow `str` here since the actual list of allowed models changes frequently.
    messages: Messages to send to the model
    model_settings: optional model settings
    model_request_parameters: optional model request parameters
    instrument: Whether to instrument the request with OpenTelemetry/Logfire, if `None` the value from
        [`logfire.instrument_pydantic_ai`][logfire.Logfire.instrument_pydantic_ai] is used.

Returns:
    The model response and token usage associated with the request.
r*   )Ú_run_until_completer   r1   ©r3   r   r+   r%   r,   s        r'   r   r   l   s-   € ôZ ÜØÜ�‹NØ)Ø%=Ø!ñ	
óð r)   c               óž   • [        X5      n[        X=(       d    [        R                  " 5       5      nUR	                  [        U5      UU5      $ )aè  Make a streamed async request to a model.

```py {title="model_request_stream_example.py"}

from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_stream


async def main():
    messages = [ModelRequest.user_text_prompt('Who was Albert Einstein?')]  # (1)!
    async with model_request_stream('openai:gpt-5-mini', messages) as stream:
        chunks = []
        async for chunk in stream:
            chunks.append(chunk)
        print(chunks)
        '''
        [
            PartStartEvent(index=0, part=TextPart(content='Albert Einstein was ')),
            FinalResultEvent(tool_name=None, tool_call_id=None),
            PartDeltaEvent(
                index=0, delta=TextPartDelta(content_delta='a German-born theoretical ')
            ),
            PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='physicist.')),
            PartEndEvent(
                index=0,
                part=TextPart(
                    content='Albert Einstein was a German-born theoretical physicist.'
                ),
            ),
        ]
        '''
```

1. See [`ModelRequest.user_text_prompt`][pydantic_ai.messages.ModelRequest.user_text_prompt] for details.

Args:
    model: The model to make a request to. We allow `str` here since the actual list of allowed models changes frequently.
    messages: Messages to send to the model
    model_settings: optional model settings
    model_request_parameters: optional model request parameters
    instrument: Whether to instrument the request with OpenTelemetry/Logfire, if `None` the value from
        [`logfire.instrument_pydantic_ai`][logfire.Logfire.instrument_pydantic_ai] is used.

Returns:
    A [stream response][pydantic_ai.models.StreamedResponse] async context manager.
)r.   r(   r   r/   Úrequest_streamr1   r2   s          r'   r   r   ¤   sG   € ôl $ EÓ6€NÜ
# H×.iÌ&×JgÒJgÓJiÓ
j€CØ×(Ñ(ÜˆX‹ØØóð r)   r   c               óD   • [        U [        U5      UUUS9n[        U5      $ )aX  Make a streamed synchronous request to a model.

This is the synchronous version of [`model_request_stream`][pydantic_ai.direct.model_request_stream].
It drives the asynchronous stream on the caller's event loop while providing a synchronous iterator interface.
The returned context manager must be used and closed on the thread where the synchronous stream is created.

```py {title="model_request_stream_sync_example.py"}

from pydantic_ai import ModelRequest
from pydantic_ai.direct import model_request_stream_sync

messages = [ModelRequest.user_text_prompt('Who was Albert Einstein?')]
with model_request_stream_sync('openai:gpt-5-mini', messages) as stream:
    chunks = []
    for chunk in stream:
        chunks.append(chunk)
    print(chunks)
    '''
    [
        PartStartEvent(index=0, part=TextPart(content='Albert Einstein was ')),
        FinalResultEvent(tool_name=None, tool_call_id=None),
        PartDeltaEvent(
            index=0, delta=TextPartDelta(content_delta='a German-born theoretical ')
        ),
        PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='physicist.')),
        PartEndEvent(
            index=0,
            part=TextPart(
                content='Albert Einstein was a German-born theoretical physicist.'
            ),
        ),
    ]
    '''
```

Args:
    model: The model to make a request to. We allow `str` here since the actual list of allowed models changes frequently.
    messages: Messages to send to the model
    model_settings: optional model settings
    model_request_parameters: optional model request parameters
    instrument: Whether to instrument the request with OpenTelemetry/Logfire, if `None` the value from
        [`logfire.instrument_pydantic_ai`][logfire.Logfire.instrument_pydantic_ai] is used.

Returns:
    A [sync stream response][pydantic_ai.direct.StreamedResponseSync] context manager.
r8   )r   r1   r   )r3   r   r+   r%   r,   Úasync_stream_cms         r'   r   r   ã   s/   € ôl +ØÜ�h“Ø%Ø!9Øñ€Oô   Ó0Ð0r)   c                ó”   • [         R                  " U 5      nUc  [        R                  R                  n[
        R                  " X!5      $ ©N)r   Úinfer_modelr   ÚAgentÚ_instrument_defaultÚinstrumented_modelsÚinstrument_model)r3   r,   r4   s      r'   r.   r.   $  s:   € ô ×'Ò'¨Ó.€NàÑÜ—[‘[×4Ñ4ˆ
ä×/Ò/°ÓKÐKr)   c                  óê   • \ rS rSr% SrS\S'   \" SSS9rS\S	'   \" SSS9rS
\S'   SS jr	        SS jr
SS jrSS jr\rSS jr\SS j5       r\SS j5       r\SS j5       r\SS j5       rSrg)r   i0  a$  Synchronous wrapper for an async streaming response, running the whole stream on the caller's event loop.

The stream uses the internal `SyncStreamBridge` to keep context-manager
and iterator lifecycles in stable tasks. Exiting the `with` block cancels the underlying request promptly
and closes the connection instead of waiting for the whole response to arrive.

This class must be used as a context manager with the `with` statement. The synchronous stream is created
when the `with` block is entered and must be used and closed on that thread.
z-AbstractAsyncContextManager[StreamedResponse]Ú_async_stream_cmNF)ÚdefaultÚinitz)SyncStreamBridge[StreamedResponse] | NoneÚ_bridgeÚboolÚ_context_enteredc                óF   • SU l         [        U R                  SS9U l        U $ )NTz`model_request_stream`)Úasync_alternative)rJ   r   rE   rH   ©Úselfs    r'   Ú	__enter__ÚStreamedResponseSync.__enter__@  s$   € Ø $ˆÔÜ'¨×(=Ñ(=ÐQiÑjˆŒØˆr)   c                óf   • U R                   c   S5       eU R                   R                  XU45        g )Nz=`__exit__` is only reachable after `__enter__` sets `_bridge`)rH   Úshutdown)rN   Úexc_typeÚexc_valÚexc_tbs       r'   Ú__exit__ÚStreamedResponseSync.__exit__E  s1   € ð �|‰|Ñ'ÐhÐ)hÓhÐ'Ø�‰×Ñ˜x°&Ð9Õ:r)   c                óf   ^• U R                  5       nUR                  mUR                  U4S j5      $ )zsStream the response as an iterable of [`ModelResponseStreamEvent`][pydantic_ai.messages.ModelResponseStreamEvent]s.c                 ó   >• [        T 5      $ r>   )Úaiter)Ústreams   €r'   Ú<lambda>Ú/StreamedResponseSync.__iter__.<locals>.<lambda>T  s	   ø€ ¬%°¬-r)   )Ú_ensure_bridger[   Ústream_sync)rN   Úbridger[   s     @r'   Ú__iter__ÚStreamedResponseSync.__iter__N  s.   ø€ à×$Ñ$Ó&ˆð —‘ˆØ×!Ñ!Ô"7Ó8Ð8r)   c                ó¦   • U R                   b  [        U R                   R                  5      $ U R                  R                   SU R
                   S3$ )Nz(context_entered=Ú))rH   Úreprr[   Ú	__class__Ú__name__rJ   rM   s    r'   Ú__repr__ÚStreamedResponseSync.__repr__V  sH   € Ø�<‰<Ñ#Ü˜Ÿ™×+Ñ+Ó,Ð,à—n‘n×-Ñ-Ð.Ð.?À×@UÑ@UÐ?VÐVWÐXÐXr)   c                óJ   • U R                   c  [        S5      eU R                   $ )NzmStreamedResponseSync must be used as a context manager. Use: `with model_request_stream_sync(...) as stream:`)rH   ÚRuntimeErrorrM   s    r'   r^   Ú#StreamedResponseSync._ensure_bridge^  s+   € Ø�<‰<ÑÜðHóð ð �|‰|Ðr)   c                ól   • U R                  5       nUR                  UR                  R                  5      $ )z&Get the current state of the response.)r^   Úcallr[   Úget©rN   r`   s     r'   ÚresponseÚStreamedResponseSync.responsef  s+   € ð ×$Ñ$Ó&ˆØ�{‰{˜6Ÿ=™=×,Ñ,Ó-Ð-r)   c                óN   ^• U R                  5       mTR                  U4S j5      $ )z%Get the usage of the response so far.c                 ó0   >• T R                   R                  $ r>   )r[   Úusage©r`   s   €r'   r\   Ú,StreamedResponseSync.usage.<locals>.<lambda>p  s   ø€  6§=¡=×#6Ò#6r)   ©r^   rn   rp   s    @r'   ru   ÚStreamedResponseSync.usagel  s#   ø€ ð ×$Ñ$Ó&ˆØ�{‰{Ô6Ó7Ð7r)   c                óN   ^• U R                  5       mTR                  U4S j5      $ )z#Get the model name of the response.c                 ó0   >• T R                   R                  $ r>   )r[   Ú
model_namerv   s   €r'   r\   Ú1StreamedResponseSync.model_name.<locals>.<lambda>v  s   ø€  6§=¡=×#;Ò#;r)   rx   rp   s    @r'   r|   ÚStreamedResponseSync.model_namer  s#   ø€ ð ×$Ñ$Ó&ˆØ�{‰{Ô;Ó<Ð<r)   c                óN   ^• U R                  5       mTR                  U4S j5      $ )z"Get the timestamp of the response.c                 ó0   >• T R                   R                  $ r>   )r[   Ú	timestamprv   s   €r'   r\   Ú0StreamedResponseSync.timestamp.<locals>.<lambda>|  s   ø€  6§=¡=×#:Ò#:r)   rx   rp   s    @r'   r�   ÚStreamedResponseSync.timestampx  s#   ø€ ð ×$Ñ$Ó&ˆØ�{‰{Ô:Ó;Ð;r)   )rH   rJ   )Úreturnr   )rS   ztype[BaseException] | NonerT   zBaseException | NonerU   zTracebackType | Noner„   ÚNone)r„   z+Iterator[messages.ModelResponseStreamEvent])r„   Ústr)r„   z"SyncStreamBridge[StreamedResponse])r„   úmessages.ModelResponse)r„   r   )r„   r	   )rg   Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ú__annotations__r   rH   rJ   rO   rV   ra   rh   Ú__str__r^   Úpropertyrq   ru   r|   r�   Ú__static_attributes__© r)   r'   r   r   0  sÌ   ‡ ñð DÓCÙ9>ÀtÐRWÑ9X€GÐ6ÓXÙ"¨5°uÑ=Ð�dÓ=ôð
;à,ð;ð &ð;ð %ð	;ð
 
ô;ô9ôYð €Gôð ó.ó ð.ð
 ó8ó ð8ð
 ó=ó ð=ð
 ó<ó ó<r)   )r$   úSequence[messages.ModelMessage]r%   úmodels.ModelRequestParametersr„   r’   )r3   ú*models.Model | models.KnownModelName | strr   r‘   r+   úsettings.ModelSettings | Noner%   ú$models.ModelRequestParameters | Noner,   ú9instrumented_models.InstrumentationSettings | bool | Noner„   r‡   )r3   r“   r   r‘   r+   r”   r%   r•   r,   r–   r„   z4AbstractAsyncContextManager[models.StreamedResponse])r3   r“   r   r‘   r+   r”   r%   r•   r,   r–   r„   r   )r3   r“   r,   r–   r„   zmodels.Model)&r‹   Ú
__future__r   Ú_annotationsr!   Úcollections.abcr   r   Ú
contextlibr   r   r   r	   Útypesr
   Úpydantic_ai.usager   Ú r   r   r   r   Ú_sync_streamr   Ú_utilsr   r7   r   r   rB   Ú__all__r(   r   r   r   r   r.   r   r�   r)   r'   Ú<module>r¡      sÄ  ðñõ 3ã ß .Ý 2ß (Ý Ý å *ç /Ó /Ý *Ý =ß Ið€ð$Ø
)ð$à;ð$ð #ô$ð2 59ØEIØLPñ2Ø5ð2à-ð2ð 2ð	2ð
 Cð2ð Jð2ð õ2ðr 59ØEIØLPñ5Ø5ð5à-ð5ð 2ð	5ð
 Cð5ð Jð5ð õ5ðx 59ØEIØLPñ<Ø5ð<à-ð<ð 2ð	<ð
 Cð<ð Jð<ð :õ<ðF 59ØEIØLPñ>1Ø5ð>1à-ð>1ð 2ð	>1ð
 Cð>1ð Jð>1ð õ>1ðB	LØ5ð	LàIð	Lð ô	Lð ÷K<ð K<ó ñK<r)   