+
    ^eòjD  ã                  óº  € R t ^ RIHt ^ RIHtHtHtHt ^ RIHt ^ RI	H
t
 ^ RIHt ^ RIHt ^ RIHtHtHtHtHtHt ^ RIHt ^ R	IHt ^ R
IHt ^ RIHt ^ RIHt ^ RIH t! ]
'       d   ^ RIH"t" ^ RI#H$t$H%t% RRRRRRRRRRRRRR/R R llt&RRRRRRRRRR/R R llt'RRRRRRRRRRRRRR/R R llt(RRRRRRRRRRRRRR/R  R! llt)R" R# lt*R$ R% lt+. R&Ot,R# )'aç  LLM lifecycle helpers for non-streaming and streaming calls.

This module is the LLM analogue of ``nemo_relay.tools``. It manages emitted
events, global middleware, optional request codecs for annotated intercepts,
and optional response codecs for structured end-event annotations.

Example::

    import nemo_relay

    request = nemo_relay.LLMRequest(
        {},
        {"messages": [{"role": "user", "content": "hello"}], "model": "demo-model"},
    )

    async def impl(req):
        return {"id": "r1", "choices": [{"message": {"role": "assistant", "content": "hi"}}]}

    result = await nemo_relay.llm.execute(
        "demo-provider",
        request,
        impl,
        response_codec=nemo_relay.codecs.OpenAIChatCodec(),
    )
)Úannotations)ÚAsyncIteratorÚ	AwaitableÚCallableÚMapping)Údatetime)ÚTYPE_CHECKING)ÚJson)Úensure_scope_stack)ÚLLMAttributesÚ	LLMHandleÚ
LLMRequestÚLLMRequestInterceptOutcomeÚ	LlmStreamÚScopeHandle)Úllm_call)Úllm_call_end)Úllm_call_execute)Úllm_conditional_execution)Úllm_request_intercepts)Úllm_stream_call_execute)ÚAnnotatedLLMResponse)ÚLlmCodecÚLlmResponseCodecÚhandleNÚ
attributesÚdataÚmetadataÚ
model_nameÚ	timestampÚcodecc               ó@   € V ^8„  d   QhRRRRRRRRR	R
RR
RRRRRRRR/
# )é   ÚnameÚstrÚrequestr   r   úScopeHandle | Noner   úLLMAttributes | Noner   úJson | Noner   r   ú
str | Noner   údatetime | Noner    úLlmCodec | NoneÚreturnr   © )Úformats   "Ú…/opt/data/installs/351f81cc06284494/environments/aa258815729c481f8402f54f4c368f83/venv/lib/python3.14/site-packages/nemo_relay/llm.pyÚ__annotate__r0   H   sx   € ÷ Gñ GØ
ðGàðGð ð	Gð
 %ðGð ðGð ðGð ðGð ðGð ðGð ñGó    c               ó>   € \        4        \        V VVVVVVVVR7	      # )a  Start a manual LLM span and return its ``LLMHandle``.

Args:
    name: Provider or logical call name recorded on emitted events.
    request: Raw ``LLMRequest`` to associate with the call.
    handle: Optional parent scope handle. When omitted, the current scope
        becomes the parent.
    attributes: Optional native LLM attributes attached to the start event.
    data: Optional JSON application payload stored on the LLM handle.
    metadata: Optional JSON metadata recorded on the emitted start event.
    model_name: Optional normalized model name to record separately from the
        provider-specific request payload.
    timestamp: Optional timezone-aware ``datetime`` recorded as the handle
        start time and on the emitted start event. When omitted, the current
        runtime time is used.
    codec: Optional request codec used to sanitize and annotate the request
        copy saved in telemetry. The caller's request stays unchanged.

Returns:
    LLMHandle: Handle used to finish the manual span with ``call_end()``.

Notes:
    This starts only the manual LLM lifecycle span. It applies
    sanitize-request guardrails to the emitted start-event payload but does
    not run request or execution intercepts. ``timestamp`` must be a
    timezone-aware ``datetime``; strings and naive datetimes are rejected.

Example::

    import nemo_relay

    request = nemo_relay.LLMRequest({}, {"messages": [], "model": "demo-model"})
    handle = nemo_relay.llm.call(
        "demo-provider",
        request,
        handle=None,
        attributes=None,
        data={"attempt": 1},
        metadata={"path": "manual"},
        model_name="demo-model",
    )
    nemo_relay.llm.call_end(
        handle,
        {"ok": True},
        data={"cached": False},
        metadata={"status": "success"},
    )
)r   r   r   r   r   r   r    )r
   Ú_native_llm_call)	r#   r%   r   r   r   r   r   r   r    s	   &&$$$$$$$r/   Úcallr4   H   s3   € ôx ÔÜØØØØØØØØØô
ð 
r1   Úannotated_responseÚresponse_codecc               ó8   € V ^8„  d   QhRRRRRRRRRR	R
RRRRR/# )r"   r   r   Úresponser	   r   r(   r   r5   z0AnnotatedLLMResponse | Mapping[str, Json] | Noner6   úLlmResponseCodec | Noner   r*   r,   ÚNoner-   )r.   s   "r/   r0   r0   ’   sY   € ÷ 8ñ 8Øð8àð8ð ð	8ð
 ð8ð Ið8ð ,ð8ð ð8ð 
ñ8r1   c          
     ó:   € \        4        \        V VVVVVVR7      # )aô  Finish a manual LLM span started by ``call()``.

Args:
    handle: LLM handle returned by ``call()``.
    response: Raw JSON-compatible response to record on the end event.
    data: Optional JSON payload used when the sanitized ``response`` is JSON null.
    metadata: Optional JSON metadata recorded on the emitted end event.
    annotated_response: Optional normalized response annotation attached to
        the emitted end event. Accepts an ``AnnotatedLLMResponse`` returned
        by a codec, or a JSON-compatible mapping matching that schema.
    response_codec: Optional response codec used to derive
        ``annotated_response`` from the sanitized end-event payload for
        observability. Ignored when ``annotated_response`` is provided.
    timestamp: Optional timezone-aware ``datetime`` recorded on the emitted
        end event. When omitted, the runtime default end timestamp is used.

Returns:
    None: This function returns after an immutable end-event snapshot and
    its middleware/subscriber chains have been queued for publication.

Notes:
    ``call_end()`` remains synchronous. Sanitize-response guardrails,
    response-codec annotation, event sanitizers, and subscriber delivery
    run later on Relay's serial publication path. Callback and codec
    sanitizer failures are logged and fail closed; they cannot be raised by
    this call. Codec failures retain their documented fallback behavior.
    ``response_codec`` and ``annotated_response`` enrich observability
    output only and do not rewrite the caller-owned response.
    When model pricing is configured, Relay estimates missing cost when the
    response annotation contains matching model and token usage data.
    To report a failed call, set ``metadata["otel.status_code"]`` to
    ``"ERROR"``. Optional ``otel.status_description`` and ``error.type``
    fields describe the failure. Otherwise, the end event defaults to
    ``OK``.
    ``timestamp`` must be a timezone-aware ``datetime``; strings and naive
    datetimes are rejected.
)r   r   r5   r6   r   )r
   Ú_native_llm_call_end)r   r8   r   r   r5   r6   r   s   &&$$$$$r/   Úcall_endr=   ’   s-   € ô^ ÔÜØØØØØ-Ø%Øôð r1   c               óD   € V ^8„  d   QhRRRRRRRRR	R
RRRRRRRRRRRR/# )r"   r#   r$   r%   r   Úfuncz.Callable[[LLMRequest], Json | Awaitable[Json]]r   r&   r   r'   r   r(   r   r   r)   r    r+   r6   r9   r,   zAwaitable[Json]r-   )r.   s   "r/   r0   r0   Í   sƒ   € ÷ ]ñ ]Ø
ð]àð]ð 9ð]ð
 ð]ð %ð]ð ð]ð ð]ð ð]ð ð]ð ,ð]ð ñ]r1   c               ó@   € \        4        \        V VVVVVVVVV	R7
      # )a•	  Run an LLM call through the managed middleware pipeline.

Pipeline order:

1. LLM conditional-execution guardrails
2. LLM request intercepts
3. LLM sanitize-request guardrails for emitted start events
4. LLM execution intercepts
5. ``func(request)``
6. LLM sanitize-response guardrails for emitted end events

Args:
    name: Provider or logical call name recorded on emitted events.
    request: Raw ``LLMRequest`` passed through guardrails, intercepts, and
        then into ``func``.
    func: Provider callback invoked as ``func(request)`` after middleware
        has finished processing the request.
    handle: Optional parent scope handle. When omitted, the current scope
        becomes the parent.
    attributes: Optional native LLM attributes attached to the start event.
    data: Optional JSON application payload stored on the managed LLM handle.
    metadata: Optional JSON metadata recorded on the emitted start event.
    model_name: Optional normalized model name to record separately from the
        provider-specific request payload.
    codec: Optional request codec used to provide
        ``AnnotatedLLMRequest`` values to request intercepts.
    response_codec: Optional response codec used to attach a normalized
        response to the emitted ``LLMEnd`` event for observability.

Returns:
    Json: The raw JSON-compatible value returned by ``func`` or by an
    execution intercept.

Raises:
    RuntimeError: If a guardrail rejects the call or the runtime fails.
    Exception: An exception raised by ``func``, a conditional-execution guardrail,
        request intercept, or execution intercept.

Notes:
    ``codec`` enables annotated request intercepts. ``response_codec``
    decodes the raw response for observability only and does not change the
    value returned to the caller.

Example::

    import nemo_relay

    request = nemo_relay.LLMRequest(
        {},
        {"messages": [{"role": "user", "content": "hi"}], "model": "demo-model"},
    )

    async def impl(req):
        return {"id": "r1", "choices": [{"message": {"role": "assistant", "content": "hello"}}]}

    result = await nemo_relay.llm.execute(
        "demo-provider",
        request,
        impl,
        handle=None,
        attributes=None,
        data={"path": "managed"},
        metadata={"request_id": "req-1"},
        model_name="demo-model",
        codec=None,
        response_codec=nemo_relay.codecs.OpenAIChatCodec(),
    )
©r   r   r   r   r   r    r6   )r
   Ú_native_llm_call_execute)
r#   r%   r?   r   r   r   r   r   r    r6   s
   &&&$$$$$$$r/   ÚexecuterC   Í   s6   € ôb ÔÜ#ØØØØØØØØØØ%ôð r1   c               óL   € V ^8„  d   QhRRRRRRRRR	R
RRRRRRRRRRRRRRRR/# )r"   r#   r$   r%   r   r?   z+Callable[[LLMRequest], AsyncIterator[Json]]Ú	collectorzCallable[[Json], None]Ú	finalizerzCallable[[], Json]r   r&   r   r'   r   r(   r   r   r)   r    r+   r6   r9   r,   zAwaitable[LlmStream]r-   )r.   s   "r/   r0   r0   -  s™   € ÷ oñ oØ
ðoàðoð 6ðoð &ð	oð
 "ðoð ðoð %ðoð ðoð ðoð ðoð ðoð ,ðoð ñor1   c               óD   € \        4        \        V VVVVVVVVV	V
VR7      # )ai  Run a streaming LLM call through the managed middleware pipeline.

Args:
    name: Provider or logical call name recorded on emitted events.
    request: Raw ``LLMRequest`` passed through guardrails and intercepts.
    func: Provider callback invoked as ``func(request)`` that yields raw
        JSON chunks.
    collector: Callback invoked for each chunk after streaming intercepts
        run. It typically accumulates state for ``finalizer``.
    finalizer: Callback invoked after the stream completes to build the
        final JSON-compatible response recorded on the ``LLMEnd`` event.
    handle: Optional parent scope handle. When omitted, the current scope
        becomes the parent.
    attributes: Optional native LLM attributes attached to the start event.
    data: Optional JSON application payload stored on the managed LLM handle.
    metadata: Optional JSON metadata recorded on the emitted start event.
    model_name: Optional normalized model name to record separately from the
        provider-specific request payload.
    codec: Optional request codec used to provide
        ``AnnotatedLLMRequest`` values to request intercepts.
    response_codec: Optional response codec used to attach a normalized
        final response to the emitted ``LLMEnd`` event for observability.

Returns:
    LlmStream: Async iterator that yields the streamed JSON chunks.

Raises:
    RuntimeError: If a guardrail rejects the call or the runtime fails.
    TypeError: If ``func`` or stream-execution intercept returns an object that is not
        an async iterator.
    Exception: An exception raised by ``func``, a conditional-execution guardrail,
        or request or stream-execution intercept.

Notes:
    ``collector`` observes a separate copy of each post-intercept chunk;
    mutating that copy does not change the yielded value. Chunk processing
    runs on the originating event loop when native stack bounds permit it,
    with native runtime polling retained for small or unknown caller
    stacks. ``finalizer``
    runs once at natural stream completion or explicit close and should
    return a representation of the full response, not the final chunk. If
    the caller stops consuming early, call ``await stream.aclose()`` to
    cancel the producer, finalize the partial response, and release native
    stream resources.

Example::

    import nemo_relay

    request = nemo_relay.LLMRequest(
        {},
        {"messages": [{"role": "user", "content": "hi"}], "model": "demo-model"},
    )
    collected = []

    async def impl(req):
        yield {"token": "hel"}
        yield {"token": "lo"}

    def collect(chunk):
        collected.append(chunk)

    def finalize():
        return {"text": "".join(chunk["token"] for chunk in collected)}

    stream = await nemo_relay.llm.stream_execute(
        "demo-provider",
        request,
        impl,
        collect,
        finalize,
        handle=None,
        attributes=None,
        data={"path": "stream"},
        metadata={"request_id": "req-2"},
        model_name="demo-model",
        codec=None,
        response_codec=None,
    )
    async for chunk in stream:
        print(chunk)
rA   )r
   Ú_native_llm_stream_call_execute)r#   r%   r?   rE   rF   r   r   r   r   r   r    r6   s   &&&&&$$$$$$$r/   Ústream_executerI   -  s<   € ôB ÔÜ*ØØØØØØØØØØØØ%ôð r1   c               ó$   € V ^8„  d   QhRRRRRR/# )r"   r#   r$   r%   r   r,   zBLLMRequestInterceptOutcome | Awaitable[LLMRequestInterceptOutcome]r-   )r.   s   "r/   r0   r0   Ÿ  s$   € ÷ 9ñ 9Ø
ð9Ø"ð9àGñ9r1   c                ó,   € \        4        \        W4      # )až  Apply global LLM request intercepts to ``request``.

Args:
    name: Provider or logical call name used when evaluating intercepts.
    request: Raw ``LLMRequest`` to pass through the registered request
        intercept chain.

Returns:
    LLMRequestInterceptOutcome | Awaitable[LLMRequestInterceptOutcome]:
    The complete request, annotation, and pending-mark outcome produced by
    the intercept chain. Outside a running event loop this is returned
    directly. Inside an event loop, await the returned value.

Raises:
    RuntimeError: If an asynchronous intercept is registered when called outside an event loop.
    Exception: An exception raised by an intercept.

Notes:
    This runs only the request-intercept chain. It does not execute
    guardrails, codecs, provider callbacks, or stream handling.
    Outside an event loop, middleware runs on a Relay helper thread while
    the caller waits for the result.
)r
   Ú_native_llm_request_intercepts)r#   r%   s   &&r/   Úrequest_interceptsrM   Ÿ  s   € ô4 ÔÜ)¨$Ó8Ð8r1   c               ó    € V ^8„  d   QhRRRR/# )r"   r%   r   r,   zAwaitable[None] | Noner-   )r.   s   "r/   r0   r0   ½  s   € ÷ 6ñ 6 :ð 6Ð2Hñ 6r1   c                ó,   € \        4        \        V 4      # )a
  Run LLM conditional-execution guardrails for ``request``.

Args:
    request: Raw ``LLMRequest`` to validate against registered
        conditional-execution guardrails.

Returns:
    Awaitable[None] | None: ``None`` when execution is allowed, returned
    directly outside an event loop or through an awaitable inside one.

Notes:
    This helper evaluates only conditional-execution guardrails and does
    not invoke request intercepts, codecs, or provider execution.
    Outside an event loop, middleware runs on a Relay helper thread while
    the caller waits for the result.

Raises:
    RuntimeError: If a guardrail rejects the call or an asynchronous
        guardrail is registered when called outside an event loop.
    Exception: An exception raised by a guardrail.
)r
   Ú!_native_llm_conditional_execution)r%   s   &r/   Úconditional_executionrQ   ½  s   € ô, ÔÜ,¨WÓ5Ð5r1   )r4   r=   rC   rI   rM   rQ   )-Ú__doc__Ú
__future__r   Úcollections.abcr   r   r   r   r   Útypingr   Ú
nemo_relayr	   Únemo_relay._contextr
   Únemo_relay._nativer   r   r   r   r   r   r   r3   r   r<   r   rB   r   rP   r   rL   r   rH   r   Únemo_relay.codecsr   r   r4   r=   rC   rI   rM   rQ   Ú__all__r-   r1   r/   Ú<module>r[      sŸ  ðñõ4 #ç GÓ GÝ Ý  å Ý 2÷÷ õõõõõõ÷ õ÷ =ðGð "&ð	Gð
 (,ðGð ðGð !ðGð "ðGð "&ðGð "÷GðT8ð ð	8ð
 !ð8ð LPð8ð /3ð8ð "&÷8ðv]ð
 "&ð]ð (,ð]ð ð]ð !ð]ð "ð]ð "ð]ð /3÷]ð@oð "&ðoð (,ðoð ðoð !ðoð "ðoð "ðoð /3÷oõd9õ<6ò4‚r1   