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 .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ USER vscode
RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.35.0" RYE_INSTALL_OPTION="--yes" bash
ENV PATH=/home/vscode/.rye/shims:$PATH

RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc
RUN echo "[[ -d .venv ]] && source .venv/bin/activate || export PATH=\$PATH" >> /home/vscode/.bashrc
3 changes: 3 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
}
}
}
},
"features": {
"ghcr.io/devcontainers/features/node:1": {}
}

// Features to add to the dev container. More info: https://containers.dev/features.
Expand Down
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.2.0"
".": "0.3.0"
}
4 changes: 2 additions & 2 deletions .stats.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
configured_endpoints: 35
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/contextual-ai%2Fsunrise-d79ccb778953ad5c2ae4b99115429c8b3f68b3b23d9b6d90b1b40393f11a4383.yml
configured_endpoints: 46
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/contextual-ai%2Fsunrise-5298551c424bb999f258bdd6c311e96c80c70701ad59bbce19b46c788ee13bd4.yml
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
# Changelog

## 0.3.0 (2025-02-26)

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

### Features

* **api:** update via SDK Studio ([#41](https://github.com/ContextualAI/contextual-client-python/issues/41)) ([4b3ea42](https://github.com/ContextualAI/contextual-client-python/commit/4b3ea42dd9effb3cec4fb078800ca96dc3609617))
* **api:** update via SDK Studio ([#49](https://github.com/ContextualAI/contextual-client-python/issues/49)) ([d54defd](https://github.com/ContextualAI/contextual-client-python/commit/d54defd3a23a488c24cae38bedd86d5721d8a71b))
* **api:** update via SDK Studio ([#50](https://github.com/ContextualAI/contextual-client-python/issues/50)) ([6060be1](https://github.com/ContextualAI/contextual-client-python/commit/6060be19c881d87e5ab7b63bc60f536a6b9e70cc))
* **client:** allow passing `NotGiven` for body ([#46](https://github.com/ContextualAI/contextual-client-python/issues/46)) ([4e2264d](https://github.com/ContextualAI/contextual-client-python/commit/4e2264da0b35d4dcfbf33a77950f0f7d57f1db14))


### Bug Fixes

* asyncify on non-asyncio runtimes ([#44](https://github.com/ContextualAI/contextual-client-python/issues/44)) ([3a16763](https://github.com/ContextualAI/contextual-client-python/commit/3a16763381747ee6ccf829fb535927446634d54c))
* **client:** mark some request bodies as optional ([4e2264d](https://github.com/ContextualAI/contextual-client-python/commit/4e2264da0b35d4dcfbf33a77950f0f7d57f1db14))


### Chores

* **internal:** codegen related update ([#45](https://github.com/ContextualAI/contextual-client-python/issues/45)) ([2651383](https://github.com/ContextualAI/contextual-client-python/commit/26513832dc75629f229493f4718e97a34588fd97))
* **internal:** fix devcontainers setup ([#47](https://github.com/ContextualAI/contextual-client-python/issues/47)) ([f5ea511](https://github.com/ContextualAI/contextual-client-python/commit/f5ea51125d954e2ef39e817c0a7bae763661c571))
* **internal:** properly set __pydantic_private__ ([#48](https://github.com/ContextualAI/contextual-client-python/issues/48)) ([b49c8a0](https://github.com/ContextualAI/contextual-client-python/commit/b49c8a0b97a15495912999b97b6b754d2dcfbb4e))
* **internal:** update client tests ([#43](https://github.com/ContextualAI/contextual-client-python/issues/43)) ([ee164e9](https://github.com/ContextualAI/contextual-client-python/commit/ee164e9e3a7f15570560922d383565ea4a50d446))

## 0.2.0 (2025-02-08)

Full Changelog: [v0.1.0...v0.2.0](https://github.com/ContextualAI/contextual-client-python/compare/v0.1.0...v0.2.0)
Expand Down
32 changes: 25 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ client = ContextualAI(
)

create_agent_output = client.agents.create(
name="xxx",
name="Example",
)
print(create_agent_output.id)
```
Expand All @@ -56,7 +56,7 @@ client = AsyncContextualAI(

async def main() -> None:
create_agent_output = await client.agents.create(
name="xxx",
name="Example",
)
print(create_agent_output.id)

Expand Down Expand Up @@ -138,6 +138,24 @@ for agent in first_page.agents:
# Remove `await` for non-async usage.
```

## File uploads

Request parameters that correspond to file uploads can be passed as `bytes`, a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.

```python
from pathlib import Path
from contextual import ContextualAI

client = ContextualAI()

client.datastores.documents.ingest(
datastore_id="182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
file=Path("/path/to/file"),
)
```

The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.

## Handling errors

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `contextual.APIConnectionError` is raised.
Expand All @@ -155,7 +173,7 @@ client = ContextualAI()

try:
client.agents.create(
name="xxx",
name="Example",
)
except contextual.APIConnectionError as e:
print("The server could not be reached")
Expand Down Expand Up @@ -200,7 +218,7 @@ client = ContextualAI(

# Or, configure per-request:
client.with_options(max_retries=5).agents.create(
name="xxx",
name="Example",
)
```

Expand All @@ -225,7 +243,7 @@ client = ContextualAI(

# Override per-request:
client.with_options(timeout=5.0).agents.create(
name="xxx",
name="Example",
)
```

Expand Down Expand Up @@ -268,7 +286,7 @@ from contextual import ContextualAI

client = ContextualAI()
response = client.agents.with_raw_response.create(
name="xxx",
name="Example",
)
print(response.headers.get('X-My-Header'))

Expand All @@ -288,7 +306,7 @@ To stream the response body, use `.with_streaming_response` instead, which requi

```python
with client.agents.with_streaming_response.create(
name="xxx",
name="Example",
) as response:
print(response.headers.get("X-My-Header"))

Expand Down
39 changes: 39 additions & 0 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Methods:
- <code title="delete /datastores/{datastore_id}/documents/{document_id}">client.datastores.documents.<a href="./src/contextual/resources/datastores/documents.py">delete</a>(document_id, \*, datastore_id) -> <a href="./src/contextual/types/datastores/document_delete_response.py">object</a></code>
- <code title="post /datastores/{datastore_id}/documents">client.datastores.documents.<a href="./src/contextual/resources/datastores/documents.py">ingest</a>(datastore_id, \*\*<a href="src/contextual/types/datastores/document_ingest_params.py">params</a>) -> <a href="./src/contextual/types/datastores/ingestion_response.py">IngestionResponse</a></code>
- <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="post /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>

# Agents

Expand Down Expand Up @@ -120,6 +121,23 @@ Types:
from contextual.types.agents import CreateDatasetResponse, DatasetMetadata, ListDatasetsResponse
```

### Tune

Types:

```python
from contextual.types.agents.datasets import TuneDeleteResponse
```

Methods:

- <code title="post /agents/{agent_id}/datasets/tune">client.agents.datasets.tune.<a href="./src/contextual/resources/agents/datasets/tune.py">create</a>(agent_id, \*\*<a href="src/contextual/types/agents/datasets/tune_create_params.py">params</a>) -> <a href="./src/contextual/types/agents/create_dataset_response.py">CreateDatasetResponse</a></code>
- <code title="get /agents/{agent_id}/datasets/tune/{dataset_name}">client.agents.datasets.tune.<a href="./src/contextual/resources/agents/datasets/tune.py">retrieve</a>(dataset_name, \*, agent_id, \*\*<a href="src/contextual/types/agents/datasets/tune_retrieve_params.py">params</a>) -> BinaryAPIResponse</code>
- <code title="put /agents/{agent_id}/datasets/tune/{dataset_name}">client.agents.datasets.tune.<a href="./src/contextual/resources/agents/datasets/tune.py">update</a>(dataset_name, \*, agent_id, \*\*<a href="src/contextual/types/agents/datasets/tune_update_params.py">params</a>) -> <a href="./src/contextual/types/agents/create_dataset_response.py">CreateDatasetResponse</a></code>
- <code title="get /agents/{agent_id}/datasets/tune">client.agents.datasets.tune.<a href="./src/contextual/resources/agents/datasets/tune.py">list</a>(agent_id, \*\*<a href="src/contextual/types/agents/datasets/tune_list_params.py">params</a>) -> <a href="./src/contextual/types/agents/list_datasets_response.py">ListDatasetsResponse</a></code>
- <code title="delete /agents/{agent_id}/datasets/tune/{dataset_name}">client.agents.datasets.tune.<a href="./src/contextual/resources/agents/datasets/tune.py">delete</a>(dataset_name, \*, agent_id) -> <a href="./src/contextual/types/agents/datasets/tune_delete_response.py">object</a></code>
- <code title="get /agents/{agent_id}/datasets/tune/{dataset_name}/metadata">client.agents.datasets.tune.<a href="./src/contextual/resources/agents/datasets/tune.py">metadata</a>(dataset_name, \*, agent_id, \*\*<a href="src/contextual/types/agents/datasets/tune_metadata_params.py">params</a>) -> <a href="./src/contextual/types/agents/dataset_metadata.py">DatasetMetadata</a></code>

### Evaluate

Types:
Expand Down Expand Up @@ -175,6 +193,27 @@ Methods:

- <code title="get /agents/{agent_id}/tune/models">client.agents.tune.models.<a href="./src/contextual/resources/agents/tune/models.py">list</a>(agent_id) -> <a href="./src/contextual/types/agents/tune/list_tune_models_response.py">ListTuneModelsResponse</a></code>

# Users

Types:

```python
from contextual.types import (
InviteUsersResponse,
ListUsersResponse,
NewUser,
UserUpdateResponse,
UserDeactivateResponse,
)
```

Methods:

- <code title="put /users">client.users.<a href="./src/contextual/resources/users.py">update</a>(\*\*<a href="src/contextual/types/user_update_params.py">params</a>) -> <a href="./src/contextual/types/user_update_response.py">object</a></code>
- <code title="get /users">client.users.<a href="./src/contextual/resources/users.py">list</a>(\*\*<a href="src/contextual/types/user_list_params.py">params</a>) -> SyncUsersPage[User]</code>
- <code title="delete /users">client.users.<a href="./src/contextual/resources/users.py">deactivate</a>(\*\*<a href="src/contextual/types/user_deactivate_params.py">params</a>) -> <a href="./src/contextual/types/user_deactivate_response.py">object</a></code>
- <code title="post /users">client.users.<a href="./src/contextual/resources/users.py">invite</a>(\*\*<a href="src/contextual/types/user_invite_params.py">params</a>) -> <a href="./src/contextual/types/invite_users_response.py">InviteUsersResponse</a></code>

# LMUnit

Types:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "contextual-client"
version = "0.2.0"
version = "0.3.0"
description = "The official Python library for the Contextual AI API"
dynamic = ["readme"]
license = "Apache-2.0"
Expand Down
10 changes: 8 additions & 2 deletions src/contextual/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
ModelBuilderProtocol,
)
from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping
from ._compat import model_copy, model_dump
from ._compat import PYDANTIC_V2, model_copy, model_dump
from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type
from ._response import (
APIResponse,
Expand Down Expand Up @@ -207,6 +207,9 @@ def _set_private_attributes(
model: Type[_T],
options: FinalRequestOptions,
) -> None:
if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None:
self.__pydantic_private__ = {}

self._model = model
self._client = client
self._options = options
Expand Down Expand Up @@ -292,6 +295,9 @@ def _set_private_attributes(
client: AsyncAPIClient,
options: FinalRequestOptions,
) -> None:
if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None:
self.__pydantic_private__ = {}

self._model = model
self._client = client
self._options = options
Expand Down Expand Up @@ -518,7 +524,7 @@ def _build_request(
# so that passing a `TypedDict` doesn't cause an error.
# https://github.com/microsoft/pyright/issues/3526#event-6715453066
params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None,
json=json_data,
json=json_data if is_given(json_data) else None,
files=files,
**kwargs,
)
Expand Down
10 changes: 9 additions & 1 deletion src/contextual/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
get_async_library,
)
from ._version import __version__
from .resources import lmunit, rerank, generate
from .resources import users, lmunit, rerank, generate
from ._streaming import Stream as Stream, AsyncStream as AsyncStream
from ._exceptions import APIStatusError, ContextualAIError
from ._base_client import (
Expand All @@ -50,6 +50,7 @@
class ContextualAI(SyncAPIClient):
datastores: datastores.DatastoresResource
agents: agents.AgentsResource
users: users.UsersResource
lmunit: lmunit.LMUnitResource
rerank: rerank.RerankResource
generate: generate.GenerateResource
Expand Down Expand Up @@ -118,6 +119,7 @@ def __init__(

self.datastores = datastores.DatastoresResource(self)
self.agents = agents.AgentsResource(self)
self.users = users.UsersResource(self)
self.lmunit = lmunit.LMUnitResource(self)
self.rerank = rerank.RerankResource(self)
self.generate = generate.GenerateResource(self)
Expand Down Expand Up @@ -235,6 +237,7 @@ def _make_status_error(
class AsyncContextualAI(AsyncAPIClient):
datastores: datastores.AsyncDatastoresResource
agents: agents.AsyncAgentsResource
users: users.AsyncUsersResource
lmunit: lmunit.AsyncLMUnitResource
rerank: rerank.AsyncRerankResource
generate: generate.AsyncGenerateResource
Expand Down Expand Up @@ -303,6 +306,7 @@ def __init__(

self.datastores = datastores.AsyncDatastoresResource(self)
self.agents = agents.AsyncAgentsResource(self)
self.users = users.AsyncUsersResource(self)
self.lmunit = lmunit.AsyncLMUnitResource(self)
self.rerank = rerank.AsyncRerankResource(self)
self.generate = generate.AsyncGenerateResource(self)
Expand Down Expand Up @@ -421,6 +425,7 @@ class ContextualAIWithRawResponse:
def __init__(self, client: ContextualAI) -> None:
self.datastores = datastores.DatastoresResourceWithRawResponse(client.datastores)
self.agents = agents.AgentsResourceWithRawResponse(client.agents)
self.users = users.UsersResourceWithRawResponse(client.users)
self.lmunit = lmunit.LMUnitResourceWithRawResponse(client.lmunit)
self.rerank = rerank.RerankResourceWithRawResponse(client.rerank)
self.generate = generate.GenerateResourceWithRawResponse(client.generate)
Expand All @@ -430,6 +435,7 @@ class AsyncContextualAIWithRawResponse:
def __init__(self, client: AsyncContextualAI) -> None:
self.datastores = datastores.AsyncDatastoresResourceWithRawResponse(client.datastores)
self.agents = agents.AsyncAgentsResourceWithRawResponse(client.agents)
self.users = users.AsyncUsersResourceWithRawResponse(client.users)
self.lmunit = lmunit.AsyncLMUnitResourceWithRawResponse(client.lmunit)
self.rerank = rerank.AsyncRerankResourceWithRawResponse(client.rerank)
self.generate = generate.AsyncGenerateResourceWithRawResponse(client.generate)
Expand All @@ -439,6 +445,7 @@ class ContextualAIWithStreamedResponse:
def __init__(self, client: ContextualAI) -> None:
self.datastores = datastores.DatastoresResourceWithStreamingResponse(client.datastores)
self.agents = agents.AgentsResourceWithStreamingResponse(client.agents)
self.users = users.UsersResourceWithStreamingResponse(client.users)
self.lmunit = lmunit.LMUnitResourceWithStreamingResponse(client.lmunit)
self.rerank = rerank.RerankResourceWithStreamingResponse(client.rerank)
self.generate = generate.GenerateResourceWithStreamingResponse(client.generate)
Expand All @@ -448,6 +455,7 @@ class AsyncContextualAIWithStreamedResponse:
def __init__(self, client: AsyncContextualAI) -> None:
self.datastores = datastores.AsyncDatastoresResourceWithStreamingResponse(client.datastores)
self.agents = agents.AsyncAgentsResourceWithStreamingResponse(client.agents)
self.users = users.AsyncUsersResourceWithStreamingResponse(client.users)
self.lmunit = lmunit.AsyncLMUnitResourceWithStreamingResponse(client.lmunit)
self.rerank = rerank.AsyncRerankResourceWithStreamingResponse(client.rerank)
self.generate = generate.AsyncGenerateResourceWithStreamingResponse(client.generate)
Expand Down
2 changes: 1 addition & 1 deletion src/contextual/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
if not is_file_content(obj):
prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`"
raise RuntimeError(
f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead."
f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/ContextualAI/contextual-client-python/tree/main#file-uploads"
) from None


Expand Down
19 changes: 17 additions & 2 deletions src/contextual/_utils/_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@
from typing import Any, TypeVar, Callable, Awaitable
from typing_extensions import ParamSpec

import anyio
import sniffio
import anyio.to_thread

T_Retval = TypeVar("T_Retval")
T_ParamSpec = ParamSpec("T_ParamSpec")


if sys.version_info >= (3, 9):
to_thread = asyncio.to_thread
_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 to_thread(
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.
Expand All @@ -34,6 +38,17 @@ async def to_thread(
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 anyio.to_thread.run_sync(
functools.partial(func, *args, **kwargs),
)


# inspired by `asyncer`, https://github.com/tiangolo/asyncer
def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
"""
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.2.0" # x-release-please-version
__version__ = "0.3.0" # x-release-please-version
Loading