From 00c9fa432ffc021c1bb1a4bf336949dff2eda58a Mon Sep 17 00:00:00 2001 From: Logan Parker Date: Wed, 18 Nov 2026 12:26:07 +0000 Subject: [PATCH] feat(api): add 23 endpoints from the current spec --- api.md | 56 + src/contextual/_client.py | 109 +- src/contextual/resources/__init__.py | 42 + src/contextual/resources/billing.py | 738 ++++++ src/contextual/resources/extract.py | 1998 +++++++++++++++++ src/contextual/resources/workspaces.py | 252 +++ src/contextual/types/__init__.py | 47 + .../types/billing_list_top_ups_params.py | 13 + .../types/billing_list_top_ups_response.py | 40 + .../billing_retrieve_acl_usage_params.py | 15 + .../billing_retrieve_acl_usage_response.py | 41 + .../billing_retrieve_balance_response.py | 13 + ...ng_retrieve_billing_mode_history_params.py | 13 + ..._retrieve_billing_mode_history_response.py | 26 + ...g_retrieve_earliest_usage_date_response.py | 15 + .../billing_retrieve_metadata_response.py | 16 + .../billing_retrieve_monthly_usage_params.py | 15 + ...billing_retrieve_monthly_usage_response.py | 68 + .../types/extract_create_job_params.py | 23 + .../types/extract_create_job_response.py | 23 + .../types/extract_create_schema_params.py | 24 + .../types/extract_create_schema_response.py | 32 + .../types/extract_delete_document_response.py | 8 + .../types/extract_delete_schema_response.py | 8 + .../types/extract_list_documents_params.py | 15 + .../types/extract_list_documents_response.py | 48 + .../types/extract_list_jobs_params.py | 17 + .../types/extract_list_jobs_response.py | 108 + .../types/extract_list_schemas_params.py | 15 + .../types/extract_list_schemas_response.py | 48 + .../extract_retrieve_document_response.py | 32 + .../types/extract_retrieve_job_response.py | 92 + .../extract_retrieve_job_results_response.py | 71 + .../types/extract_retrieve_schema_response.py | 32 + .../extract_update_job_results_params.py | 13 + .../types/extract_update_schema_params.py | 21 + .../types/extract_update_schema_response.py | 32 + .../types/extract_upload_document_params.py | 13 + .../types/extract_upload_document_response.py | 28 + .../workspace_retrieve_consent_response.py | 20 + .../types/workspace_update_consent_params.py | 12 + .../workspace_update_consent_response.py | 10 + tests/api_resources/test_billing.py | 488 ++++ tests/api_resources/test_extract.py | 1120 +++++++++ tests/api_resources/test_workspaces.py | 139 ++ tests/test_added_calls_stubbed.py | 97 + 46 files changed, 6105 insertions(+), 1 deletion(-) create mode 100644 src/contextual/resources/billing.py create mode 100644 src/contextual/resources/extract.py create mode 100644 src/contextual/resources/workspaces.py create mode 100644 src/contextual/types/billing_list_top_ups_params.py create mode 100644 src/contextual/types/billing_list_top_ups_response.py create mode 100644 src/contextual/types/billing_retrieve_acl_usage_params.py create mode 100644 src/contextual/types/billing_retrieve_acl_usage_response.py create mode 100644 src/contextual/types/billing_retrieve_balance_response.py create mode 100644 src/contextual/types/billing_retrieve_billing_mode_history_params.py create mode 100644 src/contextual/types/billing_retrieve_billing_mode_history_response.py create mode 100644 src/contextual/types/billing_retrieve_earliest_usage_date_response.py create mode 100644 src/contextual/types/billing_retrieve_metadata_response.py create mode 100644 src/contextual/types/billing_retrieve_monthly_usage_params.py create mode 100644 src/contextual/types/billing_retrieve_monthly_usage_response.py create mode 100644 src/contextual/types/extract_create_job_params.py create mode 100644 src/contextual/types/extract_create_job_response.py create mode 100644 src/contextual/types/extract_create_schema_params.py create mode 100644 src/contextual/types/extract_create_schema_response.py create mode 100644 src/contextual/types/extract_delete_document_response.py create mode 100644 src/contextual/types/extract_delete_schema_response.py create mode 100644 src/contextual/types/extract_list_documents_params.py create mode 100644 src/contextual/types/extract_list_documents_response.py create mode 100644 src/contextual/types/extract_list_jobs_params.py create mode 100644 src/contextual/types/extract_list_jobs_response.py create mode 100644 src/contextual/types/extract_list_schemas_params.py create mode 100644 src/contextual/types/extract_list_schemas_response.py create mode 100644 src/contextual/types/extract_retrieve_document_response.py create mode 100644 src/contextual/types/extract_retrieve_job_response.py create mode 100644 src/contextual/types/extract_retrieve_job_results_response.py create mode 100644 src/contextual/types/extract_retrieve_schema_response.py create mode 100644 src/contextual/types/extract_update_job_results_params.py create mode 100644 src/contextual/types/extract_update_schema_params.py create mode 100644 src/contextual/types/extract_update_schema_response.py create mode 100644 src/contextual/types/extract_upload_document_params.py create mode 100644 src/contextual/types/extract_upload_document_response.py create mode 100644 src/contextual/types/workspace_retrieve_consent_response.py create mode 100644 src/contextual/types/workspace_update_consent_params.py create mode 100644 src/contextual/types/workspace_update_consent_response.py create mode 100644 tests/api_resources/test_billing.py create mode 100644 tests/api_resources/test_extract.py create mode 100644 tests/api_resources/test_workspaces.py create mode 100644 tests/test_added_calls_stubbed.py diff --git a/api.md b/api.md index cb297b46..eb384676 100644 --- a/api.md +++ b/api.md @@ -221,3 +221,59 @@ Methods: - client.parse.job_results(job_id, \*\*params) -> ParseJobResultsResponse - client.parse.job_status(job_id) -> ParseJobStatusResponse - client.parse.jobs(\*\*params) -> ParseJobsResponse + +# Extract + +Types: + +```python +from contextual.types import ExtractDeleteDocumentResponse, ExtractDeleteSchemaResponse, ExtractListDocumentsResponse, ExtractRetrieveDocumentResponse, ExtractListJobsResponse, ExtractRetrieveJobResponse, ExtractRetrieveJobResultsResponse, ExtractListSchemasResponse, ExtractRetrieveSchemaResponse, ExtractUploadDocumentResponse, ExtractCreateJobResponse, ExtractCreateSchemaResponse, ExtractUpdateSchemaResponse +``` + +Methods: + +- client.extract.delete_document(document_id) -> ExtractDeleteDocumentResponse +- client.extract.delete_schema(schema_id) -> ExtractDeleteSchemaResponse +- client.extract.list_documents(\*\*params) -> ExtractListDocumentsResponse +- client.extract.retrieve_document(document_id) -> ExtractRetrieveDocumentResponse +- client.extract.list_jobs(\*\*params) -> ExtractListJobsResponse +- client.extract.retrieve_job(job_id) -> ExtractRetrieveJobResponse +- client.extract.retrieve_job_results(job_id) -> ExtractRetrieveJobResultsResponse +- client.extract.list_schemas(\*\*params) -> ExtractListSchemasResponse +- client.extract.retrieve_schema(schema_id) -> ExtractRetrieveSchemaResponse +- client.extract.upload_document(\*\*params) -> ExtractUploadDocumentResponse +- client.extract.create_job(\*\*params) -> ExtractCreateJobResponse +- client.extract.create_schema(\*\*params) -> ExtractCreateSchemaResponse +- client.extract.update_job_results(job_id, \*\*params) -> object +- client.extract.update_schema(schema_id, \*\*params) -> ExtractUpdateSchemaResponse + +# Billing + +Types: + +```python +from contextual.types import BillingRetrieveBalanceResponse, BillingListTopUpsResponse, BillingRetrieveBillingModeHistoryResponse, BillingRetrieveMetadataResponse, BillingRetrieveAclUsageResponse, BillingRetrieveEarliestUsageDateResponse, BillingRetrieveMonthlyUsageResponse +``` + +Methods: + +- client.billing.retrieve_balance() -> BillingRetrieveBalanceResponse +- client.billing.list_top_ups(\*\*params) -> BillingListTopUpsResponse +- client.billing.retrieve_billing_mode_history(\*\*params) -> BillingRetrieveBillingModeHistoryResponse +- client.billing.retrieve_metadata() -> BillingRetrieveMetadataResponse +- client.billing.retrieve_acl_usage(\*\*params) -> BillingRetrieveAclUsageResponse +- client.billing.retrieve_earliest_usage_date() -> BillingRetrieveEarliestUsageDateResponse +- client.billing.retrieve_monthly_usage(\*\*params) -> BillingRetrieveMonthlyUsageResponse + +# Workspaces + +Types: + +```python +from contextual.types import WorkspaceRetrieveConsentResponse, WorkspaceUpdateConsentResponse +``` + +Methods: + +- client.workspaces.retrieve_consent() -> WorkspaceRetrieveConsentResponse +- client.workspaces.update_consent(\*\*params) -> WorkspaceUpdateConsentResponse diff --git a/src/contextual/_client.py b/src/contextual/_client.py index 433b434d..04fbb9b8 100644 --- a/src/contextual/_client.py +++ b/src/contextual/_client.py @@ -31,12 +31,15 @@ ) if TYPE_CHECKING: - from .resources import parse, users, agents, lmunit, rerank, generate, datastores + from .resources import parse, users, agents, lmunit, rerank, billing, extract, generate, datastores, workspaces from .resources.parse import ParseResource, AsyncParseResource from .resources.users import UsersResource, AsyncUsersResource from .resources.lmunit import LMUnitResource, AsyncLMUnitResource from .resources.rerank import RerankResource, AsyncRerankResource + from .resources.billing import BillingResource, AsyncBillingResource + from .resources.extract import ExtractResource, AsyncExtractResource from .resources.generate import GenerateResource, AsyncGenerateResource + from .resources.workspaces import WorkspacesResource, AsyncWorkspacesResource from .resources.agents.agents import AgentsResource, AsyncAgentsResource from .resources.datastores.datastores import DatastoresResource, AsyncDatastoresResource @@ -157,6 +160,24 @@ def parse(self) -> ParseResource: return ParseResource(self) + @cached_property + def extract(self) -> ExtractResource: + from .resources.extract import ExtractResource + + return ExtractResource(self) + + @cached_property + def billing(self) -> BillingResource: + from .resources.billing import BillingResource + + return BillingResource(self) + + @cached_property + def workspaces(self) -> WorkspacesResource: + from .resources.workspaces import WorkspacesResource + + return WorkspacesResource(self) + @cached_property def with_raw_response(self) -> ContextualAIWithRawResponse: return ContextualAIWithRawResponse(self) @@ -380,6 +401,24 @@ def parse(self) -> AsyncParseResource: return AsyncParseResource(self) + @cached_property + def extract(self) -> AsyncExtractResource: + from .resources.extract import AsyncExtractResource + + return AsyncExtractResource(self) + + @cached_property + def billing(self) -> AsyncBillingResource: + from .resources.billing import AsyncBillingResource + + return AsyncBillingResource(self) + + @cached_property + def workspaces(self) -> AsyncWorkspacesResource: + from .resources.workspaces import AsyncWorkspacesResource + + return AsyncWorkspacesResource(self) + @cached_property def with_raw_response(self) -> AsyncContextualAIWithRawResponse: return AsyncContextualAIWithRawResponse(self) @@ -546,6 +585,23 @@ def parse(self) -> parse.ParseResourceWithRawResponse: return ParseResourceWithRawResponse(self._client.parse) + @cached_property + def extract(self) -> extract.ExtractResourceWithRawResponse: + from .resources.extract import ExtractResourceWithRawResponse + + return ExtractResourceWithRawResponse(self._client.extract) + + @cached_property + def billing(self) -> billing.BillingResourceWithRawResponse: + from .resources.billing import BillingResourceWithRawResponse + + return BillingResourceWithRawResponse(self._client.billing) + + @cached_property + def workspaces(self) -> workspaces.WorkspacesResourceWithRawResponse: + from .resources.workspaces import WorkspacesResourceWithRawResponse + + return WorkspacesResourceWithRawResponse(self._client.workspaces) class AsyncContextualAIWithRawResponse: _client: AsyncContextualAI @@ -595,6 +651,23 @@ def parse(self) -> parse.AsyncParseResourceWithRawResponse: return AsyncParseResourceWithRawResponse(self._client.parse) + @cached_property + def extract(self) -> extract.AsyncExtractResourceWithRawResponse: + from .resources.extract import AsyncExtractResourceWithRawResponse + + return AsyncExtractResourceWithRawResponse(self._client.extract) + + @cached_property + def billing(self) -> billing.AsyncBillingResourceWithRawResponse: + from .resources.billing import AsyncBillingResourceWithRawResponse + + return AsyncBillingResourceWithRawResponse(self._client.billing) + + @cached_property + def workspaces(self) -> workspaces.AsyncWorkspacesResourceWithRawResponse: + from .resources.workspaces import AsyncWorkspacesResourceWithRawResponse + + return AsyncWorkspacesResourceWithRawResponse(self._client.workspaces) class ContextualAIWithStreamedResponse: _client: ContextualAI @@ -644,6 +717,23 @@ def parse(self) -> parse.ParseResourceWithStreamingResponse: return ParseResourceWithStreamingResponse(self._client.parse) + @cached_property + def extract(self) -> extract.ExtractResourceWithStreamingResponse: + from .resources.extract import ExtractResourceWithStreamingResponse + + return ExtractResourceWithStreamingResponse(self._client.extract) + + @cached_property + def billing(self) -> billing.BillingResourceWithStreamingResponse: + from .resources.billing import BillingResourceWithStreamingResponse + + return BillingResourceWithStreamingResponse(self._client.billing) + + @cached_property + def workspaces(self) -> workspaces.WorkspacesResourceWithStreamingResponse: + from .resources.workspaces import WorkspacesResourceWithStreamingResponse + + return WorkspacesResourceWithStreamingResponse(self._client.workspaces) class AsyncContextualAIWithStreamedResponse: _client: AsyncContextualAI @@ -693,6 +783,23 @@ def parse(self) -> parse.AsyncParseResourceWithStreamingResponse: return AsyncParseResourceWithStreamingResponse(self._client.parse) + @cached_property + def extract(self) -> extract.AsyncExtractResourceWithStreamingResponse: + from .resources.extract import AsyncExtractResourceWithStreamingResponse + + return AsyncExtractResourceWithStreamingResponse(self._client.extract) + + @cached_property + def billing(self) -> billing.AsyncBillingResourceWithStreamingResponse: + from .resources.billing import AsyncBillingResourceWithStreamingResponse + + return AsyncBillingResourceWithStreamingResponse(self._client.billing) + + @cached_property + def workspaces(self) -> workspaces.AsyncWorkspacesResourceWithStreamingResponse: + from .resources.workspaces import AsyncWorkspacesResourceWithStreamingResponse + + return AsyncWorkspacesResourceWithStreamingResponse(self._client.workspaces) Client = ContextualAI diff --git a/src/contextual/resources/__init__.py b/src/contextual/resources/__init__.py index dc5e7f19..fa3678dd 100644 --- a/src/contextual/resources/__init__.py +++ b/src/contextual/resources/__init__.py @@ -40,6 +40,22 @@ RerankResourceWithStreamingResponse, AsyncRerankResourceWithStreamingResponse, ) +from .billing import ( + BillingResource, + AsyncBillingResource, + BillingResourceWithRawResponse, + AsyncBillingResourceWithRawResponse, + BillingResourceWithStreamingResponse, + AsyncBillingResourceWithStreamingResponse, +) +from .extract import ( + ExtractResource, + AsyncExtractResource, + ExtractResourceWithRawResponse, + AsyncExtractResourceWithRawResponse, + ExtractResourceWithStreamingResponse, + AsyncExtractResourceWithStreamingResponse, +) from .generate import ( GenerateResource, AsyncGenerateResource, @@ -56,6 +72,14 @@ DatastoresResourceWithStreamingResponse, AsyncDatastoresResourceWithStreamingResponse, ) +from .workspaces import ( + WorkspacesResource, + AsyncWorkspacesResource, + WorkspacesResourceWithRawResponse, + AsyncWorkspacesResourceWithRawResponse, + WorkspacesResourceWithStreamingResponse, + AsyncWorkspacesResourceWithStreamingResponse, +) __all__ = [ "DatastoresResource", @@ -100,4 +124,22 @@ "AsyncParseResourceWithRawResponse", "ParseResourceWithStreamingResponse", "AsyncParseResourceWithStreamingResponse", + "ExtractResource", + "AsyncExtractResource", + "ExtractResourceWithRawResponse", + "AsyncExtractResourceWithRawResponse", + "ExtractResourceWithStreamingResponse", + "AsyncExtractResourceWithStreamingResponse", + "BillingResource", + "AsyncBillingResource", + "BillingResourceWithRawResponse", + "AsyncBillingResourceWithRawResponse", + "BillingResourceWithStreamingResponse", + "AsyncBillingResourceWithStreamingResponse", + "WorkspacesResource", + "AsyncWorkspacesResource", + "WorkspacesResourceWithRawResponse", + "AsyncWorkspacesResourceWithRawResponse", + "WorkspacesResourceWithStreamingResponse", + "AsyncWorkspacesResourceWithStreamingResponse", ] diff --git a/src/contextual/resources/billing.py b/src/contextual/resources/billing.py new file mode 100644 index 00000000..e0632d6f --- /dev/null +++ b/src/contextual/resources/billing.py @@ -0,0 +1,738 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ..types import ( + billing_list_top_ups_params, + billing_retrieve_acl_usage_params, + billing_retrieve_monthly_usage_params, + billing_retrieve_billing_mode_history_params, +) +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.billing_list_top_ups_response import BillingListTopUpsResponse +from ..types.billing_retrieve_balance_response import BillingRetrieveBalanceResponse +from ..types.billing_retrieve_metadata_response import BillingRetrieveMetadataResponse +from ..types.billing_retrieve_acl_usage_response import BillingRetrieveAclUsageResponse +from ..types.billing_retrieve_monthly_usage_response import BillingRetrieveMonthlyUsageResponse +from ..types.billing_retrieve_earliest_usage_date_response import BillingRetrieveEarliestUsageDateResponse +from ..types.billing_retrieve_billing_mode_history_response import BillingRetrieveBillingModeHistoryResponse + +__all__ = ["BillingResource", "AsyncBillingResource"] + + +class BillingResource(SyncAPIResource): + @cached_property + def with_raw_response(self) -> BillingResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#accessing-raw-response-data-eg-headers + """ + return BillingResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> BillingResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#with_streaming_response + """ + return BillingResourceWithStreamingResponse(self) + + def retrieve_balance( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveBalanceResponse: + """ + Get the remaining balance for a tenant + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/balance", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BillingRetrieveBalanceResponse, + ) + + def list_top_ups( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingListTopUpsResponse: + """ + Get the top-up history for a tenant. Paginated. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/balance/top-ups", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "limit": limit, + "cursor": cursor, + }, + billing_list_top_ups_params.BillingListTopUpsParams, + ), + ), + cast_to=BillingListTopUpsResponse, + ) + + def retrieve_billing_mode_history( + self, + *, + year: int, + month: int, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveBillingModeHistoryResponse: + """ + Get the billing mode history for a tenant for a specific month. + + Args: request: Request object containing year and month with validation user_context: User context with tenant admin permissions + + Returns: Billing mode history records for the specified month and year Returns at least one entry which is the mode of the first date of the given month, with potential mode changes in the middle of the month. If no record found, defaults to LEGACY mode. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/billing_mode/history", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "year": year, + "month": month, + }, + billing_retrieve_billing_mode_history_params.BillingRetrieveBillingModeHistoryParams, + ), + ), + cast_to=BillingRetrieveBillingModeHistoryResponse, + ) + + def retrieve_metadata( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveMetadataResponse: + """ + Non admin endpoint for getting the billing metadata for a tenant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/metadata", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BillingRetrieveMetadataResponse, + ) + + def retrieve_acl_usage( + self, + *, + year: int, + month: int, + resource_id: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveAclUsageResponse: + """ + Get Agent Composer step-level usage data for a specific month. + + This API returns daily usages of advance queries grouped by steps. The data is used for visualization purposes to show users which Agent Composer steps were executed and their associated costs and token consumption. + + Note: The costs returned here are already included in the ACL_COST entry from the daily_usages table and should not be double-counted in billing. + + Args: request: Request object containing year, month, and optional resource_id user_context: User context with tenant admin permissions + + Returns: Agent Composer step usage data aggregated by step and date + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/usages/acl", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "year": year, + "month": month, + "resource_id": resource_id, + }, + billing_retrieve_acl_usage_params.BillingRetrieveAclUsageParams, + ), + ), + cast_to=BillingRetrieveAclUsageResponse, + ) + + def retrieve_earliest_usage_date( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveEarliestUsageDateResponse: + """ + Get the earliest usage date for a tenant + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/usages/earliest_date", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BillingRetrieveEarliestUsageDateResponse, + ) + + def retrieve_monthly_usage( + self, + *, + year: int, + month: int, + resource_id: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveMonthlyUsageResponse: + """ + Get monthly usage data for a tenant with validation for year and month parameters. + + Args: request: Request object containing year and month with validation user_context: User context with tenant admin permissions resource_id: Optional[UUID]. If provided, get usage data for a specific resource. Otherwise, get aggregated usage data across all resources. + + Returns: Monthly usage records for the specified month and year + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/billing/usages/monthly", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "year": year, + "month": month, + "resource_id": resource_id, + }, + billing_retrieve_monthly_usage_params.BillingRetrieveMonthlyUsageParams, + ), + ), + cast_to=BillingRetrieveMonthlyUsageResponse, + ) + + +class AsyncBillingResource(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncBillingResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#accessing-raw-response-data-eg-headers + """ + return AsyncBillingResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncBillingResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#with_streaming_response + """ + return AsyncBillingResourceWithStreamingResponse(self) + + async def retrieve_balance( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveBalanceResponse: + """ + Get the remaining balance for a tenant + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/balance", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BillingRetrieveBalanceResponse, + ) + + async def list_top_ups( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingListTopUpsResponse: + """ + Get the top-up history for a tenant. Paginated. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/balance/top-ups", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "limit": limit, + "cursor": cursor, + }, + billing_list_top_ups_params.BillingListTopUpsParams, + ), + ), + cast_to=BillingListTopUpsResponse, + ) + + async def retrieve_billing_mode_history( + self, + *, + year: int, + month: int, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveBillingModeHistoryResponse: + """ + Get the billing mode history for a tenant for a specific month. + + Args: request: Request object containing year and month with validation user_context: User context with tenant admin permissions + + Returns: Billing mode history records for the specified month and year Returns at least one entry which is the mode of the first date of the given month, with potential mode changes in the middle of the month. If no record found, defaults to LEGACY mode. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/billing_mode/history", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "year": year, + "month": month, + }, + billing_retrieve_billing_mode_history_params.BillingRetrieveBillingModeHistoryParams, + ), + ), + cast_to=BillingRetrieveBillingModeHistoryResponse, + ) + + async def retrieve_metadata( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveMetadataResponse: + """ + Non admin endpoint for getting the billing metadata for a tenant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/metadata", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BillingRetrieveMetadataResponse, + ) + + async def retrieve_acl_usage( + self, + *, + year: int, + month: int, + resource_id: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveAclUsageResponse: + """ + Get Agent Composer step-level usage data for a specific month. + + This API returns daily usages of advance queries grouped by steps. The data is used for visualization purposes to show users which Agent Composer steps were executed and their associated costs and token consumption. + + Note: The costs returned here are already included in the ACL_COST entry from the daily_usages table and should not be double-counted in billing. + + Args: request: Request object containing year, month, and optional resource_id user_context: User context with tenant admin permissions + + Returns: Agent Composer step usage data aggregated by step and date + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/usages/acl", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "year": year, + "month": month, + "resource_id": resource_id, + }, + billing_retrieve_acl_usage_params.BillingRetrieveAclUsageParams, + ), + ), + cast_to=BillingRetrieveAclUsageResponse, + ) + + async def retrieve_earliest_usage_date( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveEarliestUsageDateResponse: + """ + Get the earliest usage date for a tenant + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/usages/earliest_date", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BillingRetrieveEarliestUsageDateResponse, + ) + + async def retrieve_monthly_usage( + self, + *, + year: int, + month: int, + resource_id: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BillingRetrieveMonthlyUsageResponse: + """ + Get monthly usage data for a tenant with validation for year and month parameters. + + Args: request: Request object containing year and month with validation user_context: User context with tenant admin permissions resource_id: Optional[UUID]. If provided, get usage data for a specific resource. Otherwise, get aggregated usage data across all resources. + + Returns: Monthly usage records for the specified month and year + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/billing/usages/monthly", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "year": year, + "month": month, + "resource_id": resource_id, + }, + billing_retrieve_monthly_usage_params.BillingRetrieveMonthlyUsageParams, + ), + ), + cast_to=BillingRetrieveMonthlyUsageResponse, + ) + + +class BillingResourceWithRawResponse: + def __init__(self, billing: BillingResource) -> None: + self._billing = billing + + self.retrieve_balance = to_raw_response_wrapper( + billing.retrieve_balance, + ) + self.list_top_ups = to_raw_response_wrapper( + billing.list_top_ups, + ) + self.retrieve_billing_mode_history = to_raw_response_wrapper( + billing.retrieve_billing_mode_history, + ) + self.retrieve_metadata = to_raw_response_wrapper( + billing.retrieve_metadata, + ) + self.retrieve_acl_usage = to_raw_response_wrapper( + billing.retrieve_acl_usage, + ) + self.retrieve_earliest_usage_date = to_raw_response_wrapper( + billing.retrieve_earliest_usage_date, + ) + self.retrieve_monthly_usage = to_raw_response_wrapper( + billing.retrieve_monthly_usage, + ) + + +class AsyncBillingResourceWithRawResponse: + def __init__(self, billing: AsyncBillingResource) -> None: + self._billing = billing + + self.retrieve_balance = async_to_raw_response_wrapper( + billing.retrieve_balance, + ) + self.list_top_ups = async_to_raw_response_wrapper( + billing.list_top_ups, + ) + self.retrieve_billing_mode_history = async_to_raw_response_wrapper( + billing.retrieve_billing_mode_history, + ) + self.retrieve_metadata = async_to_raw_response_wrapper( + billing.retrieve_metadata, + ) + self.retrieve_acl_usage = async_to_raw_response_wrapper( + billing.retrieve_acl_usage, + ) + self.retrieve_earliest_usage_date = async_to_raw_response_wrapper( + billing.retrieve_earliest_usage_date, + ) + self.retrieve_monthly_usage = async_to_raw_response_wrapper( + billing.retrieve_monthly_usage, + ) + + +class BillingResourceWithStreamingResponse: + def __init__(self, billing: BillingResource) -> None: + self._billing = billing + + self.retrieve_balance = to_streamed_response_wrapper( + billing.retrieve_balance, + ) + self.list_top_ups = to_streamed_response_wrapper( + billing.list_top_ups, + ) + self.retrieve_billing_mode_history = to_streamed_response_wrapper( + billing.retrieve_billing_mode_history, + ) + self.retrieve_metadata = to_streamed_response_wrapper( + billing.retrieve_metadata, + ) + self.retrieve_acl_usage = to_streamed_response_wrapper( + billing.retrieve_acl_usage, + ) + self.retrieve_earliest_usage_date = to_streamed_response_wrapper( + billing.retrieve_earliest_usage_date, + ) + self.retrieve_monthly_usage = to_streamed_response_wrapper( + billing.retrieve_monthly_usage, + ) + + +class AsyncBillingResourceWithStreamingResponse: + def __init__(self, billing: AsyncBillingResource) -> None: + self._billing = billing + + self.retrieve_balance = async_to_streamed_response_wrapper( + billing.retrieve_balance, + ) + self.list_top_ups = async_to_streamed_response_wrapper( + billing.list_top_ups, + ) + self.retrieve_billing_mode_history = async_to_streamed_response_wrapper( + billing.retrieve_billing_mode_history, + ) + self.retrieve_metadata = async_to_streamed_response_wrapper( + billing.retrieve_metadata, + ) + self.retrieve_acl_usage = async_to_streamed_response_wrapper( + billing.retrieve_acl_usage, + ) + self.retrieve_earliest_usage_date = async_to_streamed_response_wrapper( + billing.retrieve_earliest_usage_date, + ) + self.retrieve_monthly_usage = async_to_streamed_response_wrapper( + billing.retrieve_monthly_usage, + ) diff --git a/src/contextual/resources/extract.py b/src/contextual/resources/extract.py new file mode 100644 index 00000000..2499012d --- /dev/null +++ b/src/contextual/resources/extract.py @@ -0,0 +1,1998 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Mapping, cast + +import httpx + +from ..types import ( + extract_list_jobs_params, + extract_create_job_params, + extract_list_schemas_params, + extract_create_schema_params, + extract_update_schema_params, + extract_list_documents_params, + extract_upload_document_params, + extract_update_job_results_params, +) +from .._types import Body, Omit, Query, Headers, NotGiven, FileTypes, omit, not_given +from .._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.extract_list_jobs_response import ExtractListJobsResponse +from ..types.extract_create_job_response import ExtractCreateJobResponse +from ..types.extract_list_schemas_response import ExtractListSchemasResponse +from ..types.extract_retrieve_job_response import ExtractRetrieveJobResponse +from ..types.extract_create_schema_response import ExtractCreateSchemaResponse +from ..types.extract_delete_schema_response import ExtractDeleteSchemaResponse +from ..types.extract_update_schema_response import ExtractUpdateSchemaResponse +from ..types.extract_list_documents_response import ExtractListDocumentsResponse +from ..types.extract_delete_document_response import ExtractDeleteDocumentResponse +from ..types.extract_retrieve_schema_response import ExtractRetrieveSchemaResponse +from ..types.extract_upload_document_response import ExtractUploadDocumentResponse +from ..types.extract_retrieve_document_response import ExtractRetrieveDocumentResponse +from ..types.extract_retrieve_job_results_response import ExtractRetrieveJobResultsResponse + +__all__ = ["ExtractResource", "AsyncExtractResource"] + + +class ExtractResource(SyncAPIResource): + @cached_property + def with_raw_response(self) -> ExtractResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#accessing-raw-response-data-eg-headers + """ + return ExtractResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ExtractResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#with_streaming_response + """ + return ExtractResourceWithStreamingResponse(self) + + def delete_document( + self, + document_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractDeleteDocumentResponse: + """ + Delete a document. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not document_id: + raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}") + return self._delete( + f"/extract/documents/{document_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractDeleteDocumentResponse, + ) + + def delete_schema( + self, + schema_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractDeleteSchemaResponse: + """ + Delete a schema. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schema_id: + raise ValueError(f"Expected a non-empty value for `schema_id` but received {schema_id!r}") + return self._delete( + f"/extract/schemas/{schema_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractDeleteSchemaResponse, + ) + + def list_documents( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + search: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractListDocumentsResponse: + """ + List documents for structured extraction. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/extract/documents", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "limit": limit, + "cursor": cursor, + "search": search, + }, + extract_list_documents_params.ExtractListDocumentsParams, + ), + ), + cast_to=ExtractListDocumentsResponse, + ) + + def retrieve_document( + self, + document_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveDocumentResponse: + """ + Get document information by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not document_id: + raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}") + return self._get( + f"/extract/documents/{document_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveDocumentResponse, + ) + + def list_jobs( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + job_status: object | Omit = omit, + search: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractListJobsResponse: + """ + List extraction jobs. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/extract/jobs", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "limit": limit, + "cursor": cursor, + "job_status": job_status, + "search": search, + }, + extract_list_jobs_params.ExtractListJobsParams, + ), + ), + cast_to=ExtractListJobsResponse, + ) + + def retrieve_job( + self, + job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveJobResponse: + """ + Get the status of an extraction job. + + For running jobs with a Temporal workflow, returns accumulated results and failed subtrees from workflow queries. For completed/failed jobs or jobs without workflow, these fields are empty. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not job_id: + raise ValueError(f"Expected a non-empty value for `job_id` but received {job_id!r}") + return self._get( + f"/extract/jobs/{job_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveJobResponse, + ) + + def retrieve_job_results( + self, + job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveJobResultsResponse: + """ + Get the results of a completed extraction job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not job_id: + raise ValueError(f"Expected a non-empty value for `job_id` but received {job_id!r}") + return self._get( + f"/extract/jobs/{job_id}/results", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveJobResultsResponse, + ) + + def list_schemas( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + search: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractListSchemasResponse: + """ + List schemas with optional search. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/extract/schemas", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "limit": limit, + "cursor": cursor, + "search": search, + }, + extract_list_schemas_params.ExtractListSchemasParams, + ), + ), + cast_to=ExtractListSchemasResponse, + ) + + def retrieve_schema( + self, + schema_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveSchemaResponse: + """ + Get schema information by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schema_id: + raise ValueError(f"Expected a non-empty value for `schema_id` but received {schema_id!r}") + return self._get( + f"/extract/schemas/{schema_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveSchemaResponse, + ) + + def upload_document( + self, + *, + file: FileTypes, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractUploadDocumentResponse: + """ + Upload a document for structured extraction. + + Uploads a PDF document that can be used for structured data extraction. Only PDF files are supported. + + Supported File Types: + + 1. PDF files only (`.pdf` extension) + 2. Maximum file size: 50MB (recommended) + 3. Documents are processed and validated upon upload + + Document Processing: + + 1. File size and page count are automatically calculated + 2. Document is validated for PDF format and readability + 3. Metadata is extracted and stored for future reference + 4. Document is stored securely and can be referenced by ID + + Usage: + + After uploading, you'll receive a `document_id` that can be used with: + + 1. `POST /jobs` endpoint to start extraction jobs + 2. `GET /documents/{document_id}` to retrieve document information + 3. `DELETE /documents/{document_id}` to remove the document + + Example Response: + ```json + { + "document_id": "123e4567-e89b-12d3-a456-426614174000", + "file_name": "financial_report.pdf", + "file_size": 2048576, + "page_count": 45, + "uploaded_at": "2025-01-11T18:35:00Z", + "status": "uploaded" + } + ``` + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + return self._post( + "/extract/documents/upload", + body=maybe_transform(body, extract_upload_document_params.ExtractUploadDocumentParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractUploadDocumentResponse, + ) + + def create_job( + self, + *, + document_id: str, + schema_id: str, + config: object | Omit = omit, + stream: bool | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractCreateJobResponse: + """ + Start a new structured extraction job. + + Extracts structured data from a PDF document using AI models based on a JSON Schema. The `document_id` and `schema_id` must be valid UUIDs of previously uploaded documents and created schemas. + + How It Works: + + 1. Document Processing: The system analyzes the PDF document and splits it into manageable sections + 2. Schema Analysis: Your JSON schema is parsed and validated for supported features + 3. Extraction: The pipeline processes each section and extracts data according to your schema + 4. Validation: Extracted data is validated against your schema to ensure constraints and requirements are met + 5. Results: Structured data is returned in the format defined by your schema + + Supported Models: + + 1. `gemini-2.5-flash`: Fast, cost-effective model for most use cases (default) + 2. `gemini-2.5-pro`: More powerful model for complex extractions + + Configuration Options: + + Basic Settings: + + 1. `model`: AI model to use for extraction + 2. `max_num_concurrent_requests`: Number of parallel processing requests (1-20) + 3. `validate_response_schema`: Whether to validate extracted data against schema + + Advanced Settings: + + 1. `per_key_attribution`: Enable detailed reasoning and confidence scores for each field + 2. `temperature`: Control randomness in AI responses (0.0-2.0) + 3. `seed`: Set random seed for reproducible results + 4. `enable_thinking`: Show AI reasoning process + 5. `n_max_retries`: Maximum retry attempts for failed requests + + Streaming Mode (`stream=true`): + + When `stream=true`, the endpoint returns an SSE stream instead of a job ID. Results are streamed as subtrees complete, enabling real-time progress visibility in the frontend. + + - Response: SSE stream (`text/event-stream`) with events: `start`, `subtree_result`, `subtree_error`, `agentic_array_progress` + - Job records are still created and results persisted (retrievable via `GET /jobs/{job_id}`) + - Always durable: Uses Temporal workflow—job continues running even if client disconnects + - Automatic retries: Temporal handles activity failures and retries automatically + - Use case: Interactive frontend UI where users want real-time extraction progress + + SSE Event Types: + + 1. `start`: Emitted once with `job_id`, `total_subtrees`, and `start_time` + 2. `subtree_result`: Emitted per successful subtree with `extracted_result`, `attributions`, `usage_metadata` + 3. `subtree_error`: Emitted per failed subtree with `error_message` and `error_type` + + See `STREAMING-DESIGN.md` for full protocol specification. + + Job Lifecycle: + + 1. `pending`: Job is queued and waiting to start + 2. `processing`: AI is actively extracting data from the document + 3. `completed`: Extraction finished successfully with results + 4. `failed`: Extraction failed due to an error + 5. `cancelled`: Job was cancelled before completion + + Monitoring Progress: + + Use the `GET /jobs/{job_id}` endpoint to check job status and progress: + + 1. `completion_percentage`: Overall progress (0-100) + 2. `current_step`: Current processing stage + 3. `fields_processed`: Number of schema fields completed + 4. `total_fields`: Total number of schema fields to process + + Getting Results: + + Once a job is completed, use `GET /jobs/{job_id}/results` to retrieve: + + 1. `results`: Extracted data conforming to your schema + 2. `metadata`: Processing information, costs, and performance metrics + 3. `attributions`: (if enabled) Reasoning and confidence scores for each field + + Example Request: + ```json + { + "document_id": "123e4567-e89b-12d3-a456-426614174000", + "schema_id": "987fcdeb-51a2-43d1-b456-426614174000", + "config": { + "model": "gemini-2.5-flash", + "per_key_attribution": true, + "temperature": 0.1, + "enable_thinking": true + "additional_instructions": "Extract information only about company X. Do not include information about company Y." + } + } + ``` + + Example Response: + ```json + { + "job_id": "456e7890-e89b-12d3-a456-426614174000", + "status": "pending", + "created_at": "2025-01-11T18:35:00Z", + "estimated_completion": "2025-01-11T18:40:00Z" + } + ``` + + Error Handling: + + Document and schema validation occurs before job creation for both streaming and non-streaming paths: + + - `400`: Bad Request (invalid `document_id` or `schema_id` format) + - `404`: Not Found (document or schema not found) + - `422`: Unprocessable Entity (invalid schema definition) + - `429`: Too Many Requests (user has exceeded concurrency limit of 5 active jobs) + - `500`: Internal Server Error (processing error) + + Args: + document_id: ID of the document to extract from + + schema_id: ID of the schema to use for extraction + + config: Configuration options for the extraction process + + stream: Whether to stream the results as they become available. If true, the response will be a stream of JSON objects. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/extract/jobs", + body=maybe_transform( + { + "document_id": document_id, + "schema_id": schema_id, + "config": config, + "stream": stream, + }, + extract_create_job_params.ExtractCreateJobParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractCreateJobResponse, + ) + + def create_schema( + self, + *, + name: str, + schema_definition: Dict[str, object], + description: object | Omit = omit, + metadata: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractCreateSchemaResponse: + """ + Create a new extraction schema. + + Creates a JSON Schema that defines the structure of data to extract from documents. The schema must conform to our supported subset of JSON Schema 2020-12 features. + + Supported Schema Features: + + Basic Types: + + 1. `string`: Text data with optional constraints (`minLength`, `maxLength`, `pattern`, `enum`) + 2. `integer`: Whole numbers with optional constraints (`minimum`, `maximum`, `enum`) + 3. `number`: Decimal numbers with optional constraints (`minimum`, `maximum`, `enum`) + 4. `boolean`: True/false values + 5. `null`: Null values (often used with `anyOf` for optional fields) + + Complex Types: + + 1. `object`: Key-value pairs with defined properties + 2. `array`: Lists of items with defined item schemas + 3. `anyOf`: Union types (e.g., string or null for optional fields) + + String Formats: + + Supported formats: `date-time`, `time`, `date`, `duration`, `email`, `hostname`, `ipv4`, `ipv6`, `uuid`, `uri` + + Schema Structure: + + 1. Root schema must be an `object` type + 2. Use `$defs` for reusable schema components + 3. Use `$ref` to reference definitions + 4. Arrays must have `items` schema defined + + Constraints: + + 1. Maximum 10 leaf nodes per array (prevents overly complex schemas) + 2. No circular references in `$ref` definitions + 3. String formats must be from the supported list + + Example Schemas: + + Simple Company Schema: + ```json + { + "type": "object", + "properties": { + "company_name": { + "type": "string", + "description": "The name of the company exactly as it appears in the document" + }, + "form_type": { + "type": "string", + "enum": ["10-K", "10-Q", "8-K", "S-1"], + "description": "The type of SEC form" + }, + "trading_symbol": { + "type": "string", + "description": "The trading symbol of the company" + }, + "zip_code": { + "type": "integer", + "description": "The zip code of the company headquarters" + } + }, + "required": ["company_name", "form_type", "trading_symbol", "zip_code"] + } + ``` + + Complex Resume Schema: + ```json + { + "type": "object", + "properties": { + "personalInfo": { + "type": "object", + "properties": { + "fullName": {"type": "string"}, + "contact": { + "type": "object", + "properties": { + "emails": { + "type": "array", + "items": {"type": "string", "format": "email"} + }, + "phones": { + "type": "array", + "items": {"type": "string"} + } + } + } + }, + "required": ["fullName"] + }, + "workExperience": { + "type": "array", + "items": { + "type": "object", + "properties": { + "jobTitle": {"type": "string"}, + "company": {"type": "string"}, + "startDate": {"type": "string"}, + "endDate": {"type": ["string", "null"]}, + "isCurrent": {"type": "boolean"} + }, + "required": ["jobTitle", "company", "startDate"] + } + } + }, + "required": ["personalInfo", "workExperience"] + } + ``` + + Schema with References: + ```json + { + "type": "object", + "properties": { + "algorithms": { + "type": "array", + "items": {"$ref": "#/$defs/algorithm"} + } + }, + "$defs": { + "algorithm": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "description": {"type": "string"} + }, + "required": ["name"] + } + } + } + ``` + + Best Practices: + + 1. Use descriptive field names that clearly indicate what data should be extracted + 2. Add detailed descriptions to help the AI understand what to extract + 3. Use `enum` for known values (e.g., form types, status values) + 4. Make fields optional by using `anyOf` with `null` or omitting from `required` + 5. Use arrays for lists of similar items (e.g., work experience, education) + 6. Keep schemas focused - avoid overly complex nested structures + 7. Test with sample documents to ensure the schema captures the expected data + + Args: + name: Name of the schema + + description: Description of the schema + + schema_definition: JSON Schema definition. Must be a valid JSON Schema that defines the structure of data to extract from documents. See the comprehensive schema guide in the API documentation for detailed examples and supported features. + + metadata: Additional metadata for the schema + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/extract/schemas", + body=maybe_transform( + { + "name": name, + "description": description, + "schema_definition": schema_definition, + "metadata": metadata, + }, + extract_create_schema_params.ExtractCreateSchemaParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractCreateSchemaResponse, + ) + + def update_job_results( + self, + job_id: str, + *, + results: Dict[str, object], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> object: + """ + Update the results of a completed extraction job. + + Args: + results: Extracted results conforming to the provided JSON Schema. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not job_id: + raise ValueError(f"Expected a non-empty value for `job_id` but received {job_id!r}") + return self._put( + f"/extract/jobs/{job_id}/results", + body=maybe_transform( + { + "results": results, + }, + extract_update_job_results_params.ExtractUpdateJobResultsParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=object, + ) + + def update_schema( + self, + schema_id: str, + *, + name: object | Omit = omit, + description: object | Omit = omit, + schema_definition: object | Omit = omit, + metadata: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractUpdateSchemaResponse: + """ + Update an existing schema. + + Args: + name: Name of the schema + + description: Description of the schema + + schema_definition: JSON schema definition + + metadata: Additional metadata + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schema_id: + raise ValueError(f"Expected a non-empty value for `schema_id` but received {schema_id!r}") + return self._put( + f"/extract/schemas/{schema_id}", + body=maybe_transform( + { + "name": name, + "description": description, + "schema_definition": schema_definition, + "metadata": metadata, + }, + extract_update_schema_params.ExtractUpdateSchemaParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractUpdateSchemaResponse, + ) + + +class AsyncExtractResource(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncExtractResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#accessing-raw-response-data-eg-headers + """ + return AsyncExtractResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncExtractResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#with_streaming_response + """ + return AsyncExtractResourceWithStreamingResponse(self) + + async def delete_document( + self, + document_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractDeleteDocumentResponse: + """ + Delete a document. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not document_id: + raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}") + return await self._delete( + f"/extract/documents/{document_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractDeleteDocumentResponse, + ) + + async def delete_schema( + self, + schema_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractDeleteSchemaResponse: + """ + Delete a schema. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schema_id: + raise ValueError(f"Expected a non-empty value for `schema_id` but received {schema_id!r}") + return await self._delete( + f"/extract/schemas/{schema_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractDeleteSchemaResponse, + ) + + async def list_documents( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + search: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractListDocumentsResponse: + """ + List documents for structured extraction. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/extract/documents", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "limit": limit, + "cursor": cursor, + "search": search, + }, + extract_list_documents_params.ExtractListDocumentsParams, + ), + ), + cast_to=ExtractListDocumentsResponse, + ) + + async def retrieve_document( + self, + document_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveDocumentResponse: + """ + Get document information by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not document_id: + raise ValueError(f"Expected a non-empty value for `document_id` but received {document_id!r}") + return await self._get( + f"/extract/documents/{document_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveDocumentResponse, + ) + + async def list_jobs( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + job_status: object | Omit = omit, + search: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractListJobsResponse: + """ + List extraction jobs. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/extract/jobs", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "limit": limit, + "cursor": cursor, + "job_status": job_status, + "search": search, + }, + extract_list_jobs_params.ExtractListJobsParams, + ), + ), + cast_to=ExtractListJobsResponse, + ) + + async def retrieve_job( + self, + job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveJobResponse: + """ + Get the status of an extraction job. + + For running jobs with a Temporal workflow, returns accumulated results and failed subtrees from workflow queries. For completed/failed jobs or jobs without workflow, these fields are empty. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not job_id: + raise ValueError(f"Expected a non-empty value for `job_id` but received {job_id!r}") + return await self._get( + f"/extract/jobs/{job_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveJobResponse, + ) + + async def retrieve_job_results( + self, + job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveJobResultsResponse: + """ + Get the results of a completed extraction job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not job_id: + raise ValueError(f"Expected a non-empty value for `job_id` but received {job_id!r}") + return await self._get( + f"/extract/jobs/{job_id}/results", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveJobResultsResponse, + ) + + async def list_schemas( + self, + *, + limit: int | Omit = omit, + cursor: object | Omit = omit, + search: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractListSchemasResponse: + """ + List schemas with optional search. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/extract/schemas", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "limit": limit, + "cursor": cursor, + "search": search, + }, + extract_list_schemas_params.ExtractListSchemasParams, + ), + ), + cast_to=ExtractListSchemasResponse, + ) + + async def retrieve_schema( + self, + schema_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractRetrieveSchemaResponse: + """ + Get schema information by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schema_id: + raise ValueError(f"Expected a non-empty value for `schema_id` but received {schema_id!r}") + return await self._get( + f"/extract/schemas/{schema_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractRetrieveSchemaResponse, + ) + + async def upload_document( + self, + *, + file: FileTypes, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractUploadDocumentResponse: + """ + Upload a document for structured extraction. + + Uploads a PDF document that can be used for structured data extraction. Only PDF files are supported. + + Supported File Types: + + 1. PDF files only (`.pdf` extension) + 2. Maximum file size: 50MB (recommended) + 3. Documents are processed and validated upon upload + + Document Processing: + + 1. File size and page count are automatically calculated + 2. Document is validated for PDF format and readability + 3. Metadata is extracted and stored for future reference + 4. Document is stored securely and can be referenced by ID + + Usage: + + After uploading, you'll receive a `document_id` that can be used with: + + 1. `POST /jobs` endpoint to start extraction jobs + 2. `GET /documents/{document_id}` to retrieve document information + 3. `DELETE /documents/{document_id}` to remove the document + + Example Response: + ```json + { + "document_id": "123e4567-e89b-12d3-a456-426614174000", + "file_name": "financial_report.pdf", + "file_size": 2048576, + "page_count": 45, + "uploaded_at": "2025-01-11T18:35:00Z", + "status": "uploaded" + } + ``` + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + return await self._post( + "/extract/documents/upload", + body=await async_maybe_transform(body, extract_upload_document_params.ExtractUploadDocumentParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractUploadDocumentResponse, + ) + + async def create_job( + self, + *, + document_id: str, + schema_id: str, + config: object | Omit = omit, + stream: bool | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractCreateJobResponse: + """ + Start a new structured extraction job. + + Extracts structured data from a PDF document using AI models based on a JSON Schema. The `document_id` and `schema_id` must be valid UUIDs of previously uploaded documents and created schemas. + + How It Works: + + 1. Document Processing: The system analyzes the PDF document and splits it into manageable sections + 2. Schema Analysis: Your JSON schema is parsed and validated for supported features + 3. Extraction: The pipeline processes each section and extracts data according to your schema + 4. Validation: Extracted data is validated against your schema to ensure constraints and requirements are met + 5. Results: Structured data is returned in the format defined by your schema + + Supported Models: + + 1. `gemini-2.5-flash`: Fast, cost-effective model for most use cases (default) + 2. `gemini-2.5-pro`: More powerful model for complex extractions + + Configuration Options: + + Basic Settings: + + 1. `model`: AI model to use for extraction + 2. `max_num_concurrent_requests`: Number of parallel processing requests (1-20) + 3. `validate_response_schema`: Whether to validate extracted data against schema + + Advanced Settings: + + 1. `per_key_attribution`: Enable detailed reasoning and confidence scores for each field + 2. `temperature`: Control randomness in AI responses (0.0-2.0) + 3. `seed`: Set random seed for reproducible results + 4. `enable_thinking`: Show AI reasoning process + 5. `n_max_retries`: Maximum retry attempts for failed requests + + Streaming Mode (`stream=true`): + + When `stream=true`, the endpoint returns an SSE stream instead of a job ID. Results are streamed as subtrees complete, enabling real-time progress visibility in the frontend. + + - Response: SSE stream (`text/event-stream`) with events: `start`, `subtree_result`, `subtree_error`, `agentic_array_progress` + - Job records are still created and results persisted (retrievable via `GET /jobs/{job_id}`) + - Always durable: Uses Temporal workflow—job continues running even if client disconnects + - Automatic retries: Temporal handles activity failures and retries automatically + - Use case: Interactive frontend UI where users want real-time extraction progress + + SSE Event Types: + + 1. `start`: Emitted once with `job_id`, `total_subtrees`, and `start_time` + 2. `subtree_result`: Emitted per successful subtree with `extracted_result`, `attributions`, `usage_metadata` + 3. `subtree_error`: Emitted per failed subtree with `error_message` and `error_type` + + See `STREAMING-DESIGN.md` for full protocol specification. + + Job Lifecycle: + + 1. `pending`: Job is queued and waiting to start + 2. `processing`: AI is actively extracting data from the document + 3. `completed`: Extraction finished successfully with results + 4. `failed`: Extraction failed due to an error + 5. `cancelled`: Job was cancelled before completion + + Monitoring Progress: + + Use the `GET /jobs/{job_id}` endpoint to check job status and progress: + + 1. `completion_percentage`: Overall progress (0-100) + 2. `current_step`: Current processing stage + 3. `fields_processed`: Number of schema fields completed + 4. `total_fields`: Total number of schema fields to process + + Getting Results: + + Once a job is completed, use `GET /jobs/{job_id}/results` to retrieve: + + 1. `results`: Extracted data conforming to your schema + 2. `metadata`: Processing information, costs, and performance metrics + 3. `attributions`: (if enabled) Reasoning and confidence scores for each field + + Example Request: + ```json + { + "document_id": "123e4567-e89b-12d3-a456-426614174000", + "schema_id": "987fcdeb-51a2-43d1-b456-426614174000", + "config": { + "model": "gemini-2.5-flash", + "per_key_attribution": true, + "temperature": 0.1, + "enable_thinking": true + "additional_instructions": "Extract information only about company X. Do not include information about company Y." + } + } + ``` + + Example Response: + ```json + { + "job_id": "456e7890-e89b-12d3-a456-426614174000", + "status": "pending", + "created_at": "2025-01-11T18:35:00Z", + "estimated_completion": "2025-01-11T18:40:00Z" + } + ``` + + Error Handling: + + Document and schema validation occurs before job creation for both streaming and non-streaming paths: + + - `400`: Bad Request (invalid `document_id` or `schema_id` format) + - `404`: Not Found (document or schema not found) + - `422`: Unprocessable Entity (invalid schema definition) + - `429`: Too Many Requests (user has exceeded concurrency limit of 5 active jobs) + - `500`: Internal Server Error (processing error) + + Args: + document_id: ID of the document to extract from + + schema_id: ID of the schema to use for extraction + + config: Configuration options for the extraction process + + stream: Whether to stream the results as they become available. If true, the response will be a stream of JSON objects. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/extract/jobs", + body=await async_maybe_transform( + { + "document_id": document_id, + "schema_id": schema_id, + "config": config, + "stream": stream, + }, + extract_create_job_params.ExtractCreateJobParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractCreateJobResponse, + ) + + async def create_schema( + self, + *, + name: str, + schema_definition: Dict[str, object], + description: object | Omit = omit, + metadata: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractCreateSchemaResponse: + """ + Create a new extraction schema. + + Creates a JSON Schema that defines the structure of data to extract from documents. The schema must conform to our supported subset of JSON Schema 2020-12 features. + + Supported Schema Features: + + Basic Types: + + 1. `string`: Text data with optional constraints (`minLength`, `maxLength`, `pattern`, `enum`) + 2. `integer`: Whole numbers with optional constraints (`minimum`, `maximum`, `enum`) + 3. `number`: Decimal numbers with optional constraints (`minimum`, `maximum`, `enum`) + 4. `boolean`: True/false values + 5. `null`: Null values (often used with `anyOf` for optional fields) + + Complex Types: + + 1. `object`: Key-value pairs with defined properties + 2. `array`: Lists of items with defined item schemas + 3. `anyOf`: Union types (e.g., string or null for optional fields) + + String Formats: + + Supported formats: `date-time`, `time`, `date`, `duration`, `email`, `hostname`, `ipv4`, `ipv6`, `uuid`, `uri` + + Schema Structure: + + 1. Root schema must be an `object` type + 2. Use `$defs` for reusable schema components + 3. Use `$ref` to reference definitions + 4. Arrays must have `items` schema defined + + Constraints: + + 1. Maximum 10 leaf nodes per array (prevents overly complex schemas) + 2. No circular references in `$ref` definitions + 3. String formats must be from the supported list + + Example Schemas: + + Simple Company Schema: + ```json + { + "type": "object", + "properties": { + "company_name": { + "type": "string", + "description": "The name of the company exactly as it appears in the document" + }, + "form_type": { + "type": "string", + "enum": ["10-K", "10-Q", "8-K", "S-1"], + "description": "The type of SEC form" + }, + "trading_symbol": { + "type": "string", + "description": "The trading symbol of the company" + }, + "zip_code": { + "type": "integer", + "description": "The zip code of the company headquarters" + } + }, + "required": ["company_name", "form_type", "trading_symbol", "zip_code"] + } + ``` + + Complex Resume Schema: + ```json + { + "type": "object", + "properties": { + "personalInfo": { + "type": "object", + "properties": { + "fullName": {"type": "string"}, + "contact": { + "type": "object", + "properties": { + "emails": { + "type": "array", + "items": {"type": "string", "format": "email"} + }, + "phones": { + "type": "array", + "items": {"type": "string"} + } + } + } + }, + "required": ["fullName"] + }, + "workExperience": { + "type": "array", + "items": { + "type": "object", + "properties": { + "jobTitle": {"type": "string"}, + "company": {"type": "string"}, + "startDate": {"type": "string"}, + "endDate": {"type": ["string", "null"]}, + "isCurrent": {"type": "boolean"} + }, + "required": ["jobTitle", "company", "startDate"] + } + } + }, + "required": ["personalInfo", "workExperience"] + } + ``` + + Schema with References: + ```json + { + "type": "object", + "properties": { + "algorithms": { + "type": "array", + "items": {"$ref": "#/$defs/algorithm"} + } + }, + "$defs": { + "algorithm": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "description": {"type": "string"} + }, + "required": ["name"] + } + } + } + ``` + + Best Practices: + + 1. Use descriptive field names that clearly indicate what data should be extracted + 2. Add detailed descriptions to help the AI understand what to extract + 3. Use `enum` for known values (e.g., form types, status values) + 4. Make fields optional by using `anyOf` with `null` or omitting from `required` + 5. Use arrays for lists of similar items (e.g., work experience, education) + 6. Keep schemas focused - avoid overly complex nested structures + 7. Test with sample documents to ensure the schema captures the expected data + + Args: + name: Name of the schema + + description: Description of the schema + + schema_definition: JSON Schema definition. Must be a valid JSON Schema that defines the structure of data to extract from documents. See the comprehensive schema guide in the API documentation for detailed examples and supported features. + + metadata: Additional metadata for the schema + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/extract/schemas", + body=await async_maybe_transform( + { + "name": name, + "description": description, + "schema_definition": schema_definition, + "metadata": metadata, + }, + extract_create_schema_params.ExtractCreateSchemaParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractCreateSchemaResponse, + ) + + async def update_job_results( + self, + job_id: str, + *, + results: Dict[str, object], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> object: + """ + Update the results of a completed extraction job. + + Args: + results: Extracted results conforming to the provided JSON Schema. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not job_id: + raise ValueError(f"Expected a non-empty value for `job_id` but received {job_id!r}") + return await self._put( + f"/extract/jobs/{job_id}/results", + body=await async_maybe_transform( + { + "results": results, + }, + extract_update_job_results_params.ExtractUpdateJobResultsParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=object, + ) + + async def update_schema( + self, + schema_id: str, + *, + name: object | Omit = omit, + description: object | Omit = omit, + schema_definition: object | Omit = omit, + metadata: object | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ExtractUpdateSchemaResponse: + """ + Update an existing schema. + + Args: + name: Name of the schema + + description: Description of the schema + + schema_definition: JSON schema definition + + metadata: Additional metadata + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schema_id: + raise ValueError(f"Expected a non-empty value for `schema_id` but received {schema_id!r}") + return await self._put( + f"/extract/schemas/{schema_id}", + body=await async_maybe_transform( + { + "name": name, + "description": description, + "schema_definition": schema_definition, + "metadata": metadata, + }, + extract_update_schema_params.ExtractUpdateSchemaParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ExtractUpdateSchemaResponse, + ) + + +class ExtractResourceWithRawResponse: + def __init__(self, extract: ExtractResource) -> None: + self._extract = extract + + self.delete_document = to_raw_response_wrapper( + extract.delete_document, + ) + self.delete_schema = to_raw_response_wrapper( + extract.delete_schema, + ) + self.list_documents = to_raw_response_wrapper( + extract.list_documents, + ) + self.retrieve_document = to_raw_response_wrapper( + extract.retrieve_document, + ) + self.list_jobs = to_raw_response_wrapper( + extract.list_jobs, + ) + self.retrieve_job = to_raw_response_wrapper( + extract.retrieve_job, + ) + self.retrieve_job_results = to_raw_response_wrapper( + extract.retrieve_job_results, + ) + self.list_schemas = to_raw_response_wrapper( + extract.list_schemas, + ) + self.retrieve_schema = to_raw_response_wrapper( + extract.retrieve_schema, + ) + self.upload_document = to_raw_response_wrapper( + extract.upload_document, + ) + self.create_job = to_raw_response_wrapper( + extract.create_job, + ) + self.create_schema = to_raw_response_wrapper( + extract.create_schema, + ) + self.update_job_results = to_raw_response_wrapper( + extract.update_job_results, + ) + self.update_schema = to_raw_response_wrapper( + extract.update_schema, + ) + + +class AsyncExtractResourceWithRawResponse: + def __init__(self, extract: AsyncExtractResource) -> None: + self._extract = extract + + self.delete_document = async_to_raw_response_wrapper( + extract.delete_document, + ) + self.delete_schema = async_to_raw_response_wrapper( + extract.delete_schema, + ) + self.list_documents = async_to_raw_response_wrapper( + extract.list_documents, + ) + self.retrieve_document = async_to_raw_response_wrapper( + extract.retrieve_document, + ) + self.list_jobs = async_to_raw_response_wrapper( + extract.list_jobs, + ) + self.retrieve_job = async_to_raw_response_wrapper( + extract.retrieve_job, + ) + self.retrieve_job_results = async_to_raw_response_wrapper( + extract.retrieve_job_results, + ) + self.list_schemas = async_to_raw_response_wrapper( + extract.list_schemas, + ) + self.retrieve_schema = async_to_raw_response_wrapper( + extract.retrieve_schema, + ) + self.upload_document = async_to_raw_response_wrapper( + extract.upload_document, + ) + self.create_job = async_to_raw_response_wrapper( + extract.create_job, + ) + self.create_schema = async_to_raw_response_wrapper( + extract.create_schema, + ) + self.update_job_results = async_to_raw_response_wrapper( + extract.update_job_results, + ) + self.update_schema = async_to_raw_response_wrapper( + extract.update_schema, + ) + + +class ExtractResourceWithStreamingResponse: + def __init__(self, extract: ExtractResource) -> None: + self._extract = extract + + self.delete_document = to_streamed_response_wrapper( + extract.delete_document, + ) + self.delete_schema = to_streamed_response_wrapper( + extract.delete_schema, + ) + self.list_documents = to_streamed_response_wrapper( + extract.list_documents, + ) + self.retrieve_document = to_streamed_response_wrapper( + extract.retrieve_document, + ) + self.list_jobs = to_streamed_response_wrapper( + extract.list_jobs, + ) + self.retrieve_job = to_streamed_response_wrapper( + extract.retrieve_job, + ) + self.retrieve_job_results = to_streamed_response_wrapper( + extract.retrieve_job_results, + ) + self.list_schemas = to_streamed_response_wrapper( + extract.list_schemas, + ) + self.retrieve_schema = to_streamed_response_wrapper( + extract.retrieve_schema, + ) + self.upload_document = to_streamed_response_wrapper( + extract.upload_document, + ) + self.create_job = to_streamed_response_wrapper( + extract.create_job, + ) + self.create_schema = to_streamed_response_wrapper( + extract.create_schema, + ) + self.update_job_results = to_streamed_response_wrapper( + extract.update_job_results, + ) + self.update_schema = to_streamed_response_wrapper( + extract.update_schema, + ) + + +class AsyncExtractResourceWithStreamingResponse: + def __init__(self, extract: AsyncExtractResource) -> None: + self._extract = extract + + self.delete_document = async_to_streamed_response_wrapper( + extract.delete_document, + ) + self.delete_schema = async_to_streamed_response_wrapper( + extract.delete_schema, + ) + self.list_documents = async_to_streamed_response_wrapper( + extract.list_documents, + ) + self.retrieve_document = async_to_streamed_response_wrapper( + extract.retrieve_document, + ) + self.list_jobs = async_to_streamed_response_wrapper( + extract.list_jobs, + ) + self.retrieve_job = async_to_streamed_response_wrapper( + extract.retrieve_job, + ) + self.retrieve_job_results = async_to_streamed_response_wrapper( + extract.retrieve_job_results, + ) + self.list_schemas = async_to_streamed_response_wrapper( + extract.list_schemas, + ) + self.retrieve_schema = async_to_streamed_response_wrapper( + extract.retrieve_schema, + ) + self.upload_document = async_to_streamed_response_wrapper( + extract.upload_document, + ) + self.create_job = async_to_streamed_response_wrapper( + extract.create_job, + ) + self.create_schema = async_to_streamed_response_wrapper( + extract.create_schema, + ) + self.update_job_results = async_to_streamed_response_wrapper( + extract.update_job_results, + ) + self.update_schema = async_to_streamed_response_wrapper( + extract.update_schema, + ) diff --git a/src/contextual/resources/workspaces.py b/src/contextual/resources/workspaces.py new file mode 100644 index 00000000..736f9215 --- /dev/null +++ b/src/contextual/resources/workspaces.py @@ -0,0 +1,252 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +from ..types import workspace_update_consent_params +from .._types import Body, Query, Headers, NotGiven, not_given +from .._utils import maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.workspace_update_consent_response import WorkspaceUpdateConsentResponse +from ..types.workspace_retrieve_consent_response import WorkspaceRetrieveConsentResponse + +__all__ = ["WorkspacesResource", "AsyncWorkspacesResource"] + + +class WorkspacesResource(SyncAPIResource): + @cached_property + def with_raw_response(self) -> WorkspacesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#accessing-raw-response-data-eg-headers + """ + return WorkspacesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> WorkspacesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#with_streaming_response + """ + return WorkspacesResourceWithStreamingResponse(self) + + def retrieve_consent( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspaceRetrieveConsentResponse: + """ + Retrieve the current consent status for the workspace. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/workspaces/consent", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspaceRetrieveConsentResponse, + ) + + def update_consent( + self, + *, + type: Literal["CONSENT_FULL", "CONSENT_SUPPORT", "REVOKE", "UNKNOWN"], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspaceUpdateConsentResponse: + """ + Update the consent status for the workspace. + + Args: + type: The new consent status + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._put( + "/workspaces/consent", + body=maybe_transform( + { + "type": type, + }, + workspace_update_consent_params.WorkspaceUpdateConsentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspaceUpdateConsentResponse, + ) + + +class AsyncWorkspacesResource(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncWorkspacesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#accessing-raw-response-data-eg-headers + """ + return AsyncWorkspacesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncWorkspacesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/ContextualAI/contextual-client-python#with_streaming_response + """ + return AsyncWorkspacesResourceWithStreamingResponse(self) + + async def retrieve_consent( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspaceRetrieveConsentResponse: + """ + Retrieve the current consent status for the workspace. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/workspaces/consent", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspaceRetrieveConsentResponse, + ) + + async def update_consent( + self, + *, + type: Literal["CONSENT_FULL", "CONSENT_SUPPORT", "REVOKE", "UNKNOWN"], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspaceUpdateConsentResponse: + """ + Update the consent status for the workspace. + + Args: + type: The new consent status + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._put( + "/workspaces/consent", + body=await async_maybe_transform( + { + "type": type, + }, + workspace_update_consent_params.WorkspaceUpdateConsentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspaceUpdateConsentResponse, + ) + + +class WorkspacesResourceWithRawResponse: + def __init__(self, workspaces: WorkspacesResource) -> None: + self._workspaces = workspaces + + self.retrieve_consent = to_raw_response_wrapper( + workspaces.retrieve_consent, + ) + self.update_consent = to_raw_response_wrapper( + workspaces.update_consent, + ) + + +class AsyncWorkspacesResourceWithRawResponse: + def __init__(self, workspaces: AsyncWorkspacesResource) -> None: + self._workspaces = workspaces + + self.retrieve_consent = async_to_raw_response_wrapper( + workspaces.retrieve_consent, + ) + self.update_consent = async_to_raw_response_wrapper( + workspaces.update_consent, + ) + + +class WorkspacesResourceWithStreamingResponse: + def __init__(self, workspaces: WorkspacesResource) -> None: + self._workspaces = workspaces + + self.retrieve_consent = to_streamed_response_wrapper( + workspaces.retrieve_consent, + ) + self.update_consent = to_streamed_response_wrapper( + workspaces.update_consent, + ) + + +class AsyncWorkspacesResourceWithStreamingResponse: + def __init__(self, workspaces: AsyncWorkspacesResource) -> None: + self._workspaces = workspaces + + self.retrieve_consent = async_to_streamed_response_wrapper( + workspaces.retrieve_consent, + ) + self.update_consent = async_to_streamed_response_wrapper( + workspaces.update_consent, + ) diff --git a/src/contextual/types/__init__.py b/src/contextual/types/__init__.py index e23e1661..2a5b0e9c 100644 --- a/src/contextual/types/__init__.py +++ b/src/contextual/types/__init__.py @@ -87,3 +87,50 @@ agent_configs.AgentConfigs.model_rebuild(_parent_namespace_depth=0) agent_metadata.AgentMetadata.model_rebuild(_parent_namespace_depth=0) filter_and_rerank_config.FilterAndRerankConfig.model_rebuild(_parent_namespace_depth=0) +from .extract_list_jobs_params import ExtractListJobsParams as ExtractListJobsParams +from .extract_create_job_params import ExtractCreateJobParams as ExtractCreateJobParams +from .extract_list_jobs_response import ExtractListJobsResponse as ExtractListJobsResponse +from .billing_list_top_ups_params import BillingListTopUpsParams as BillingListTopUpsParams +from .extract_create_job_response import ExtractCreateJobResponse as ExtractCreateJobResponse +from .extract_list_schemas_params import ExtractListSchemasParams as ExtractListSchemasParams +from .extract_create_schema_params import ExtractCreateSchemaParams as ExtractCreateSchemaParams +from .extract_update_schema_params import ExtractUpdateSchemaParams as ExtractUpdateSchemaParams +from .billing_list_top_ups_response import BillingListTopUpsResponse as BillingListTopUpsResponse +from .extract_list_documents_params import ExtractListDocumentsParams as ExtractListDocumentsParams +from .extract_list_schemas_response import ExtractListSchemasResponse as ExtractListSchemasResponse +from .extract_retrieve_job_response import ExtractRetrieveJobResponse as ExtractRetrieveJobResponse +from .extract_create_schema_response import ExtractCreateSchemaResponse as ExtractCreateSchemaResponse +from .extract_delete_schema_response import ExtractDeleteSchemaResponse as ExtractDeleteSchemaResponse +from .extract_update_schema_response import ExtractUpdateSchemaResponse as ExtractUpdateSchemaResponse +from .extract_upload_document_params import ExtractUploadDocumentParams as ExtractUploadDocumentParams +from .extract_list_documents_response import ExtractListDocumentsResponse as ExtractListDocumentsResponse +from .workspace_update_consent_params import WorkspaceUpdateConsentParams as WorkspaceUpdateConsentParams +from .extract_delete_document_response import ExtractDeleteDocumentResponse as ExtractDeleteDocumentResponse +from .extract_retrieve_schema_response import ExtractRetrieveSchemaResponse as ExtractRetrieveSchemaResponse +from .extract_upload_document_response import ExtractUploadDocumentResponse as ExtractUploadDocumentResponse +from .billing_retrieve_acl_usage_params import BillingRetrieveAclUsageParams as BillingRetrieveAclUsageParams +from .billing_retrieve_balance_response import BillingRetrieveBalanceResponse as BillingRetrieveBalanceResponse +from .extract_update_job_results_params import ExtractUpdateJobResultsParams as ExtractUpdateJobResultsParams +from .workspace_update_consent_response import WorkspaceUpdateConsentResponse as WorkspaceUpdateConsentResponse +from .billing_retrieve_metadata_response import BillingRetrieveMetadataResponse as BillingRetrieveMetadataResponse +from .extract_retrieve_document_response import ExtractRetrieveDocumentResponse as ExtractRetrieveDocumentResponse +from .billing_retrieve_acl_usage_response import BillingRetrieveAclUsageResponse as BillingRetrieveAclUsageResponse +from .workspace_retrieve_consent_response import WorkspaceRetrieveConsentResponse as WorkspaceRetrieveConsentResponse +from .billing_retrieve_monthly_usage_params import ( + BillingRetrieveMonthlyUsageParams as BillingRetrieveMonthlyUsageParams, +) +from .extract_retrieve_job_results_response import ( + ExtractRetrieveJobResultsResponse as ExtractRetrieveJobResultsResponse, +) +from .billing_retrieve_monthly_usage_response import ( + BillingRetrieveMonthlyUsageResponse as BillingRetrieveMonthlyUsageResponse, +) +from .billing_retrieve_billing_mode_history_params import ( + BillingRetrieveBillingModeHistoryParams as BillingRetrieveBillingModeHistoryParams, +) +from .billing_retrieve_earliest_usage_date_response import ( + BillingRetrieveEarliestUsageDateResponse as BillingRetrieveEarliestUsageDateResponse, +) +from .billing_retrieve_billing_mode_history_response import ( + BillingRetrieveBillingModeHistoryResponse as BillingRetrieveBillingModeHistoryResponse, +) diff --git a/src/contextual/types/billing_list_top_ups_params.py b/src/contextual/types/billing_list_top_ups_params.py new file mode 100644 index 00000000..82cc3906 --- /dev/null +++ b/src/contextual/types/billing_list_top_ups_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BillingListTopUpsParams"] + + +class BillingListTopUpsParams(TypedDict, total=False): + cursor: object + + limit: int diff --git a/src/contextual/types/billing_list_top_ups_response.py b/src/contextual/types/billing_list_top_ups_response.py new file mode 100644 index 00000000..1c2584f9 --- /dev/null +++ b/src/contextual/types/billing_list_top_ups_response.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import List, Optional +from datetime import datetime + +from .._models import BaseModel + +__all__ = ["BillingListTopUpsResponse", "TopUp"] + + +class TopUp(BaseModel): + """Individual top-up entry""" + + amount: float + """Amount of the top-up""" + + created_at: datetime + """Date when the top-up was created""" + + description: str + """Description of the top-up""" + + ending_balance: float + """Ending balance after the top-up""" + + starting_balance: float + """Starting balance before the top-up""" + + +class BillingListTopUpsResponse(BaseModel): + """Response to GET /billing/free-credit request""" + + cursor: Optional[str] = None + """Cursor for next page""" + + has_more: bool + """Whether there are more top-ups to fetch""" + + top_ups: List[TopUp] + """List of top-ups""" diff --git a/src/contextual/types/billing_retrieve_acl_usage_params.py b/src/contextual/types/billing_retrieve_acl_usage_params.py new file mode 100644 index 00000000..876ac24d --- /dev/null +++ b/src/contextual/types/billing_retrieve_acl_usage_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["BillingRetrieveAclUsageParams"] + + +class BillingRetrieveAclUsageParams(TypedDict, total=False): + month: Required[int] + + year: Required[int] + + resource_id: object diff --git a/src/contextual/types/billing_retrieve_acl_usage_response.py b/src/contextual/types/billing_retrieve_acl_usage_response.py new file mode 100644 index 00000000..a71e5f3e --- /dev/null +++ b/src/contextual/types/billing_retrieve_acl_usage_response.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel + +__all__ = ["BillingRetrieveAclUsageResponse", "Usage"] + + +class Usage(BaseModel): + """ + Single day's Agent Composer usage for a specific step. + + Represents aggregated usage data for a pipeline step on a specific date, summing across all models used by that step. + """ + + date: str + """Date in ISO format (YYYY-MM-DD)""" + + input_tokens: int + """Total input tokens for this step""" + + output_tokens: int + """Total output tokens for this step""" + + step_name: str + """Name of the pipeline step""" + + total_cost: float + """Total cost in USD for this step""" + + +class BillingRetrieveAclUsageResponse(BaseModel): + """ + Response containing daily usages of advance queries grouped by steps. + + This API returns step-level breakdown of Agent Composer usage for visualization purposes. The costs in this response are already included in the ACL_COST entry from the daily_usages table and should not be double-counted. + """ + + usages: List[Usage] + """List of Agent Composer step usages aggregated by step and date""" diff --git a/src/contextual/types/billing_retrieve_balance_response.py b/src/contextual/types/billing_retrieve_balance_response.py new file mode 100644 index 00000000..db6ffdaf --- /dev/null +++ b/src/contextual/types/billing_retrieve_balance_response.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + + +from .._models import BaseModel + +__all__ = ["BillingRetrieveBalanceResponse"] + + +class BillingRetrieveBalanceResponse(BaseModel): + """Response to GET /billing/balance request""" + + balance: float + """Balance of the user""" diff --git a/src/contextual/types/billing_retrieve_billing_mode_history_params.py b/src/contextual/types/billing_retrieve_billing_mode_history_params.py new file mode 100644 index 00000000..3461de19 --- /dev/null +++ b/src/contextual/types/billing_retrieve_billing_mode_history_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["BillingRetrieveBillingModeHistoryParams"] + + +class BillingRetrieveBillingModeHistoryParams(TypedDict, total=False): + month: Required[int] + + year: Required[int] diff --git a/src/contextual/types/billing_retrieve_billing_mode_history_response.py b/src/contextual/types/billing_retrieve_billing_mode_history_response.py new file mode 100644 index 00000000..a8f1d1fc --- /dev/null +++ b/src/contextual/types/billing_retrieve_billing_mode_history_response.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +import datetime +from typing import List +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BillingRetrieveBillingModeHistoryResponse", "BillingMode"] + + +class BillingMode(BaseModel): + """Individual billing mode entry""" + + billing_mode: Literal["ON_DEMAND_PREPAID", "ON_DEMAND_PAY_ARREARS", "PROVISION_THROUGHPUT", "LEGACY"] + """Billing mode""" + + date: datetime.date + """Date (yyyy-mm-dd) when the billing mode became effective""" + + +class BillingRetrieveBillingModeHistoryResponse(BaseModel): + """Response to GET /billing/billing_mode/history request""" + + billing_modes: List[BillingMode] + """List of billing mode entries for the specified month""" diff --git a/src/contextual/types/billing_retrieve_earliest_usage_date_response.py b/src/contextual/types/billing_retrieve_earliest_usage_date_response.py new file mode 100644 index 00000000..a1c0c2fc --- /dev/null +++ b/src/contextual/types/billing_retrieve_earliest_usage_date_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +import datetime +from typing import Optional + +from .._models import BaseModel + +__all__ = ["BillingRetrieveEarliestUsageDateResponse"] + + +class BillingRetrieveEarliestUsageDateResponse(BaseModel): + """Response to GET /billing/usage/earliest_date request""" + + date: Optional[datetime.date] = None + """Earliest usage date""" diff --git a/src/contextual/types/billing_retrieve_metadata_response.py b/src/contextual/types/billing_retrieve_metadata_response.py new file mode 100644 index 00000000..cbad8f10 --- /dev/null +++ b/src/contextual/types/billing_retrieve_metadata_response.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + + +from .._models import BaseModel + +__all__ = ["BillingRetrieveMetadataResponse"] + + +class BillingRetrieveMetadataResponse(BaseModel): + """Response to GET /billing/metadata request""" + + is_auto_top_up_enabled: bool + """Whether auto top-up is enabled""" + + is_low_balance: bool + """Whether the user is low on balance""" diff --git a/src/contextual/types/billing_retrieve_monthly_usage_params.py b/src/contextual/types/billing_retrieve_monthly_usage_params.py new file mode 100644 index 00000000..677e97e3 --- /dev/null +++ b/src/contextual/types/billing_retrieve_monthly_usage_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["BillingRetrieveMonthlyUsageParams"] + + +class BillingRetrieveMonthlyUsageParams(TypedDict, total=False): + month: Required[int] + + year: Required[int] + + resource_id: object diff --git a/src/contextual/types/billing_retrieve_monthly_usage_response.py b/src/contextual/types/billing_retrieve_monthly_usage_response.py new file mode 100644 index 00000000..1483b5c5 --- /dev/null +++ b/src/contextual/types/billing_retrieve_monthly_usage_response.py @@ -0,0 +1,68 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +import datetime +from typing import List +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BillingRetrieveMonthlyUsageResponse", "Usage"] + + +class Usage(BaseModel): + date: datetime.date + """Date of the usage""" + + price: float + """Price per unit""" + + quantity: int + """Usage quantity""" + + usage_type: Literal[ + "QUERY_REFORMULATION_INPUT_TOKEN", + "QUERY_REFORMULATION_OUTPUT_TOKEN", + "QUERY_EXPANSION_INPUT_TOKEN", + "QUERY_EXPANSION_OUTPUT_TOKEN", + "QUERY_FILTER_TOKEN", + "QUERY_RETRIEVAL_TOKEN", + "QUERY_RERANK_TOKEN", + "QUERY_GENERATION_INPUT_TOKEN", + "QUERY_GENERATION_OUTPUT_TOKEN", + "QUERY_CONTEXTUALIZATION_TOKEN", + "QUERY_GROUNDEDNESS_TOKEN", + "QUERY_PLANNING_INPUT_TOKEN", + "QUERY_PLANNING_OUTPUT_TOKEN", + "QUERY_TRANSLATION_INPUT_TOKEN", + "QUERY_TRANSLATION_OUTPUT_TOKEN", + "QUERY_REQUEST", + "TUNE_REQUEST", + "EVAL_REQUEST", + "INGEST_BASIC_PAGE", + "INGEST_STANDARD_PAGE", + "INGEST_V3_STANDARD_PAGE", + "INGEST_V3_ADVANCED_PAGE", + "INGEST_V3_PREMIUM_PAGE", + "PARSE_BASIC_PAGE", + "PARSE_STANDARD_PAGE", + "RERANK_TOKEN", + "RERANK_V2_MINI_TOKEN", + "RERANK_V2_TOKEN", + "GENERATE_INPUT_TOKEN", + "GENERATE_OUTPUT_TOKEN", + "LMUNIT_TOKEN", + "ACL_COST", + "STRUCTURED_EXTRACTION_COST", + "STRUCTURED_EXTRACTION_INPUT_TOKENS", + "STRUCTURED_EXTRACTION_OUTPUT_TOKENS", + "STRUCTURED_EXTRACTION_CACHED_TOKENS", + "STRUCTURED_EXTRACTION_REASONING_TOKENS", + ] + """Type of usage""" + + +class BillingRetrieveMonthlyUsageResponse(BaseModel): + """Response to GET /billing/usage/monthly request""" + + usages: List[Usage] + """List of daily usages""" diff --git a/src/contextual/types/extract_create_job_params.py b/src/contextual/types/extract_create_job_params.py new file mode 100644 index 00000000..d89d1674 --- /dev/null +++ b/src/contextual/types/extract_create_job_params.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["ExtractCreateJobParams"] + + +class ExtractCreateJobParams(TypedDict, total=False): + document_id: Required[str] + """ID of the document to extract from""" + + schema_id: Required[str] + """ID of the schema to use for extraction""" + + config: object + """Configuration options for the extraction process""" + + stream: bool + """ + Whether to stream the results as they become available. If true, the response will be a stream of JSON objects. + """ diff --git a/src/contextual/types/extract_create_job_response.py b/src/contextual/types/extract_create_job_response.py new file mode 100644 index 00000000..1e23ca58 --- /dev/null +++ b/src/contextual/types/extract_create_job_response.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ExtractCreateJobResponse"] + + +class ExtractCreateJobResponse(BaseModel): + """Response model for extraction job creation.""" + + created_at: str + """Timestamp when the job was created""" + + estimated_completion: str + """Estimated completion time""" + + job_id: str + """Unique ID of the extraction job""" + + status: Literal["pending", "processing", "retrying", "completed", "failed", "cancelled"] + """Current status of the job""" diff --git a/src/contextual/types/extract_create_schema_params.py b/src/contextual/types/extract_create_schema_params.py new file mode 100644 index 00000000..fdb75105 --- /dev/null +++ b/src/contextual/types/extract_create_schema_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, TypedDict + +__all__ = ["ExtractCreateSchemaParams"] + + +class ExtractCreateSchemaParams(TypedDict, total=False): + name: Required[str] + """Name of the schema""" + + schema_definition: Required[Dict[str, object]] + """ + JSON Schema definition. Must be a valid JSON Schema that defines the structure of data to extract from documents. See the comprehensive schema guide in the API documentation for detailed examples and supported features. + """ + + description: object + """Description of the schema""" + + metadata: object + """Additional metadata for the schema""" diff --git a/src/contextual/types/extract_create_schema_response.py b/src/contextual/types/extract_create_schema_response.py new file mode 100644 index 00000000..e3d71326 --- /dev/null +++ b/src/contextual/types/extract_create_schema_response.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .._models import BaseModel + +__all__ = ["ExtractCreateSchemaResponse"] + + +class ExtractCreateSchemaResponse(BaseModel): + """Response model for schema information.""" + + created_at: str + """Timestamp when the schema was created""" + + description: Optional[str] = None + """Description of the schema""" + + metadata: Dict[str, object] + """Schema metadata""" + + name: str + """Name of the schema""" + + schema_definition: Dict[str, object] + """JSON schema definition""" + + schema_id: str + """Unique ID of the schema""" + + updated_at: str + """Timestamp when the schema was last updated""" diff --git a/src/contextual/types/extract_delete_document_response.py b/src/contextual/types/extract_delete_document_response.py new file mode 100644 index 00000000..a4503c5c --- /dev/null +++ b/src/contextual/types/extract_delete_document_response.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import TypeAlias + +__all__ = ["ExtractDeleteDocumentResponse"] + +ExtractDeleteDocumentResponse: TypeAlias = Dict[str, str] diff --git a/src/contextual/types/extract_delete_schema_response.py b/src/contextual/types/extract_delete_schema_response.py new file mode 100644 index 00000000..cb55c48f --- /dev/null +++ b/src/contextual/types/extract_delete_schema_response.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import TypeAlias + +__all__ = ["ExtractDeleteSchemaResponse"] + +ExtractDeleteSchemaResponse: TypeAlias = Dict[str, str] diff --git a/src/contextual/types/extract_list_documents_params.py b/src/contextual/types/extract_list_documents_params.py new file mode 100644 index 00000000..394dc9ea --- /dev/null +++ b/src/contextual/types/extract_list_documents_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ExtractListDocumentsParams"] + + +class ExtractListDocumentsParams(TypedDict, total=False): + cursor: object + + limit: int + + search: object diff --git a/src/contextual/types/extract_list_documents_response.py b/src/contextual/types/extract_list_documents_response.py new file mode 100644 index 00000000..9437a62f --- /dev/null +++ b/src/contextual/types/extract_list_documents_response.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["ExtractListDocumentsResponse", "Document"] + + +class Document(BaseModel): + """Response model for document information.""" + + document_id: str + """Unique ID of the document""" + + file_name: str + """Original filename""" + + file_size: int + """File size in bytes""" + + page_count: int + """Number of pages in the document""" + + signed_url: Optional[str] = None + """Presigned download URL for the document (valid for 1 hour). Only available for GCS and S3 storage backends.""" + + status: str + """Document status""" + + uploaded_at: str + """Timestamp when the document was uploaded""" + + +class ExtractListDocumentsResponse(BaseModel): + """Response model for document listing.""" + + documents: List[Document] + """List of documents""" + + next_cursor: Optional[str] = None + """Next cursor to continue pagination. Omitted if there are no more documents to retrieve.""" + + prev_cursor: Optional[str] = None + """Previous cursor to go back in pagination. Omitted if this is the first page.""" + + total_count: int + """Total number of documents""" diff --git a/src/contextual/types/extract_list_jobs_params.py b/src/contextual/types/extract_list_jobs_params.py new file mode 100644 index 00000000..f0e2cdb5 --- /dev/null +++ b/src/contextual/types/extract_list_jobs_params.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ExtractListJobsParams"] + + +class ExtractListJobsParams(TypedDict, total=False): + cursor: object + + job_status: object + + limit: int + + search: object diff --git a/src/contextual/types/extract_list_jobs_response.py b/src/contextual/types/extract_list_jobs_response.py new file mode 100644 index 00000000..9fc2aa33 --- /dev/null +++ b/src/contextual/types/extract_list_jobs_response.py @@ -0,0 +1,108 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ExtractListJobsResponse", "JobProgress", "JobConfigExtractConfig", "Job"] + + +class JobProgress(BaseModel): + """Progress information for an extraction job.""" + + completion_percentage: int + """Overall progress percentage (0-100)""" + + current_step: str + """Current processing stage or step description""" + + fields_processed: Optional[int] = None + """Number of schema fields that have been processed""" + + total_fields: Optional[int] = None + """Total number of schema fields to process""" + + +class JobConfigExtractConfig(BaseModel): + """ + Configuration for structured extraction. Most settings have sensible defaults, but you can customize them for your specific use case. + """ + + additional_instructions: Optional[str] = None + """ + Additional instructions to the model. This is a string that will be appended to the prompt. It is useful for providing additional context or instructions to the model. + """ + + enable_agentic_array_extraction: Optional[bool] = None + """ + If True, will use agentic array extraction to extract the array of objects when possible. Requires isolate_arrays=True in splitter_config. One can also enable agentic array extraction for specific arrays by setting agenticArrayExtractionMaxItemsPerTurn > 0 for the array in the JSON schema. + """ + + enable_thinking: Optional[bool] = None + """Enable reasoning which can improve accuracy but increases processing time and cost.""" + + model: Optional[Literal["gemini-2.5-flash", "gemini-2.5-pro", "gemini-3-pro-preview", "gemini-3-flash-preview"]] = ( + None + ) + """ + Base model for extraction. 'gemini-2.5-flash' is faster and cheaper, while 'gemini-2.5-pro' is more accurate and expensive. + """ + + per_key_attribution: Optional[bool] = None + """ + Set to include attributions for each extracted field including reasoning, confidence scores, and page numbers. This option increases processing time and cost. + """ + + temperature: Optional[float] = None + """ + Sampling temperature (0.0-2.0). Lower values make output more deterministic and consistent, higher values vary more. Leave as None for model defaults. + """ + + +class Job(BaseModel): + """ + Response model for job status. + + Returns basic job status and progress. + """ + + config: Optional[JobConfigExtractConfig] = None + """Configuration used for the extraction job (model, temperature, etc.)""" + + created_at: str + """Timestamp when the job was created""" + + current_activity: str + """Current activity being performed""" + + document_id: str + """ID of the document used for the extraction""" + + job_id: str + """Unique ID of the extraction job""" + + progress: JobProgress + """Progress information for an extraction job.""" + + schema_id: str + """ID of the schema used for the extraction""" + + status: Literal["pending", "processing", "retrying", "completed", "failed", "cancelled"] + """Current status of the job""" + + +class ExtractListJobsResponse(BaseModel): + """Response model for job listing.""" + + jobs: List[Job] + """List of jobs""" + + next_cursor: Optional[str] = None + """Next cursor to continue pagination. Omitted if there are no more jobs to retrieve.""" + + prev_cursor: Optional[str] = None + """Previous cursor to go back in pagination. Omitted if this is the first page.""" + + total_count: int + """Total number of jobs""" diff --git a/src/contextual/types/extract_list_schemas_params.py b/src/contextual/types/extract_list_schemas_params.py new file mode 100644 index 00000000..a34f0219 --- /dev/null +++ b/src/contextual/types/extract_list_schemas_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ExtractListSchemasParams"] + + +class ExtractListSchemasParams(TypedDict, total=False): + cursor: object + + limit: int + + search: object diff --git a/src/contextual/types/extract_list_schemas_response.py b/src/contextual/types/extract_list_schemas_response.py new file mode 100644 index 00000000..1dcc12e4 --- /dev/null +++ b/src/contextual/types/extract_list_schemas_response.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional + +from .._models import BaseModel + +__all__ = ["ExtractListSchemasResponse", "Schema"] + + +class Schema(BaseModel): + """Response model for schema information.""" + + created_at: str + """Timestamp when the schema was created""" + + description: Optional[str] = None + """Description of the schema""" + + metadata: Dict[str, object] + """Schema metadata""" + + name: str + """Name of the schema""" + + schema_definition: Dict[str, object] + """JSON schema definition""" + + schema_id: str + """Unique ID of the schema""" + + updated_at: str + """Timestamp when the schema was last updated""" + + +class ExtractListSchemasResponse(BaseModel): + """Response model for schema listing.""" + + next_cursor: Optional[str] = None + """Next cursor to continue pagination. Omitted if there are no more schemas to retrieve.""" + + prev_cursor: Optional[str] = None + """Previous cursor to go back in pagination. Omitted if this is the first page.""" + + schemas: List[Schema] + """List of schemas""" + + total_count: int + """Total number of schemas""" diff --git a/src/contextual/types/extract_retrieve_document_response.py b/src/contextual/types/extract_retrieve_document_response.py new file mode 100644 index 00000000..642b6590 --- /dev/null +++ b/src/contextual/types/extract_retrieve_document_response.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["ExtractRetrieveDocumentResponse"] + + +class ExtractRetrieveDocumentResponse(BaseModel): + """Response model for document information.""" + + document_id: str + """Unique ID of the document""" + + file_name: str + """Original filename""" + + file_size: int + """File size in bytes""" + + page_count: int + """Number of pages in the document""" + + signed_url: Optional[str] = None + """Presigned download URL for the document (valid for 1 hour). Only available for GCS and S3 storage backends.""" + + status: str + """Document status""" + + uploaded_at: str + """Timestamp when the document was uploaded""" diff --git a/src/contextual/types/extract_retrieve_job_response.py b/src/contextual/types/extract_retrieve_job_response.py new file mode 100644 index 00000000..ceb938bc --- /dev/null +++ b/src/contextual/types/extract_retrieve_job_response.py @@ -0,0 +1,92 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ExtractRetrieveJobResponse", "Progress", "ConfigExtractConfig"] + + +class Progress(BaseModel): + """Progress information for an extraction job.""" + + completion_percentage: int + """Overall progress percentage (0-100)""" + + current_step: str + """Current processing stage or step description""" + + fields_processed: Optional[int] = None + """Number of schema fields that have been processed""" + + total_fields: Optional[int] = None + """Total number of schema fields to process""" + + +class ConfigExtractConfig(BaseModel): + """ + Configuration for structured extraction. Most settings have sensible defaults, but you can customize them for your specific use case. + """ + + additional_instructions: Optional[str] = None + """ + Additional instructions to the model. This is a string that will be appended to the prompt. It is useful for providing additional context or instructions to the model. + """ + + enable_agentic_array_extraction: Optional[bool] = None + """ + If True, will use agentic array extraction to extract the array of objects when possible. Requires isolate_arrays=True in splitter_config. One can also enable agentic array extraction for specific arrays by setting agenticArrayExtractionMaxItemsPerTurn > 0 for the array in the JSON schema. + """ + + enable_thinking: Optional[bool] = None + """Enable reasoning which can improve accuracy but increases processing time and cost.""" + + model: Optional[Literal["gemini-2.5-flash", "gemini-2.5-pro", "gemini-3-pro-preview", "gemini-3-flash-preview"]] = ( + None + ) + """ + Base model for extraction. 'gemini-2.5-flash' is faster and cheaper, while 'gemini-2.5-pro' is more accurate and expensive. + """ + + per_key_attribution: Optional[bool] = None + """ + Set to include attributions for each extracted field including reasoning, confidence scores, and page numbers. This option increases processing time and cost. + """ + + temperature: Optional[float] = None + """ + Sampling temperature (0.0-2.0). Lower values make output more deterministic and consistent, higher values vary more. Leave as None for model defaults. + """ + + +class ExtractRetrieveJobResponse(BaseModel): + """ + Response model for job status. + + Returns basic job status and progress. + """ + + config: Optional[ConfigExtractConfig] = None + """Configuration used for the extraction job (model, temperature, etc.)""" + + created_at: str + """Timestamp when the job was created""" + + current_activity: str + """Current activity being performed""" + + document_id: str + """ID of the document used for the extraction""" + + job_id: str + """Unique ID of the extraction job""" + + progress: Progress + """Progress information for an extraction job.""" + + schema_id: str + """ID of the schema used for the extraction""" + + status: Literal["pending", "processing", "retrying", "completed", "failed", "cancelled"] + """Current status of the job""" diff --git a/src/contextual/types/extract_retrieve_job_results_response.py b/src/contextual/types/extract_retrieve_job_results_response.py new file mode 100644 index 00000000..b5823d5c --- /dev/null +++ b/src/contextual/types/extract_retrieve_job_results_response.py @@ -0,0 +1,71 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ExtractRetrieveJobResultsResponse", "ConfigExtractConfig"] + + +class ConfigExtractConfig(BaseModel): + """ + Configuration for structured extraction. Most settings have sensible defaults, but you can customize them for your specific use case. + """ + + additional_instructions: Optional[str] = None + """ + Additional instructions to the model. This is a string that will be appended to the prompt. It is useful for providing additional context or instructions to the model. + """ + + enable_agentic_array_extraction: Optional[bool] = None + """ + If True, will use agentic array extraction to extract the array of objects when possible. Requires isolate_arrays=True in splitter_config. One can also enable agentic array extraction for specific arrays by setting agenticArrayExtractionMaxItemsPerTurn > 0 for the array in the JSON schema. + """ + + enable_thinking: Optional[bool] = None + """Enable reasoning which can improve accuracy but increases processing time and cost.""" + + model: Optional[Literal["gemini-2.5-flash", "gemini-2.5-pro", "gemini-3-pro-preview", "gemini-3-flash-preview"]] = ( + None + ) + """ + Base model for extraction. 'gemini-2.5-flash' is faster and cheaper, while 'gemini-2.5-pro' is more accurate and expensive. + """ + + per_key_attribution: Optional[bool] = None + """ + Set to include attributions for each extracted field including reasoning, confidence scores, and page numbers. This option increases processing time and cost. + """ + + temperature: Optional[float] = None + """ + Sampling temperature (0.0-2.0). Lower values make output more deterministic and consistent, higher values vary more. Leave as None for model defaults. + """ + + +class ExtractRetrieveJobResultsResponse(BaseModel): + """ + Response model for job results. + + The results field contains extracted data conforming to the provided JSON Schema. When per_key_attribution is enabled in ExtractConfig, primitive fields in results will be wrapped with AttributionInfo structures containing the extracted_value along with reasoning, confidence, and page location metadata. + """ + + config: Optional[ConfigExtractConfig] = None + """Configuration used for the extraction job (model, temperature, etc.)""" + + job_id: str + """Unique ID of the extraction job""" + + metadata: Dict[str, object] + """ + Metadata about the extraction process. May include has_attributions boolean flag indicating if attribution data is present in results. + """ + + results: Dict[str, object] + """ + Extracted results conforming to the provided JSON Schema. When per_key_attribution is enabled, primitive values are wrapped with AttributionInfo containing extracted_value, reasoning, confidence, and location fields. + """ + + status: Literal["pending", "processing", "retrying", "completed", "failed", "cancelled"] + """Current status of the job""" diff --git a/src/contextual/types/extract_retrieve_schema_response.py b/src/contextual/types/extract_retrieve_schema_response.py new file mode 100644 index 00000000..6f30fda8 --- /dev/null +++ b/src/contextual/types/extract_retrieve_schema_response.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .._models import BaseModel + +__all__ = ["ExtractRetrieveSchemaResponse"] + + +class ExtractRetrieveSchemaResponse(BaseModel): + """Response model for schema information.""" + + created_at: str + """Timestamp when the schema was created""" + + description: Optional[str] = None + """Description of the schema""" + + metadata: Dict[str, object] + """Schema metadata""" + + name: str + """Name of the schema""" + + schema_definition: Dict[str, object] + """JSON schema definition""" + + schema_id: str + """Unique ID of the schema""" + + updated_at: str + """Timestamp when the schema was last updated""" diff --git a/src/contextual/types/extract_update_job_results_params.py b/src/contextual/types/extract_update_job_results_params.py new file mode 100644 index 00000000..374487ef --- /dev/null +++ b/src/contextual/types/extract_update_job_results_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, TypedDict + +__all__ = ["ExtractUpdateJobResultsParams"] + + +class ExtractUpdateJobResultsParams(TypedDict, total=False): + results: Required[Dict[str, object]] + """Extracted results conforming to the provided JSON Schema.""" diff --git a/src/contextual/types/extract_update_schema_params.py b/src/contextual/types/extract_update_schema_params.py new file mode 100644 index 00000000..a9482655 --- /dev/null +++ b/src/contextual/types/extract_update_schema_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ExtractUpdateSchemaParams"] + + +class ExtractUpdateSchemaParams(TypedDict, total=False): + description: object + """Description of the schema""" + + metadata: object + """Additional metadata""" + + name: object + """Name of the schema""" + + schema_definition: object + """JSON schema definition""" diff --git a/src/contextual/types/extract_update_schema_response.py b/src/contextual/types/extract_update_schema_response.py new file mode 100644 index 00000000..2c97e0e1 --- /dev/null +++ b/src/contextual/types/extract_update_schema_response.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .._models import BaseModel + +__all__ = ["ExtractUpdateSchemaResponse"] + + +class ExtractUpdateSchemaResponse(BaseModel): + """Response model for schema information.""" + + created_at: str + """Timestamp when the schema was created""" + + description: Optional[str] = None + """Description of the schema""" + + metadata: Dict[str, object] + """Schema metadata""" + + name: str + """Name of the schema""" + + schema_definition: Dict[str, object] + """JSON schema definition""" + + schema_id: str + """Unique ID of the schema""" + + updated_at: str + """Timestamp when the schema was last updated""" diff --git a/src/contextual/types/extract_upload_document_params.py b/src/contextual/types/extract_upload_document_params.py new file mode 100644 index 00000000..33fa036d --- /dev/null +++ b/src/contextual/types/extract_upload_document_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .._types import FileTypes + +__all__ = ["ExtractUploadDocumentParams"] + + +class ExtractUploadDocumentParams(TypedDict, total=False): + file: Required[FileTypes] diff --git a/src/contextual/types/extract_upload_document_response.py b/src/contextual/types/extract_upload_document_response.py new file mode 100644 index 00000000..012dc1f1 --- /dev/null +++ b/src/contextual/types/extract_upload_document_response.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + + +from .._models import BaseModel + +__all__ = ["ExtractUploadDocumentResponse"] + + +class ExtractUploadDocumentResponse(BaseModel): + """Response model for document upload.""" + + document_id: str + """Unique ID of the uploaded document""" + + file_name: str + """Original filename of the uploaded document""" + + file_size: int + """File size in bytes""" + + page_count: int + """Number of pages in the document""" + + status: str + """Upload status""" + + uploaded_at: str + """Timestamp when the document was uploaded""" diff --git a/src/contextual/types/workspace_retrieve_consent_response.py b/src/contextual/types/workspace_retrieve_consent_response.py new file mode 100644 index 00000000..0c96c655 --- /dev/null +++ b/src/contextual/types/workspace_retrieve_consent_response.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["WorkspaceRetrieveConsentResponse"] + + +class WorkspaceRetrieveConsentResponse(BaseModel): + """Response for the endpoint that retrieves the consent status for the workspace.""" + + created_at: Optional[str] = None + """The timestamp when the consent was granted or revoked""" + + email: Optional[str] = None + """The email of the user who granted or revoked the consent""" + + status: str + """The current consent status in `ConsentType`.""" diff --git a/src/contextual/types/workspace_update_consent_params.py b/src/contextual/types/workspace_update_consent_params.py new file mode 100644 index 00000000..2b4c9937 --- /dev/null +++ b/src/contextual/types/workspace_update_consent_params.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["WorkspaceUpdateConsentParams"] + + +class WorkspaceUpdateConsentParams(TypedDict, total=False): + type: Required[Literal["CONSENT_FULL", "CONSENT_SUPPORT", "REVOKE", "UNKNOWN"]] + """The new consent status""" diff --git a/src/contextual/types/workspace_update_consent_response.py b/src/contextual/types/workspace_update_consent_response.py new file mode 100644 index 00000000..fa7860f2 --- /dev/null +++ b/src/contextual/types/workspace_update_consent_response.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + + +from .._models import BaseModel + +__all__ = ["WorkspaceUpdateConsentResponse"] + + +class WorkspaceUpdateConsentResponse(BaseModel): + pass diff --git a/tests/api_resources/test_billing.py b/tests/api_resources/test_billing.py new file mode 100644 index 00000000..ff6fc1e5 --- /dev/null +++ b/tests/api_resources/test_billing.py @@ -0,0 +1,488 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from contextual import ContextualAI, AsyncContextualAI +from tests.utils import assert_matches_type +from contextual.types import ( + BillingListTopUpsResponse, + BillingRetrieveBalanceResponse, + BillingRetrieveAclUsageResponse, + BillingRetrieveMetadataResponse, + BillingRetrieveMonthlyUsageResponse, + BillingRetrieveEarliestUsageDateResponse, + BillingRetrieveBillingModeHistoryResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestBilling: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_retrieve_balance(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_balance() + assert_matches_type(BillingRetrieveBalanceResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_retrieve_balance(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.retrieve_balance() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingRetrieveBalanceResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_balance(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.retrieve_balance() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingRetrieveBalanceResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_list_top_ups(self, client: ContextualAI) -> None: + billing = client.billing.list_top_ups() + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + @parametrize + def test_method_list_top_ups_with_all_params(self, client: ContextualAI) -> None: + billing = client.billing.list_top_ups( + limit=1, + cursor="cursor", + ) + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_list_top_ups(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.list_top_ups() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_list_top_ups(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.list_top_ups() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_billing_mode_history(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_billing_mode_history( + year=2025, + month=1, + ) + assert_matches_type(BillingRetrieveBillingModeHistoryResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_retrieve_billing_mode_history(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.retrieve_billing_mode_history( + year=2025, + month=1, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingRetrieveBillingModeHistoryResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_billing_mode_history(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.retrieve_billing_mode_history( + year=2025, + month=1, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingRetrieveBillingModeHistoryResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_metadata(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_metadata() + assert_matches_type(BillingRetrieveMetadataResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_retrieve_metadata(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.retrieve_metadata() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingRetrieveMetadataResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_metadata(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.retrieve_metadata() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingRetrieveMetadataResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_acl_usage(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_acl_usage( + year=2025, + month=1, + ) + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + @parametrize + def test_method_retrieve_acl_usage_with_all_params(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_acl_usage( + year=2025, + month=1, + resource_id="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", + ) + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_retrieve_acl_usage(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.retrieve_acl_usage( + year=2025, + month=1, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_acl_usage(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.retrieve_acl_usage( + year=2025, + month=1, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_earliest_usage_date(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_earliest_usage_date() + assert_matches_type(BillingRetrieveEarliestUsageDateResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_retrieve_earliest_usage_date(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.retrieve_earliest_usage_date() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingRetrieveEarliestUsageDateResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_earliest_usage_date(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.retrieve_earliest_usage_date() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingRetrieveEarliestUsageDateResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_monthly_usage(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_monthly_usage( + year=2025, + month=1, + ) + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + @parametrize + def test_method_retrieve_monthly_usage_with_all_params(self, client: ContextualAI) -> None: + billing = client.billing.retrieve_monthly_usage( + year=2025, + month=1, + resource_id="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", + ) + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + @parametrize + def test_raw_response_retrieve_monthly_usage(self, client: ContextualAI) -> None: + response = client.billing.with_raw_response.retrieve_monthly_usage( + year=2025, + month=1, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = response.parse() + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_monthly_usage(self, client: ContextualAI) -> None: + with client.billing.with_streaming_response.retrieve_monthly_usage( + year=2025, + month=1, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = response.parse() + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncBilling: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @parametrize + async def test_method_retrieve_balance(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_balance() + assert_matches_type(BillingRetrieveBalanceResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_balance(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.retrieve_balance() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingRetrieveBalanceResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_balance(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.retrieve_balance() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingRetrieveBalanceResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_list_top_ups(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.list_top_ups() + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + @parametrize + async def test_method_list_top_ups_with_all_params(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.list_top_ups( + limit=1, + cursor="cursor", + ) + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_list_top_ups(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.list_top_ups() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_list_top_ups(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.list_top_ups() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingListTopUpsResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_billing_mode_history(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_billing_mode_history( + year=2025, + month=1, + ) + assert_matches_type(BillingRetrieveBillingModeHistoryResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_billing_mode_history(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.retrieve_billing_mode_history( + year=2025, + month=1, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingRetrieveBillingModeHistoryResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_billing_mode_history(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.retrieve_billing_mode_history( + year=2025, + month=1, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingRetrieveBillingModeHistoryResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_metadata(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_metadata() + assert_matches_type(BillingRetrieveMetadataResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_metadata(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.retrieve_metadata() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingRetrieveMetadataResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_metadata(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.retrieve_metadata() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingRetrieveMetadataResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_acl_usage(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_acl_usage( + year=2025, + month=1, + ) + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + @parametrize + async def test_method_retrieve_acl_usage_with_all_params(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_acl_usage( + year=2025, + month=1, + resource_id="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", + ) + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_acl_usage(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.retrieve_acl_usage( + year=2025, + month=1, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_acl_usage(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.retrieve_acl_usage( + year=2025, + month=1, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingRetrieveAclUsageResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_earliest_usage_date(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_earliest_usage_date() + assert_matches_type(BillingRetrieveEarliestUsageDateResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_earliest_usage_date(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.retrieve_earliest_usage_date() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingRetrieveEarliestUsageDateResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_earliest_usage_date(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.retrieve_earliest_usage_date() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingRetrieveEarliestUsageDateResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_monthly_usage(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_monthly_usage( + year=2025, + month=1, + ) + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + @parametrize + async def test_method_retrieve_monthly_usage_with_all_params(self, async_client: AsyncContextualAI) -> None: + billing = await async_client.billing.retrieve_monthly_usage( + year=2025, + month=1, + resource_id="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", + ) + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_monthly_usage(self, async_client: AsyncContextualAI) -> None: + response = await async_client.billing.with_raw_response.retrieve_monthly_usage( + year=2025, + month=1, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + billing = await response.parse() + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_monthly_usage(self, async_client: AsyncContextualAI) -> None: + async with async_client.billing.with_streaming_response.retrieve_monthly_usage( + year=2025, + month=1, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + billing = await response.parse() + assert_matches_type(BillingRetrieveMonthlyUsageResponse, billing, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_extract.py b/tests/api_resources/test_extract.py new file mode 100644 index 00000000..ecffec4a --- /dev/null +++ b/tests/api_resources/test_extract.py @@ -0,0 +1,1120 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from contextual import ContextualAI, AsyncContextualAI +from tests.utils import assert_matches_type +from contextual.types import ( + ExtractListJobsResponse, + ExtractCreateJobResponse, + ExtractListSchemasResponse, + ExtractRetrieveJobResponse, + ExtractCreateSchemaResponse, + ExtractDeleteSchemaResponse, + ExtractUpdateSchemaResponse, + ExtractListDocumentsResponse, + ExtractDeleteDocumentResponse, + ExtractRetrieveSchemaResponse, + ExtractUploadDocumentResponse, + ExtractRetrieveDocumentResponse, + ExtractRetrieveJobResultsResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestExtract: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_delete_document(self, client: ContextualAI) -> None: + extract = client.extract.delete_document( + "document_id", + ) + assert_matches_type(ExtractDeleteDocumentResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_delete_document(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.delete_document( + "document_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractDeleteDocumentResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_delete_document(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.delete_document( + "document_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractDeleteDocumentResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete_document(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `document_id` but received ''"): + client.extract.with_raw_response.delete_document( + "", + ) + + @parametrize + def test_method_delete_schema(self, client: ContextualAI) -> None: + extract = client.extract.delete_schema( + "schema_id", + ) + assert_matches_type(ExtractDeleteSchemaResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_delete_schema(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.delete_schema( + "schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractDeleteSchemaResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_delete_schema(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.delete_schema( + "schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractDeleteSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete_schema(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schema_id` but received ''"): + client.extract.with_raw_response.delete_schema( + "", + ) + + @parametrize + def test_method_list_documents(self, client: ContextualAI) -> None: + extract = client.extract.list_documents() + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + @parametrize + def test_method_list_documents_with_all_params(self, client: ContextualAI) -> None: + extract = client.extract.list_documents( + limit=1, + cursor="cursor", + search="search", + ) + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_list_documents(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.list_documents() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_list_documents(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.list_documents() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_document(self, client: ContextualAI) -> None: + extract = client.extract.retrieve_document( + "document_id", + ) + assert_matches_type(ExtractRetrieveDocumentResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_retrieve_document(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.retrieve_document( + "document_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractRetrieveDocumentResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_document(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.retrieve_document( + "document_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractRetrieveDocumentResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve_document(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `document_id` but received ''"): + client.extract.with_raw_response.retrieve_document( + "", + ) + + @parametrize + def test_method_list_jobs(self, client: ContextualAI) -> None: + extract = client.extract.list_jobs() + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + @parametrize + def test_method_list_jobs_with_all_params(self, client: ContextualAI) -> None: + extract = client.extract.list_jobs( + limit=1, + cursor="cursor", + job_status="job_status", + search="search", + ) + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_list_jobs(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.list_jobs() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_list_jobs(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.list_jobs() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_job(self, client: ContextualAI) -> None: + extract = client.extract.retrieve_job( + "job_id", + ) + assert_matches_type(ExtractRetrieveJobResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_retrieve_job(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.retrieve_job( + "job_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractRetrieveJobResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_job(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.retrieve_job( + "job_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractRetrieveJobResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve_job(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `job_id` but received ''"): + client.extract.with_raw_response.retrieve_job( + "", + ) + + @parametrize + def test_method_retrieve_job_results(self, client: ContextualAI) -> None: + extract = client.extract.retrieve_job_results( + "job_id", + ) + assert_matches_type(ExtractRetrieveJobResultsResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_retrieve_job_results(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.retrieve_job_results( + "job_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractRetrieveJobResultsResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_job_results(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.retrieve_job_results( + "job_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractRetrieveJobResultsResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve_job_results(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `job_id` but received ''"): + client.extract.with_raw_response.retrieve_job_results( + "", + ) + + @parametrize + def test_method_list_schemas(self, client: ContextualAI) -> None: + extract = client.extract.list_schemas() + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + @parametrize + def test_method_list_schemas_with_all_params(self, client: ContextualAI) -> None: + extract = client.extract.list_schemas( + limit=1, + cursor="cursor", + search="search", + ) + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_list_schemas(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.list_schemas() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_list_schemas(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.list_schemas() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve_schema(self, client: ContextualAI) -> None: + extract = client.extract.retrieve_schema( + "schema_id", + ) + assert_matches_type(ExtractRetrieveSchemaResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_retrieve_schema(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.retrieve_schema( + "schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractRetrieveSchemaResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_schema(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.retrieve_schema( + "schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractRetrieveSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve_schema(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schema_id` but received ''"): + client.extract.with_raw_response.retrieve_schema( + "", + ) + + @parametrize + def test_method_upload_document(self, client: ContextualAI) -> None: + extract = client.extract.upload_document( + file=b"raw file contents", + ) + assert_matches_type(ExtractUploadDocumentResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_upload_document(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.upload_document( + file=b"raw file contents", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractUploadDocumentResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_upload_document(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.upload_document( + file=b"raw file contents", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractUploadDocumentResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_create_job(self, client: ContextualAI) -> None: + extract = client.extract.create_job( + document_id="document_id", + schema_id="schema_id", + ) + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + @parametrize + def test_method_create_job_with_all_params(self, client: ContextualAI) -> None: + extract = client.extract.create_job( + document_id="document_id", + schema_id="schema_id", + config={}, + stream=True, + ) + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_create_job(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.create_job( + document_id="document_id", + schema_id="schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_create_job(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.create_job( + document_id="document_id", + schema_id="schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_create_schema(self, client: ContextualAI) -> None: + extract = client.extract.create_schema( + name="name", + schema_definition={}, + ) + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + @parametrize + def test_method_create_schema_with_all_params(self, client: ContextualAI) -> None: + extract = client.extract.create_schema( + name="name", + description="description", + schema_definition={}, + metadata={}, + ) + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_create_schema(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.create_schema( + name="name", + schema_definition={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_create_schema(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.create_schema( + name="name", + schema_definition={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_update_job_results(self, client: ContextualAI) -> None: + extract = client.extract.update_job_results( + "job_id", + results={}, + ) + assert_matches_type(object, extract, path=["response"]) + + @parametrize + def test_raw_response_update_job_results(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.update_job_results( + "job_id", + results={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(object, extract, path=["response"]) + + @parametrize + def test_streaming_response_update_job_results(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.update_job_results( + "job_id", + results={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(object, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_update_job_results(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `job_id` but received ''"): + client.extract.with_raw_response.update_job_results( + "", + results={}, + ) + + @parametrize + def test_method_update_schema(self, client: ContextualAI) -> None: + extract = client.extract.update_schema( + "schema_id", + ) + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + @parametrize + def test_method_update_schema_with_all_params(self, client: ContextualAI) -> None: + extract = client.extract.update_schema( + "schema_id", + name="name", + description="description", + schema_definition={}, + metadata={}, + ) + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + @parametrize + def test_raw_response_update_schema(self, client: ContextualAI) -> None: + response = client.extract.with_raw_response.update_schema( + "schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = response.parse() + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + @parametrize + def test_streaming_response_update_schema(self, client: ContextualAI) -> None: + with client.extract.with_streaming_response.update_schema( + "schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = response.parse() + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_update_schema(self, client: ContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schema_id` but received ''"): + client.extract.with_raw_response.update_schema( + "", + ) + + +class TestAsyncExtract: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @parametrize + async def test_method_delete_document(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.delete_document( + "document_id", + ) + assert_matches_type(ExtractDeleteDocumentResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_delete_document(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.delete_document( + "document_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractDeleteDocumentResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_delete_document(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.delete_document( + "document_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractDeleteDocumentResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete_document(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `document_id` but received ''"): + await async_client.extract.with_raw_response.delete_document( + "", + ) + + @parametrize + async def test_method_delete_schema(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.delete_schema( + "schema_id", + ) + assert_matches_type(ExtractDeleteSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_delete_schema(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.delete_schema( + "schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractDeleteSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_delete_schema(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.delete_schema( + "schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractDeleteSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete_schema(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schema_id` but received ''"): + await async_client.extract.with_raw_response.delete_schema( + "", + ) + + @parametrize + async def test_method_list_documents(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.list_documents() + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + @parametrize + async def test_method_list_documents_with_all_params(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.list_documents( + limit=1, + cursor="cursor", + search="search", + ) + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_list_documents(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.list_documents() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_list_documents(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.list_documents() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractListDocumentsResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_document(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.retrieve_document( + "document_id", + ) + assert_matches_type(ExtractRetrieveDocumentResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_document(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.retrieve_document( + "document_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractRetrieveDocumentResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_document(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.retrieve_document( + "document_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractRetrieveDocumentResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve_document(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `document_id` but received ''"): + await async_client.extract.with_raw_response.retrieve_document( + "", + ) + + @parametrize + async def test_method_list_jobs(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.list_jobs() + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + @parametrize + async def test_method_list_jobs_with_all_params(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.list_jobs( + limit=1, + cursor="cursor", + job_status="job_status", + search="search", + ) + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_list_jobs(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.list_jobs() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_list_jobs(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.list_jobs() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractListJobsResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_job(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.retrieve_job( + "job_id", + ) + assert_matches_type(ExtractRetrieveJobResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_job(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.retrieve_job( + "job_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractRetrieveJobResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_job(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.retrieve_job( + "job_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractRetrieveJobResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve_job(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `job_id` but received ''"): + await async_client.extract.with_raw_response.retrieve_job( + "", + ) + + @parametrize + async def test_method_retrieve_job_results(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.retrieve_job_results( + "job_id", + ) + assert_matches_type(ExtractRetrieveJobResultsResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_job_results(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.retrieve_job_results( + "job_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractRetrieveJobResultsResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_job_results(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.retrieve_job_results( + "job_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractRetrieveJobResultsResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve_job_results(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `job_id` but received ''"): + await async_client.extract.with_raw_response.retrieve_job_results( + "", + ) + + @parametrize + async def test_method_list_schemas(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.list_schemas() + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + @parametrize + async def test_method_list_schemas_with_all_params(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.list_schemas( + limit=1, + cursor="cursor", + search="search", + ) + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_list_schemas(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.list_schemas() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_list_schemas(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.list_schemas() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractListSchemasResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve_schema(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.retrieve_schema( + "schema_id", + ) + assert_matches_type(ExtractRetrieveSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_schema(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.retrieve_schema( + "schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractRetrieveSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_schema(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.retrieve_schema( + "schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractRetrieveSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve_schema(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schema_id` but received ''"): + await async_client.extract.with_raw_response.retrieve_schema( + "", + ) + + @parametrize + async def test_method_upload_document(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.upload_document( + file=b"raw file contents", + ) + assert_matches_type(ExtractUploadDocumentResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_upload_document(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.upload_document( + file=b"raw file contents", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractUploadDocumentResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_upload_document(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.upload_document( + file=b"raw file contents", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractUploadDocumentResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_create_job(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.create_job( + document_id="document_id", + schema_id="schema_id", + ) + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + @parametrize + async def test_method_create_job_with_all_params(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.create_job( + document_id="document_id", + schema_id="schema_id", + config={}, + stream=True, + ) + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_create_job(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.create_job( + document_id="document_id", + schema_id="schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_create_job(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.create_job( + document_id="document_id", + schema_id="schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractCreateJobResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_create_schema(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.create_schema( + name="name", + schema_definition={}, + ) + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_method_create_schema_with_all_params(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.create_schema( + name="name", + description="description", + schema_definition={}, + metadata={}, + ) + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_create_schema(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.create_schema( + name="name", + schema_definition={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_create_schema(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.create_schema( + name="name", + schema_definition={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractCreateSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_update_job_results(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.update_job_results( + "job_id", + results={}, + ) + assert_matches_type(object, extract, path=["response"]) + + @parametrize + async def test_raw_response_update_job_results(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.update_job_results( + "job_id", + results={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(object, extract, path=["response"]) + + @parametrize + async def test_streaming_response_update_job_results(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.update_job_results( + "job_id", + results={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(object, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_update_job_results(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `job_id` but received ''"): + await async_client.extract.with_raw_response.update_job_results( + "", + results={}, + ) + + @parametrize + async def test_method_update_schema(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.update_schema( + "schema_id", + ) + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_method_update_schema_with_all_params(self, async_client: AsyncContextualAI) -> None: + extract = await async_client.extract.update_schema( + "schema_id", + name="name", + description="description", + schema_definition={}, + metadata={}, + ) + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_raw_response_update_schema(self, async_client: AsyncContextualAI) -> None: + response = await async_client.extract.with_raw_response.update_schema( + "schema_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + extract = await response.parse() + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + @parametrize + async def test_streaming_response_update_schema(self, async_client: AsyncContextualAI) -> None: + async with async_client.extract.with_streaming_response.update_schema( + "schema_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + extract = await response.parse() + assert_matches_type(ExtractUpdateSchemaResponse, extract, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_update_schema(self, async_client: AsyncContextualAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schema_id` but received ''"): + await async_client.extract.with_raw_response.update_schema( + "", + ) diff --git a/tests/api_resources/test_workspaces.py b/tests/api_resources/test_workspaces.py new file mode 100644 index 00000000..76963217 --- /dev/null +++ b/tests/api_resources/test_workspaces.py @@ -0,0 +1,139 @@ +# File generated from our OpenAPI spec. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from contextual import ContextualAI, AsyncContextualAI +from tests.utils import assert_matches_type +from contextual.types import ( + WorkspaceUpdateConsentResponse, + WorkspaceRetrieveConsentResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestWorkspaces: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_retrieve_consent(self, client: ContextualAI) -> None: + workspace = client.workspaces.retrieve_consent() + assert_matches_type(WorkspaceRetrieveConsentResponse, workspace, path=["response"]) + + @parametrize + def test_raw_response_retrieve_consent(self, client: ContextualAI) -> None: + response = client.workspaces.with_raw_response.retrieve_consent() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace = response.parse() + assert_matches_type(WorkspaceRetrieveConsentResponse, workspace, path=["response"]) + + @parametrize + def test_streaming_response_retrieve_consent(self, client: ContextualAI) -> None: + with client.workspaces.with_streaming_response.retrieve_consent() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace = response.parse() + assert_matches_type(WorkspaceRetrieveConsentResponse, workspace, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_update_consent(self, client: ContextualAI) -> None: + workspace = client.workspaces.update_consent( + type="CONSENT_FULL", + ) + assert_matches_type(WorkspaceUpdateConsentResponse, workspace, path=["response"]) + + @parametrize + def test_raw_response_update_consent(self, client: ContextualAI) -> None: + response = client.workspaces.with_raw_response.update_consent( + type="CONSENT_FULL", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace = response.parse() + assert_matches_type(WorkspaceUpdateConsentResponse, workspace, path=["response"]) + + @parametrize + def test_streaming_response_update_consent(self, client: ContextualAI) -> None: + with client.workspaces.with_streaming_response.update_consent( + type="CONSENT_FULL", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace = response.parse() + assert_matches_type(WorkspaceUpdateConsentResponse, workspace, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncWorkspaces: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @parametrize + async def test_method_retrieve_consent(self, async_client: AsyncContextualAI) -> None: + workspace = await async_client.workspaces.retrieve_consent() + assert_matches_type(WorkspaceRetrieveConsentResponse, workspace, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_consent(self, async_client: AsyncContextualAI) -> None: + response = await async_client.workspaces.with_raw_response.retrieve_consent() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace = await response.parse() + assert_matches_type(WorkspaceRetrieveConsentResponse, workspace, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_consent(self, async_client: AsyncContextualAI) -> None: + async with async_client.workspaces.with_streaming_response.retrieve_consent() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace = await response.parse() + assert_matches_type(WorkspaceRetrieveConsentResponse, workspace, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_update_consent(self, async_client: AsyncContextualAI) -> None: + workspace = await async_client.workspaces.update_consent( + type="CONSENT_FULL", + ) + assert_matches_type(WorkspaceUpdateConsentResponse, workspace, path=["response"]) + + @parametrize + async def test_raw_response_update_consent(self, async_client: AsyncContextualAI) -> None: + response = await async_client.workspaces.with_raw_response.update_consent( + type="CONSENT_FULL", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace = await response.parse() + assert_matches_type(WorkspaceUpdateConsentResponse, workspace, path=["response"]) + + @parametrize + async def test_streaming_response_update_consent(self, async_client: AsyncContextualAI) -> None: + async with async_client.workspaces.with_streaming_response.update_consent( + type="CONSENT_FULL", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace = await response.parse() + assert_matches_type(WorkspaceUpdateConsentResponse, workspace, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/test_added_calls_stubbed.py b/tests/test_added_calls_stubbed.py new file mode 100644 index 00000000..2dcea721 --- /dev/null +++ b/tests/test_added_calls_stubbed.py @@ -0,0 +1,97 @@ +# Checks each call added from the live API description against a stubbed transport (respx). +# For every call: one request with the description's method and path, every argument sent where the description +# puts it, and the documented response parsed into the method's return type with strict validation on. + +from __future__ import annotations + +import json +from typing import Any, Dict, cast + +import httpx +import respx +import pytest + +from contextual import ContextualAI, AsyncContextualAI, types +from contextual._models import BaseModel + +base_url = "http://stub.test" + +CASES: list[Dict[str, Any]] = json.loads( + '[{"id": "extract.delete_document", "resource": "extract", "method": "delete_document", "http": "DELETE", "path": "/extract/documents/document_id-value", "args": ["document_id-value"], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {}, "response_type": "ExtractDeleteDocumentResponse", "multipart": []}, {"id": "extract.delete_schema", "resource": "extract", "method": "delete_schema", "http": "DELETE", "path": "/extract/schemas/schema_id-value", "args": ["schema_id-value"], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {}, "response_type": "ExtractDeleteSchemaResponse", "multipart": []}, {"id": "extract.list_documents", "resource": "extract", "method": "list_documents", "http": "GET", "path": "/extract/documents", "args": [], "kwargs": {"limit": 1, "cursor": "cursor-value", "search": "search-value"}, "body": {}, "query": {"limit": "1", "cursor": "cursor-value", "search": "search-value"}, "headers": {}, "response": {"documents": [{"document_id": "document_id-value", "file_name": "file_name-value", "file_size": 1, "page_count": 1, "uploaded_at": "uploaded_at-value", "status": "status-value", "signed_url": "signed_url-value"}], "total_count": 1, "next_cursor": "next_cursor-value", "prev_cursor": "prev_cursor-value"}, "response_type": "ExtractListDocumentsResponse", "multipart": []}, {"id": "extract.retrieve_document", "resource": "extract", "method": "retrieve_document", "http": "GET", "path": "/extract/documents/document_id-value", "args": ["document_id-value"], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"document_id": "document_id-value", "file_name": "file_name-value", "file_size": 1, "page_count": 1, "uploaded_at": "uploaded_at-value", "status": "status-value", "signed_url": "signed_url-value"}, "response_type": "ExtractRetrieveDocumentResponse", "multipart": []}, {"id": "extract.list_jobs", "resource": "extract", "method": "list_jobs", "http": "GET", "path": "/extract/jobs", "args": [], "kwargs": {"limit": 1, "cursor": "cursor-value", "job_status": "job_status-value", "search": "search-value"}, "body": {}, "query": {"limit": "1", "cursor": "cursor-value", "job_status": "job_status-value", "search": "search-value"}, "headers": {}, "response": {"jobs": [{"job_id": "job_id-value", "status": "pending", "created_at": "created_at-value", "progress": {"completion_percentage": 1, "current_step": "current_step-value", "fields_processed": 1, "total_fields": 1}, "current_activity": "current_activity-value", "schema_id": "schema_id-value", "document_id": "document_id-value", "config": {"model": "gemini-2.5-flash", "per_key_attribution": true, "temperature": 1.5, "enable_thinking": true, "additional_instructions": "additional_instructions-value", "enable_agentic_array_extraction": true}}], "total_count": 1, "next_cursor": "next_cursor-value", "prev_cursor": "prev_cursor-value"}, "response_type": "ExtractListJobsResponse", "multipart": []}, {"id": "extract.retrieve_job", "resource": "extract", "method": "retrieve_job", "http": "GET", "path": "/extract/jobs/job_id-value", "args": ["job_id-value"], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"job_id": "job_id-value", "status": "pending", "created_at": "created_at-value", "progress": {"completion_percentage": 1, "current_step": "current_step-value", "fields_processed": 1, "total_fields": 1}, "current_activity": "current_activity-value", "schema_id": "schema_id-value", "document_id": "document_id-value", "config": {"model": "gemini-2.5-flash", "per_key_attribution": true, "temperature": 1.5, "enable_thinking": true, "additional_instructions": "additional_instructions-value", "enable_agentic_array_extraction": true}}, "response_type": "ExtractRetrieveJobResponse", "multipart": []}, {"id": "extract.retrieve_job_results", "resource": "extract", "method": "retrieve_job_results", "http": "GET", "path": "/extract/jobs/job_id-value/results", "args": ["job_id-value"], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"job_id": "job_id-value", "status": "pending", "results": {}, "metadata": {}, "config": {"model": "gemini-2.5-flash", "per_key_attribution": true, "temperature": 1.5, "enable_thinking": true, "additional_instructions": "additional_instructions-value", "enable_agentic_array_extraction": true}}, "response_type": "ExtractRetrieveJobResultsResponse", "multipart": []}, {"id": "extract.list_schemas", "resource": "extract", "method": "list_schemas", "http": "GET", "path": "/extract/schemas", "args": [], "kwargs": {"limit": 1, "cursor": "cursor-value", "search": "search-value"}, "body": {}, "query": {"limit": "1", "cursor": "cursor-value", "search": "search-value"}, "headers": {}, "response": {"schemas": [{"schema_id": "schema_id-value", "name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}, "created_at": "created_at-value", "updated_at": "updated_at-value"}], "total_count": 1, "next_cursor": "next_cursor-value", "prev_cursor": "prev_cursor-value"}, "response_type": "ExtractListSchemasResponse", "multipart": []}, {"id": "extract.retrieve_schema", "resource": "extract", "method": "retrieve_schema", "http": "GET", "path": "/extract/schemas/schema_id-value", "args": ["schema_id-value"], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"schema_id": "schema_id-value", "name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}, "created_at": "created_at-value", "updated_at": "updated_at-value"}, "response_type": "ExtractRetrieveSchemaResponse", "multipart": []}, {"id": "extract.upload_document", "resource": "extract", "method": "upload_document", "http": "POST", "path": "/extract/documents/upload", "args": [], "kwargs": {"file": "__FILE__"}, "body": {}, "query": {}, "headers": {}, "response": {"document_id": "document_id-value", "file_name": "file_name-value", "file_size": 1, "page_count": 1, "uploaded_at": "uploaded_at-value", "status": "status-value"}, "response_type": "ExtractUploadDocumentResponse", "multipart": ["file"]}, {"id": "extract.create_job", "resource": "extract", "method": "create_job", "http": "POST", "path": "/extract/jobs", "args": [], "kwargs": {"document_id": "document_id-value", "schema_id": "schema_id-value", "config": {"model": "gemini-2.5-flash", "per_key_attribution": true, "temperature": 1.5, "enable_thinking": true, "additional_instructions": "additional_instructions-value", "enable_agentic_array_extraction": true}, "stream": true}, "body": {"document_id": "document_id-value", "schema_id": "schema_id-value", "config": {"model": "gemini-2.5-flash", "per_key_attribution": true, "temperature": 1.5, "enable_thinking": true, "additional_instructions": "additional_instructions-value", "enable_agentic_array_extraction": true}, "stream": true}, "query": {}, "headers": {}, "response": {"job_id": "job_id-value", "status": "pending", "created_at": "created_at-value", "estimated_completion": "estimated_completion-value"}, "response_type": "ExtractCreateJobResponse", "multipart": []}, {"id": "extract.create_schema", "resource": "extract", "method": "create_schema", "http": "POST", "path": "/extract/schemas", "args": [], "kwargs": {"name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}}, "body": {"name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}}, "query": {}, "headers": {}, "response": {"schema_id": "schema_id-value", "name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}, "created_at": "created_at-value", "updated_at": "updated_at-value"}, "response_type": "ExtractCreateSchemaResponse", "multipart": []}, {"id": "extract.update_job_results", "resource": "extract", "method": "update_job_results", "http": "PUT", "path": "/extract/jobs/job_id-value/results", "args": ["job_id-value"], "kwargs": {"results": {}}, "body": {"results": {}}, "query": {}, "headers": {}, "response": {}, "response_type": "object", "multipart": []}, {"id": "extract.update_schema", "resource": "extract", "method": "update_schema", "http": "PUT", "path": "/extract/schemas/schema_id-value", "args": ["schema_id-value"], "kwargs": {"name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}}, "body": {"name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}}, "query": {}, "headers": {}, "response": {"schema_id": "schema_id-value", "name": "name-value", "description": "description-value", "schema_definition": {}, "metadata": {}, "created_at": "created_at-value", "updated_at": "updated_at-value"}, "response_type": "ExtractUpdateSchemaResponse", "multipart": []}, {"id": "billing.retrieve_balance", "resource": "billing", "method": "retrieve_balance", "http": "GET", "path": "/billing/balance", "args": [], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"balance": 1.5}, "response_type": "BillingRetrieveBalanceResponse", "multipart": []}, {"id": "billing.list_top_ups", "resource": "billing", "method": "list_top_ups", "http": "GET", "path": "/billing/balance/top-ups", "args": [], "kwargs": {"limit": 1, "cursor": "cursor-value"}, "body": {}, "query": {"limit": "1", "cursor": "cursor-value"}, "headers": {}, "response": {"top_ups": [{"amount": 1.5, "created_at": "2026-01-15T10:00:00+00:00", "description": "description-value", "starting_balance": 1.5, "ending_balance": 1.5}], "has_more": true, "cursor": "cursor-value"}, "response_type": "BillingListTopUpsResponse", "multipart": []}, {"id": "billing.retrieve_billing_mode_history", "resource": "billing", "method": "retrieve_billing_mode_history", "http": "GET", "path": "/billing/billing_mode/history", "args": [], "kwargs": {"year": 2025, "month": 1}, "body": {}, "query": {"year": "2025", "month": "1"}, "headers": {}, "response": {"billing_modes": [{"date": "2026-01-15", "billing_mode": "ON_DEMAND_PREPAID"}]}, "response_type": "BillingRetrieveBillingModeHistoryResponse", "multipart": []}, {"id": "billing.retrieve_metadata", "resource": "billing", "method": "retrieve_metadata", "http": "GET", "path": "/billing/metadata", "args": [], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"is_low_balance": true, "is_auto_top_up_enabled": true}, "response_type": "BillingRetrieveMetadataResponse", "multipart": []}, {"id": "billing.retrieve_acl_usage", "resource": "billing", "method": "retrieve_acl_usage", "http": "GET", "path": "/billing/usages/acl", "args": [], "kwargs": {"year": 2025, "month": 1, "resource_id": "resource_id-value"}, "body": {}, "query": {"year": "2025", "month": "1", "resource_id": "resource_id-value"}, "headers": {}, "response": {"usages": [{"step_name": "step_name-value", "date": "date-value", "input_tokens": 1, "output_tokens": 1, "total_cost": 1.5}]}, "response_type": "BillingRetrieveAclUsageResponse", "multipart": []}, {"id": "billing.retrieve_earliest_usage_date", "resource": "billing", "method": "retrieve_earliest_usage_date", "http": "GET", "path": "/billing/usages/earliest_date", "args": [], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"date": "2026-01-15"}, "response_type": "BillingRetrieveEarliestUsageDateResponse", "multipart": []}, {"id": "billing.retrieve_monthly_usage", "resource": "billing", "method": "retrieve_monthly_usage", "http": "GET", "path": "/billing/usages/monthly", "args": [], "kwargs": {"year": 2025, "month": 1, "resource_id": "resource_id-value"}, "body": {}, "query": {"year": "2025", "month": "1", "resource_id": "resource_id-value"}, "headers": {}, "response": {"usages": [{"date": "2026-01-15", "usage_type": "QUERY_REFORMULATION_INPUT_TOKEN", "quantity": 1, "price": 1.5}]}, "response_type": "BillingRetrieveMonthlyUsageResponse", "multipart": []}, {"id": "workspaces.retrieve_consent", "resource": "workspaces", "method": "retrieve_consent", "http": "GET", "path": "/workspaces/consent", "args": [], "kwargs": {}, "body": {}, "query": {}, "headers": {}, "response": {"status": "status-value", "email": "email-value", "created_at": "created_at-value"}, "response_type": "WorkspaceRetrieveConsentResponse", "multipart": []}, {"id": "workspaces.update_consent", "resource": "workspaces", "method": "update_consent", "http": "PUT", "path": "/workspaces/consent", "args": [], "kwargs": {"type": "CONSENT_FULL"}, "body": {"type": "CONSENT_FULL"}, "query": {}, "headers": {}, "response": {}, "response_type": "WorkspaceUpdateConsentResponse", "multipart": []}]' +) + + +def _check_request(route: respx.Route, case: Dict[str, Any]) -> None: + assert route.call_count == 1 + request = cast(httpx.Request, route.calls[0].request) # pyright: ignore[reportUnknownMemberType] + assert request.method == case["http"] + assert request.url.path == case["path"] + if case["multipart"]: + # a file upload goes as multipart form data, with every field the description names + assert request.headers["content-type"].startswith("multipart/form-data") + for key in case["multipart"]: + assert f'name="{key}"'.encode() in request.content, key + elif case["body"]: + sent = json.loads(request.content or b"{}") + for key, expected in case["body"].items(): + assert sent.get(key) == expected, key + for key, expected in case["query"].items(): + assert str(request.url.params.get(key)).lower() == expected.lower(), key + for key, expected in case["headers"].items(): + assert request.headers.get(key) == expected, key + + +def _kwargs(case: Dict[str, Any]) -> Dict[str, Any]: + return {k: (b"%PDF-1.4 stub" if v == "__FILE__" else v) for k, v in case["kwargs"].items()} + + +def _check_response(result: Any, case: Dict[str, Any]) -> None: + if case["response_type"] == "None": + # a call whose success response has no body returns None + assert result is None + return + expected = case["response"] + if isinstance(result, BaseModel): + # every field of the documented response came back, under its wire name + assert set(result.to_dict(use_api_names=True).keys()) == set(expected.keys()) + elif isinstance(expected, str): + # a string response comes back as the response body's text, as the existing string methods do + assert result == json.dumps(expected) + else: + # a list or map response is returned as parsed + assert result == expected + if case["response_type"] == "object": + return # an untyped response: returned as parsed, checked above + expected_type = getattr(types, case["response_type"]) + if isinstance(expected_type, type): + assert isinstance(result, expected_type) + + +@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES]) +@respx.mock +def test_added_call_sync(case: Dict[str, Any]) -> None: + route = respx.route(method=case["http"], url__startswith=base_url + case["path"]).mock( + return_value=httpx.Response(204) + if case["response_type"] == "None" + else httpx.Response(200, json=case["response"]) + ) + client = ContextualAI(base_url=base_url, api_key="My API Key", _strict_response_validation=True) + method = getattr(getattr(client, case["resource"]), case["method"]) + result = method(*case["args"], **_kwargs(case)) + _check_request(route, case) + _check_response(result, case) + + +@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES]) +@respx.mock +async def test_added_call_async(case: Dict[str, Any]) -> None: + route = respx.route(method=case["http"], url__startswith=base_url + case["path"]).mock( + return_value=httpx.Response(204) + if case["response_type"] == "None" + else httpx.Response(200, json=case["response"]) + ) + client = AsyncContextualAI(base_url=base_url, api_key="My API Key", _strict_response_validation=True) + method = getattr(getattr(client, case["resource"]), case["method"]) + result = await method(*case["args"], **_kwargs(case)) + _check_request(route, case) + _check_response(result, case)