Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.9.0"
".": "0.10.0"
}
4 changes: 2 additions & 2 deletions .stats.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
configured_endpoints: 34
configured_endpoints: 36
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/contextual-ai%2Fsunrise-c8152db455001be3f09a3bc60d63711699d2c2a4ea5f7bbc1d71726efda0fd9b.yml
openapi_spec_hash: 97719df292ca220de5d35d36f9756b95
config_hash: ae81af9b7eb88a788a80bcf3480e0b6b
config_hash: fdaf751580ba8a60e222e560847af1ac
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# Changelog

## 0.10.0 (2025-11-11)

Full Changelog: [v0.9.0...v0.10.0](https://github.com/ContextualAI/contextual-client-python/compare/v0.9.0...v0.10.0)

### Features

* **api:** update via SDK Studio ([921ea1c](https://github.com/ContextualAI/contextual-client-python/commit/921ea1c3e6e4432638c535c7e413c92d2e1398f5))


### Bug Fixes

* **client:** close streams without requiring full consumption ([3f212eb](https://github.com/ContextualAI/contextual-client-python/commit/3f212ebb31085b404c72d827f1d6992dd4bed24c))
* compat with Python 3.14 ([6f2d195](https://github.com/ContextualAI/contextual-client-python/commit/6f2d1958bb397cedb94f970c361e617e01c3fdf6))


### Chores

* **internal/tests:** avoid race condition with implicit client cleanup ([f7f3568](https://github.com/ContextualAI/contextual-client-python/commit/f7f35681c6ac40661872fbdc3159e79ff764d135))
* **internal:** grammar fix (it's -> its) ([12b822d](https://github.com/ContextualAI/contextual-client-python/commit/12b822dcede4ba84a7889775254f8b02b311ae5f))
* **package:** drop Python 3.8 support ([c2ddf6a](https://github.com/ContextualAI/contextual-client-python/commit/c2ddf6a2d51ff845cb2dcd872dc37b934ef97199))

## 0.9.0 (2025-10-28)

Full Changelog: [v0.8.0...v0.9.0](https://github.com/ContextualAI/contextual-client-python/compare/v0.8.0...v0.9.0)
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<!-- prettier-ignore -->
[![PyPI version](https://img.shields.io/pypi/v/contextual-client.svg?label=pypi%20(stable))](https://pypi.org/project/contextual-client/)

The Contextual AI Python library provides convenient access to the Contextual AI REST API from any Python 3.8+
The Contextual AI Python library provides convenient access to the Contextual AI REST API from any Python 3.9+
application. The library includes type definitions for all request params and response fields,
and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).

Expand Down Expand Up @@ -467,7 +467,7 @@ print(contextual.__version__)

## Requirements

Python 3.8 or higher.
Python 3.9 or higher.

## Contributing

Expand Down
13 changes: 13 additions & 0 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ Methods:
- <code title="get /datastores/{datastore_id}/documents/{document_id}/metadata">client.datastores.documents.<a href="./src/contextual/resources/datastores/documents.py">metadata</a>(document_id, \*, datastore_id) -> <a href="./src/contextual/types/datastores/document_metadata.py">DocumentMetadata</a></code>
- <code title="put /datastores/{datastore_id}/documents/{document_id}/metadata">client.datastores.documents.<a href="./src/contextual/resources/datastores/documents.py">set_metadata</a>(document_id, \*, datastore_id, \*\*<a href="src/contextual/types/datastores/document_set_metadata_params.py">params</a>) -> <a href="./src/contextual/types/datastores/document_metadata.py">DocumentMetadata</a></code>

## Contents

Types:

```python
from contextual.types.datastores import ContentListResponse, ContentMetadataResponse
```

Methods:

- <code title="get /datastores/{datastore_id}/contents">client.datastores.contents.<a href="./src/contextual/resources/datastores/contents.py">list</a>(datastore_id, \*\*<a href="src/contextual/types/datastores/content_list_params.py">params</a>) -> <a href="./src/contextual/types/datastores/content_list_response.py">SyncContentsPage[ContentListResponse]</a></code>
- <code title="get /datastores/{datastore_id}/contents/{content_id}/metadata">client.datastores.contents.<a href="./src/contextual/resources/datastores/contents.py">metadata</a>(content_id, \*, datastore_id, \*\*<a href="src/contextual/types/datastores/content_metadata_params.py">params</a>) -> <a href="./src/contextual/types/datastores/content_metadata_response.py">ContentMetadataResponse</a></code>

# Agents

Types:
Expand Down
7 changes: 3 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "contextual-client"
version = "0.9.0"
version = "0.10.0"
description = "The official Python library for the Contextual AI API"
dynamic = ["readme"]
license = "Apache-2.0"
Expand All @@ -15,11 +15,10 @@ dependencies = [
"distro>=1.7.0, <2",
"sniffio",
]
requires-python = ">= 3.8"
requires-python = ">= 3.9"
classifiers = [
"Typing :: Typed",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down Expand Up @@ -141,7 +140,7 @@ filterwarnings = [
# there are a couple of flags that are still disabled by
# default in strict mode as they are experimental and niche.
typeCheckingMode = "strict"
pythonVersion = "3.8"
pythonVersion = "3.9"

exclude = [
"_dev",
Expand Down
11 changes: 8 additions & 3 deletions src/contextual/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import inspect
import weakref
from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast
from datetime import date, datetime
from typing_extensions import (
Expand Down Expand Up @@ -573,6 +574,9 @@ class CachedDiscriminatorType(Protocol):
__discriminator__: DiscriminatorDetails


DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary()


class DiscriminatorDetails:
field_name: str
"""The name of the discriminator field in the variant class, e.g.
Expand Down Expand Up @@ -615,8 +619,9 @@ def __init__(


def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
if isinstance(union, CachedDiscriminatorType):
return union.__discriminator__
cached = DISCRIMINATOR_CACHE.get(union)
if cached is not None:
return cached

discriminator_field_name: str | None = None

Expand Down Expand Up @@ -669,7 +674,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,
discriminator_field=discriminator_field_name,
discriminator_alias=discriminator_alias,
)
cast(CachedDiscriminatorType, union).__discriminator__ = details
DISCRIMINATOR_CACHE.setdefault(union, details)
return details


Expand Down
10 changes: 4 additions & 6 deletions src/contextual/_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,8 @@ def __stream__(self) -> Iterator[_T]:
for sse in iterator:
yield process_data(data=sse.json(), cast_to=cast_to, response=response)

# Ensure the entire stream is consumed
for _sse in iterator:
...
# As we might not fully consume the response stream, we need to close it explicitly
response.close()

def __enter__(self) -> Self:
return self
Expand Down Expand Up @@ -121,9 +120,8 @@ async def __stream__(self) -> AsyncIterator[_T]:
async for sse in iterator:
yield process_data(data=sse.json(), cast_to=cast_to, response=response)

# Ensure the entire stream is consumed
async for _sse in iterator:
...
# As we might not fully consume the response stream, we need to close it explicitly
await response.aclose()

async def __aenter__(self) -> Self:
return self
Expand Down
34 changes: 3 additions & 31 deletions src/contextual/_utils/_sync.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from __future__ import annotations

import sys
import asyncio
import functools
import contextvars
from typing import Any, TypeVar, Callable, Awaitable
from typing import TypeVar, Callable, Awaitable
from typing_extensions import ParamSpec

import anyio
Expand All @@ -15,34 +13,11 @@
T_ParamSpec = ParamSpec("T_ParamSpec")


if sys.version_info >= (3, 9):
_asyncio_to_thread = asyncio.to_thread
else:
# backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
# for Python 3.8 support
async def _asyncio_to_thread(
func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
) -> Any:
"""Asynchronously run function *func* in a separate thread.

Any *args and **kwargs supplied for this function are directly passed
to *func*. Also, the current :class:`contextvars.Context` is propagated,
allowing context variables from the main thread to be accessed in the
separate thread.

Returns a coroutine that can be awaited to get the eventual result of *func*.
"""
loop = asyncio.events.get_running_loop()
ctx = contextvars.copy_context()
func_call = functools.partial(ctx.run, func, *args, **kwargs)
return await loop.run_in_executor(None, func_call)


async def to_thread(
func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
) -> T_Retval:
if sniffio.current_async_library() == "asyncio":
return await _asyncio_to_thread(func, *args, **kwargs)
return await asyncio.to_thread(func, *args, **kwargs)

return await anyio.to_thread.run_sync(
functools.partial(func, *args, **kwargs),
Expand All @@ -53,10 +28,7 @@ async def to_thread(
def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
"""
Take a blocking function and create an async one that receives the same
positional and keyword arguments. For python version 3.9 and above, it uses
asyncio.to_thread to run the function in a separate thread. For python version
3.8, it uses locally defined copy of the asyncio.to_thread function which was
introduced in python 3.9.
positional and keyword arguments.

Usage:

Expand Down
2 changes: 1 addition & 1 deletion src/contextual/_utils/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]:
# Type safe methods for narrowing types with TypeVars.
# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
# however this cause Pyright to rightfully report errors. As we know we don't
# care about the contained types we can safely use `object` in it's place.
# care about the contained types we can safely use `object` in its place.
#
# There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
# `is_*` is for when you're dealing with an unknown input
Expand Down
2 changes: 1 addition & 1 deletion src/contextual/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

__title__ = "contextual"
__version__ = "0.9.0" # x-release-please-version
__version__ = "0.10.0" # x-release-please-version
46 changes: 46 additions & 0 deletions src/contextual/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"AsyncUsersPage",
"SyncPage",
"AsyncPage",
"SyncContentsPage",
"AsyncContentsPage",
]

_T = TypeVar("_T")
Expand Down Expand Up @@ -177,3 +179,47 @@ def next_page_info(self) -> Optional[PageInfo]:
return None

return PageInfo(params={"cursor": next_cursor})


class SyncContentsPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
data: List[_T]

@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data

@override
def next_page_info(self) -> Optional[PageInfo]:
offset = self._options.params.get("offset") or 0
if not isinstance(offset, int):
raise ValueError(f'Expected "offset" param to be an integer but got {offset}')

length = len(self._get_page_items())
current_count = offset + length

return PageInfo(params={"offset": current_count})


class AsyncContentsPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]):
data: List[_T]

@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data

@override
def next_page_info(self) -> Optional[PageInfo]:
offset = self._options.params.get("offset") or 0
if not isinstance(offset, int):
raise ValueError(f'Expected "offset" param to be an integer but got {offset}')

length = len(self._get_page_items())
current_count = offset + length

return PageInfo(params={"offset": current_count})
14 changes: 14 additions & 0 deletions src/contextual/resources/datastores/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from .contents import (
ContentsResource,
AsyncContentsResource,
ContentsResourceWithRawResponse,
AsyncContentsResourceWithRawResponse,
ContentsResourceWithStreamingResponse,
AsyncContentsResourceWithStreamingResponse,
)
from .documents import (
DocumentsResource,
AsyncDocumentsResource,
Expand All @@ -24,6 +32,12 @@
"AsyncDocumentsResourceWithRawResponse",
"DocumentsResourceWithStreamingResponse",
"AsyncDocumentsResourceWithStreamingResponse",
"ContentsResource",
"AsyncContentsResource",
"ContentsResourceWithRawResponse",
"AsyncContentsResourceWithRawResponse",
"ContentsResourceWithStreamingResponse",
"AsyncContentsResourceWithStreamingResponse",
"DatastoresResource",
"AsyncDatastoresResource",
"DatastoresResourceWithRawResponse",
Expand Down
Loading