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

import typing
import urllib.parse
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.remove_none_from_dict import remove_none_from_dict
from ...errors.unprocessable_entity_error import UnprocessableEntityError
from ...types.extract_agent import ExtractAgent
from ...types.extract_config import ExtractConfig
from ...types.extract_job import ExtractJob
from ...types.extract_job_create import ExtractJobCreate
from ...types.extract_resultset import ExtractResultset
from ...types.extract_run import ExtractRun
from ...types.extract_schema_validate_response import ExtractSchemaValidateResponse
from ...types.http_validation_error import HttpValidationError
from ...types.llama_extract_settings import LlamaExtractSettings
from .types.extract_agent_create_data_schema import ExtractAgentCreateDataSchema
from .types.extract_agent_update_data_schema import ExtractAgentUpdateDataSchema
from .types.extract_schema_validate_request_data_schema import ExtractSchemaValidateRequestDataSchema

try:
    import pydantic
    if pydantic.__version__.startswith("1."):
        raise ImportError
    import pydantic.v1 as pydantic  # type: ignore
except ImportError:
    import pydantic  # type: ignore

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


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

    def list_extraction_agents(self, *, project_id: typing.Optional[str] = None) -> typing.List[ExtractAgent]:
        """
        Parameters:
            - project_id: typing.Optional[str].
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.list_extraction_agents()
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/extraction-agents"),
            params=remove_none_from_dict({"project_id": project_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.List[ExtractAgent], _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 create_extraction_agent(
        self,
        *,
        project_id: typing.Optional[str] = None,
        organization_id: typing.Optional[str] = None,
        name: str,
        data_schema: ExtractAgentCreateDataSchema,
        config: ExtractConfig,
    ) -> ExtractAgent:
        """
        Parameters:
            - project_id: typing.Optional[str].

            - organization_id: typing.Optional[str].

            - name: str. The name of the extraction schema

            - data_schema: ExtractAgentCreateDataSchema. The schema of the data.

            - config: ExtractConfig. The configuration parameters for the extraction agent.
        ---
        from llama_cloud import ExtractConfig, ExtractMode, ExtractTarget
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.create_extraction_agent(
            name="string",
            config=ExtractConfig(
                extraction_target=ExtractTarget.PER_DOC,
                extraction_mode=ExtractMode.FAST,
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/extraction-agents"),
            params=remove_none_from_dict({"project_id": project_id, "organization_id": organization_id}),
            json=jsonable_encoder({"name": name, "data_schema": data_schema, "config": config}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 validate_extraction_schema(
        self, *, data_schema: ExtractSchemaValidateRequestDataSchema
    ) -> ExtractSchemaValidateResponse:
        """
        Validates an extraction agent's schema definition.
        Returns the normalized and validated schema if valid, otherwise raises an HTTP 400.

        Parameters:
            - data_schema: ExtractSchemaValidateRequestDataSchema.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.validate_extraction_schema()
        """
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/extraction-agents/schema/validation"
            ),
            json=jsonable_encoder({"data_schema": data_schema}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractSchemaValidateResponse, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_extraction_agent_by_name(self, name: str, *, project_id: typing.Optional[str] = None) -> ExtractAgent:
        """
        Parameters:
            - name: str.

            - project_id: typing.Optional[str].
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.get_extraction_agent_by_name(
            name="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/extraction-agents/by-name/{name}"
            ),
            params=remove_none_from_dict({"project_id": project_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_extraction_agent(self, extraction_agent_id: str) -> ExtractAgent:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.get_extraction_agent(
            extraction_agent_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/",
                f"api/v1/extractionv2/extraction-agents/{extraction_agent_id}",
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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_extraction_agent(
        self, extraction_agent_id: str, *, data_schema: ExtractAgentUpdateDataSchema, config: ExtractConfig
    ) -> ExtractAgent:
        """
        Parameters:
            - extraction_agent_id: str.

            - data_schema: ExtractAgentUpdateDataSchema. The schema of the data

            - config: ExtractConfig. The configuration parameters for the extraction agent.
        ---
        from llama_cloud import ExtractConfig, ExtractMode, ExtractTarget
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.update_extraction_agent(
            extraction_agent_id="string",
            config=ExtractConfig(
                extraction_target=ExtractTarget.PER_DOC,
                extraction_mode=ExtractMode.FAST,
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "PUT",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/",
                f"api/v1/extractionv2/extraction-agents/{extraction_agent_id}",
            ),
            json=jsonable_encoder({"data_schema": data_schema, "config": config}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 delete_extraction_agent(self, extraction_agent_id: str) -> typing.Any:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.delete_extraction_agent(
            extraction_agent_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "DELETE",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/",
                f"api/v1/extractionv2/extraction-agents/{extraction_agent_id}",
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.Any, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 list_jobs(self, *, extraction_agent_id: str) -> typing.List[ExtractJob]:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.list_jobs(
            extraction_agent_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs"),
            params=remove_none_from_dict({"extraction_agent_id": extraction_agent_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.List[ExtractJob], _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job(self, *, request: ExtractJobCreate) -> ExtractJob:
        """
        Parameters:
            - request: ExtractJobCreate.
        ---
        from llama_cloud import (
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
        )
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.run_job(
            request=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs"),
            json=jsonable_encoder(request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractJob, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_job(self, job_id: str) -> ExtractJob:
        """
        Parameters:
            - job_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.get_job(
            job_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/jobs/{job_id}"),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractJob, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job_with_parsed_file_test(
        self, *, job_create: ExtractJobCreate, extract_settings: typing.Optional[LlamaExtractSettings] = OMIT
    ) -> ExtractResultset:
        """
        Parameters:
            - job_create: ExtractJobCreate.

            - extract_settings: typing.Optional[LlamaExtractSettings].
        ---
        from llama_cloud import (
            ChunkMode,
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
            LlamaExtractSettings,
            LlamaParseParameters,
        )
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.run_job_with_parsed_file_test(
            job_create=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
            extract_settings=LlamaExtractSettings(
                chunk_mode=ChunkMode.PAGE,
                llama_parse_params=LlamaParseParameters(),
            ),
        )
        """
        _request: typing.Dict[str, typing.Any] = {"job_create": job_create}
        if extract_settings is not OMIT:
            _request["extract_settings"] = extract_settings
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs/parsed/test"),
            json=jsonable_encoder(_request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractResultset, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job_with_parsed_file(self, *, request: ExtractJobCreate) -> ExtractResultset:
        """
        Parameters:
            - request: ExtractJobCreate.
        ---
        from llama_cloud import (
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
        )
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.run_job_with_parsed_file(
            request=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs/parsed"),
            json=jsonable_encoder(request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractResultset, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job_test_user(
        self, *, job_create: ExtractJobCreate, extract_settings: typing.Optional[LlamaExtractSettings] = OMIT
    ) -> ExtractJob:
        """
        Parameters:
            - job_create: ExtractJobCreate.

            - extract_settings: typing.Optional[LlamaExtractSettings].
        ---
        from llama_cloud import (
            ChunkMode,
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
            LlamaExtractSettings,
            LlamaParseParameters,
        )
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.run_job_test_user(
            job_create=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
            extract_settings=LlamaExtractSettings(
                chunk_mode=ChunkMode.PAGE,
                llama_parse_params=LlamaParseParameters(),
            ),
        )
        """
        _request: typing.Dict[str, typing.Any] = {"job_create": job_create}
        if extract_settings is not OMIT:
            _request["extract_settings"] = extract_settings
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs/test"),
            json=jsonable_encoder(_request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractJob, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_job_result(self, job_id: str) -> ExtractResultset:
        """
        Parameters:
            - job_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.get_job_result(
            job_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/jobs/{job_id}/result"
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractResultset, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 list_extract_runs(self, *, extraction_agent_id: str) -> typing.List[ExtractRun]:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.list_extract_runs(
            extraction_agent_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/runs"),
            params=remove_none_from_dict({"extraction_agent_id": extraction_agent_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.List[ExtractRun], _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_run_by_job_id(self, job_id: str) -> ExtractRun:
        """
        Parameters:
            - job_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.get_run_by_job_id(
            job_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/runs/by-job/{job_id}"
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractRun, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_run(self, run_id: str) -> ExtractRun:
        """
        Parameters:
            - run_id: str.
        ---
        from llama_cloud.client import LlamaCloud

        client = LlamaCloud(
            token="YOUR_TOKEN",
        )
        client.llama_extract.get_run(
            run_id="string",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/runs/{run_id}"),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractRun, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 AsyncLlamaExtractClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_extraction_agents(self, *, project_id: typing.Optional[str] = None) -> typing.List[ExtractAgent]:
        """
        Parameters:
            - project_id: typing.Optional[str].
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.list_extraction_agents()
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/extraction-agents"),
            params=remove_none_from_dict({"project_id": project_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.List[ExtractAgent], _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 create_extraction_agent(
        self,
        *,
        project_id: typing.Optional[str] = None,
        organization_id: typing.Optional[str] = None,
        name: str,
        data_schema: ExtractAgentCreateDataSchema,
        config: ExtractConfig,
    ) -> ExtractAgent:
        """
        Parameters:
            - project_id: typing.Optional[str].

            - organization_id: typing.Optional[str].

            - name: str. The name of the extraction schema

            - data_schema: ExtractAgentCreateDataSchema. The schema of the data.

            - config: ExtractConfig. The configuration parameters for the extraction agent.
        ---
        from llama_cloud import ExtractConfig, ExtractMode, ExtractTarget
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.create_extraction_agent(
            name="string",
            config=ExtractConfig(
                extraction_target=ExtractTarget.PER_DOC,
                extraction_mode=ExtractMode.FAST,
            ),
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/extraction-agents"),
            params=remove_none_from_dict({"project_id": project_id, "organization_id": organization_id}),
            json=jsonable_encoder({"name": name, "data_schema": data_schema, "config": config}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 validate_extraction_schema(
        self, *, data_schema: ExtractSchemaValidateRequestDataSchema
    ) -> ExtractSchemaValidateResponse:
        """
        Validates an extraction agent's schema definition.
        Returns the normalized and validated schema if valid, otherwise raises an HTTP 400.

        Parameters:
            - data_schema: ExtractSchemaValidateRequestDataSchema.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.validate_extraction_schema()
        """
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/extraction-agents/schema/validation"
            ),
            json=jsonable_encoder({"data_schema": data_schema}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractSchemaValidateResponse, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_extraction_agent_by_name(self, name: str, *, project_id: typing.Optional[str] = None) -> ExtractAgent:
        """
        Parameters:
            - name: str.

            - project_id: typing.Optional[str].
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.get_extraction_agent_by_name(
            name="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/extraction-agents/by-name/{name}"
            ),
            params=remove_none_from_dict({"project_id": project_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_extraction_agent(self, extraction_agent_id: str) -> ExtractAgent:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.get_extraction_agent(
            extraction_agent_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/",
                f"api/v1/extractionv2/extraction-agents/{extraction_agent_id}",
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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_extraction_agent(
        self, extraction_agent_id: str, *, data_schema: ExtractAgentUpdateDataSchema, config: ExtractConfig
    ) -> ExtractAgent:
        """
        Parameters:
            - extraction_agent_id: str.

            - data_schema: ExtractAgentUpdateDataSchema. The schema of the data

            - config: ExtractConfig. The configuration parameters for the extraction agent.
        ---
        from llama_cloud import ExtractConfig, ExtractMode, ExtractTarget
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.update_extraction_agent(
            extraction_agent_id="string",
            config=ExtractConfig(
                extraction_target=ExtractTarget.PER_DOC,
                extraction_mode=ExtractMode.FAST,
            ),
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "PUT",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/",
                f"api/v1/extractionv2/extraction-agents/{extraction_agent_id}",
            ),
            json=jsonable_encoder({"data_schema": data_schema, "config": config}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractAgent, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 delete_extraction_agent(self, extraction_agent_id: str) -> typing.Any:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.delete_extraction_agent(
            extraction_agent_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "DELETE",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/",
                f"api/v1/extractionv2/extraction-agents/{extraction_agent_id}",
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.Any, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 list_jobs(self, *, extraction_agent_id: str) -> typing.List[ExtractJob]:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.list_jobs(
            extraction_agent_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs"),
            params=remove_none_from_dict({"extraction_agent_id": extraction_agent_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.List[ExtractJob], _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job(self, *, request: ExtractJobCreate) -> ExtractJob:
        """
        Parameters:
            - request: ExtractJobCreate.
        ---
        from llama_cloud import (
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
        )
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.run_job(
            request=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs"),
            json=jsonable_encoder(request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractJob, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_job(self, job_id: str) -> ExtractJob:
        """
        Parameters:
            - job_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.get_job(
            job_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/jobs/{job_id}"),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractJob, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job_with_parsed_file_test(
        self, *, job_create: ExtractJobCreate, extract_settings: typing.Optional[LlamaExtractSettings] = OMIT
    ) -> ExtractResultset:
        """
        Parameters:
            - job_create: ExtractJobCreate.

            - extract_settings: typing.Optional[LlamaExtractSettings].
        ---
        from llama_cloud import (
            ChunkMode,
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
            LlamaExtractSettings,
            LlamaParseParameters,
        )
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.run_job_with_parsed_file_test(
            job_create=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
            extract_settings=LlamaExtractSettings(
                chunk_mode=ChunkMode.PAGE,
                llama_parse_params=LlamaParseParameters(),
            ),
        )
        """
        _request: typing.Dict[str, typing.Any] = {"job_create": job_create}
        if extract_settings is not OMIT:
            _request["extract_settings"] = extract_settings
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs/parsed/test"),
            json=jsonable_encoder(_request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractResultset, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job_with_parsed_file(self, *, request: ExtractJobCreate) -> ExtractResultset:
        """
        Parameters:
            - request: ExtractJobCreate.
        ---
        from llama_cloud import (
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
        )
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.run_job_with_parsed_file(
            request=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs/parsed"),
            json=jsonable_encoder(request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractResultset, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 run_job_test_user(
        self, *, job_create: ExtractJobCreate, extract_settings: typing.Optional[LlamaExtractSettings] = OMIT
    ) -> ExtractJob:
        """
        Parameters:
            - job_create: ExtractJobCreate.

            - extract_settings: typing.Optional[LlamaExtractSettings].
        ---
        from llama_cloud import (
            ChunkMode,
            ExtractConfig,
            ExtractJobCreate,
            ExtractMode,
            ExtractTarget,
            LlamaExtractSettings,
            LlamaParseParameters,
        )
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.run_job_test_user(
            job_create=ExtractJobCreate(
                extraction_agent_id="string",
                file_id="string",
                config_override=ExtractConfig(
                    extraction_target=ExtractTarget.PER_DOC,
                    extraction_mode=ExtractMode.FAST,
                ),
            ),
            extract_settings=LlamaExtractSettings(
                chunk_mode=ChunkMode.PAGE,
                llama_parse_params=LlamaParseParameters(),
            ),
        )
        """
        _request: typing.Dict[str, typing.Any] = {"job_create": job_create}
        if extract_settings is not OMIT:
            _request["extract_settings"] = extract_settings
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/jobs/test"),
            json=jsonable_encoder(_request),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractJob, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_job_result(self, job_id: str) -> ExtractResultset:
        """
        Parameters:
            - job_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.get_job_result(
            job_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/jobs/{job_id}/result"
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractResultset, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 list_extract_runs(self, *, extraction_agent_id: str) -> typing.List[ExtractRun]:
        """
        Parameters:
            - extraction_agent_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.list_extract_runs(
            extraction_agent_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "api/v1/extractionv2/runs"),
            params=remove_none_from_dict({"extraction_agent_id": extraction_agent_id}),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(typing.List[ExtractRun], _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_run_by_job_id(self, job_id: str) -> ExtractRun:
        """
        Parameters:
            - job_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.get_run_by_job_id(
            job_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(
                f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/runs/by-job/{job_id}"
            ),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractRun, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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 get_run(self, run_id: str) -> ExtractRun:
        """
        Parameters:
            - run_id: str.
        ---
        from llama_cloud.client import AsyncLlamaCloud

        client = AsyncLlamaCloud(
            token="YOUR_TOKEN",
        )
        await client.llama_extract.get_run(
            run_id="string",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "GET",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", f"api/v1/extractionv2/runs/{run_id}"),
            headers=self._client_wrapper.get_headers(),
            timeout=60,
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(ExtractRun, _response.json())  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic.parse_obj_as(HttpValidationError, _response.json()))  # type: ignore
        try:
            _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)
