# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.jsonable_encoder import jsonable_encoder
from ...core.pydantic_utilities import pydantic_v1
from ...core.request_options import RequestOptions
from ...errors.bad_request_error import BadRequestError
from ...errors.forbidden_error import ForbiddenError
from ...errors.internal_server_error import InternalServerError
from ...errors.not_found_error import NotFoundError
from ...types.compile_prompt_deployment_expand_meta_request import CompilePromptDeploymentExpandMetaRequest
from ...types.deployment_provider_payload_response import DeploymentProviderPayloadResponse
from ...types.deployment_read import DeploymentRead
from ...types.deployment_release_tag_read import DeploymentReleaseTagRead
from ...types.paginated_slim_deployment_read_list import PaginatedSlimDeploymentReadList
from ...types.prompt_deployment_input_request import PromptDeploymentInputRequest
from .types.deployments_list_request_status import DeploymentsListRequestStatus

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class DeploymentsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        ordering: typing.Optional[str] = None,
        status: typing.Optional[DeploymentsListRequestStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> PaginatedSlimDeploymentReadList:
        """
        Used to list all Prompt Deployments.

        Parameters
        ----------
        limit : typing.Optional[int]
            Number of results to return per page.

        offset : typing.Optional[int]
            The initial index from which to return the results.

        ordering : typing.Optional[str]
            Which field to use when ordering the results.

        status : typing.Optional[DeploymentsListRequestStatus]
            status

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        PaginatedSlimDeploymentReadList


        Examples
        --------
        from vellum.client import Vellum

        client = Vellum(
            api_key="YOUR_API_KEY",
        )
        client.deployments.list()
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/deployments",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={"limit": limit, "offset": offset, "ordering": ordering, "status": status},
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(PaginatedSlimDeploymentReadList, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def retrieve(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> DeploymentRead:
        """
        Used to retrieve a Prompt Deployment given its ID or name.

        Parameters
        ----------
        id : str
            Either the Deployment's ID or its unique name

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentRead


        Examples
        --------
        from vellum.client import Vellum

        client = Vellum(
            api_key="YOUR_API_KEY",
        )
        client.deployments.retrieve(
            id="id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/deployments/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentRead, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def retrieve_deployment_release_tag(
        self, id: str, name: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> DeploymentReleaseTagRead:
        """
        Retrieve a Deployment Release Tag by tag name, associated with a specified Deployment.

        Parameters
        ----------
        id : str
            A UUID string identifying this deployment.

        name : str
            The name of the Release Tag associated with this Deployment that you'd like to retrieve.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentReleaseTagRead


        Examples
        --------
        from vellum.client import Vellum

        client = Vellum(
            api_key="YOUR_API_KEY",
        )
        client.deployments.retrieve_deployment_release_tag(
            id="id",
            name="name",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/deployments/{jsonable_encoder(id)}/release-tags/{jsonable_encoder(name)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentReleaseTagRead, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update_deployment_release_tag(
        self,
        id: str,
        name: str,
        *,
        history_item_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DeploymentReleaseTagRead:
        """
        Updates an existing Release Tag associated with the specified Deployment.

        Parameters
        ----------
        id : str
            A UUID string identifying this deployment.

        name : str
            The name of the Release Tag associated with this Deployment that you'd like to update.

        history_item_id : typing.Optional[str]
            The ID of the Deployment History Item to tag

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentReleaseTagRead


        Examples
        --------
        from vellum.client import Vellum

        client = Vellum(
            api_key="YOUR_API_KEY",
        )
        client.deployments.update_deployment_release_tag(
            id="id",
            name="name",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/deployments/{jsonable_encoder(id)}/release-tags/{jsonable_encoder(name)}",
            base_url=self._client_wrapper.get_environment().default,
            method="PATCH",
            json={"history_item_id": history_item_id},
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentReleaseTagRead, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def retrieve_provider_payload(
        self,
        *,
        inputs: typing.Sequence[PromptDeploymentInputRequest],
        deployment_id: typing.Optional[str] = OMIT,
        deployment_name: typing.Optional[str] = OMIT,
        release_tag: typing.Optional[str] = OMIT,
        expand_meta: typing.Optional[CompilePromptDeploymentExpandMetaRequest] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DeploymentProviderPayloadResponse:
        """
        Given a set of input variable values, compile the exact payload that Vellum would send to the configured model provider
        for execution if the execute-prompt endpoint had been invoked. Note that this endpoint does not actually execute the
        prompt or make an API call to the model provider.

        This endpoint is useful if you don't want to proxy LLM provider requests through Vellum and prefer to send them directly
        to the provider yourself. Note that no guarantees are made on the format of this API's response schema, other than
        that it will be a valid payload for the configured model provider. It's not recommended that you try to parse or
        derive meaning from the response body and instead, should simply pass it directly to the model provider as is.

        We encourage you to seek advise from Vellum Support before integrating with this API for production use.

        Parameters
        ----------
        inputs : typing.Sequence[PromptDeploymentInputRequest]
            The list of inputs defined in the Prompt's deployment with their corresponding values.

        deployment_id : typing.Optional[str]
            The ID of the deployment. Must provide either this or deployment_name.

        deployment_name : typing.Optional[str]
            The name of the deployment. Must provide either this or deployment_id.

        release_tag : typing.Optional[str]
            Optionally specify a release tag if you want to pin to a specific release of the Workflow Deployment

        expand_meta : typing.Optional[CompilePromptDeploymentExpandMetaRequest]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentProviderPayloadResponse


        Examples
        --------
        from vellum.client import Vellum

        client = Vellum(
            api_key="YOUR_API_KEY",
        )
        client.deployments.retrieve_provider_payload(
            inputs=[],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/deployments/provider-payload",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "deployment_id": deployment_id,
                "deployment_name": deployment_name,
                "inputs": inputs,
                "release_tag": release_tag,
                "expand_meta": expand_meta,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentProviderPayloadResponse, _response.json())  # type: ignore
            if _response.status_code == 400:
                raise BadRequestError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 403:
                raise ForbiddenError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 404:
                raise NotFoundError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 500:
                raise InternalServerError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncDeploymentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        ordering: typing.Optional[str] = None,
        status: typing.Optional[DeploymentsListRequestStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> PaginatedSlimDeploymentReadList:
        """
        Used to list all Prompt Deployments.

        Parameters
        ----------
        limit : typing.Optional[int]
            Number of results to return per page.

        offset : typing.Optional[int]
            The initial index from which to return the results.

        ordering : typing.Optional[str]
            Which field to use when ordering the results.

        status : typing.Optional[DeploymentsListRequestStatus]
            status

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        PaginatedSlimDeploymentReadList


        Examples
        --------
        import asyncio

        from vellum.client import AsyncVellum

        client = AsyncVellum(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.deployments.list()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/deployments",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={"limit": limit, "offset": offset, "ordering": ordering, "status": status},
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(PaginatedSlimDeploymentReadList, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def retrieve(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> DeploymentRead:
        """
        Used to retrieve a Prompt Deployment given its ID or name.

        Parameters
        ----------
        id : str
            Either the Deployment's ID or its unique name

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentRead


        Examples
        --------
        import asyncio

        from vellum.client import AsyncVellum

        client = AsyncVellum(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.deployments.retrieve(
                id="id",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/deployments/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentRead, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def retrieve_deployment_release_tag(
        self, id: str, name: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> DeploymentReleaseTagRead:
        """
        Retrieve a Deployment Release Tag by tag name, associated with a specified Deployment.

        Parameters
        ----------
        id : str
            A UUID string identifying this deployment.

        name : str
            The name of the Release Tag associated with this Deployment that you'd like to retrieve.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentReleaseTagRead


        Examples
        --------
        import asyncio

        from vellum.client import AsyncVellum

        client = AsyncVellum(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.deployments.retrieve_deployment_release_tag(
                id="id",
                name="name",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/deployments/{jsonable_encoder(id)}/release-tags/{jsonable_encoder(name)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentReleaseTagRead, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update_deployment_release_tag(
        self,
        id: str,
        name: str,
        *,
        history_item_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DeploymentReleaseTagRead:
        """
        Updates an existing Release Tag associated with the specified Deployment.

        Parameters
        ----------
        id : str
            A UUID string identifying this deployment.

        name : str
            The name of the Release Tag associated with this Deployment that you'd like to update.

        history_item_id : typing.Optional[str]
            The ID of the Deployment History Item to tag

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentReleaseTagRead


        Examples
        --------
        import asyncio

        from vellum.client import AsyncVellum

        client = AsyncVellum(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.deployments.update_deployment_release_tag(
                id="id",
                name="name",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/deployments/{jsonable_encoder(id)}/release-tags/{jsonable_encoder(name)}",
            base_url=self._client_wrapper.get_environment().default,
            method="PATCH",
            json={"history_item_id": history_item_id},
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentReleaseTagRead, _response.json())  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def retrieve_provider_payload(
        self,
        *,
        inputs: typing.Sequence[PromptDeploymentInputRequest],
        deployment_id: typing.Optional[str] = OMIT,
        deployment_name: typing.Optional[str] = OMIT,
        release_tag: typing.Optional[str] = OMIT,
        expand_meta: typing.Optional[CompilePromptDeploymentExpandMetaRequest] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DeploymentProviderPayloadResponse:
        """
        Given a set of input variable values, compile the exact payload that Vellum would send to the configured model provider
        for execution if the execute-prompt endpoint had been invoked. Note that this endpoint does not actually execute the
        prompt or make an API call to the model provider.

        This endpoint is useful if you don't want to proxy LLM provider requests through Vellum and prefer to send them directly
        to the provider yourself. Note that no guarantees are made on the format of this API's response schema, other than
        that it will be a valid payload for the configured model provider. It's not recommended that you try to parse or
        derive meaning from the response body and instead, should simply pass it directly to the model provider as is.

        We encourage you to seek advise from Vellum Support before integrating with this API for production use.

        Parameters
        ----------
        inputs : typing.Sequence[PromptDeploymentInputRequest]
            The list of inputs defined in the Prompt's deployment with their corresponding values.

        deployment_id : typing.Optional[str]
            The ID of the deployment. Must provide either this or deployment_name.

        deployment_name : typing.Optional[str]
            The name of the deployment. Must provide either this or deployment_id.

        release_tag : typing.Optional[str]
            Optionally specify a release tag if you want to pin to a specific release of the Workflow Deployment

        expand_meta : typing.Optional[CompilePromptDeploymentExpandMetaRequest]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        DeploymentProviderPayloadResponse


        Examples
        --------
        import asyncio

        from vellum.client import AsyncVellum

        client = AsyncVellum(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.deployments.retrieve_provider_payload(
                inputs=[],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/deployments/provider-payload",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "deployment_id": deployment_id,
                "deployment_name": deployment_name,
                "inputs": inputs,
                "release_tag": release_tag,
                "expand_meta": expand_meta,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return pydantic_v1.parse_obj_as(DeploymentProviderPayloadResponse, _response.json())  # type: ignore
            if _response.status_code == 400:
                raise BadRequestError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 403:
                raise ForbiddenError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 404:
                raise NotFoundError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 500:
                raise InternalServerError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
