diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8ccc7f01..25c51a78 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,12 +1,14 @@
name: CI
on:
push:
- branches-ignore:
- - 'generated'
- - 'codegen/**'
- - 'integrated/**'
- - 'stl-preview-head/**'
- - 'stl-preview-base/**'
+ branches:
+ - '**'
+ - '!integrated/**'
+ - '!stl-preview-head/**'
+ - '!stl-preview-base/**'
+ - '!generated'
+ - '!codegen/**'
+ - 'codegen/stl/**'
pull_request:
branches-ignore:
- 'stl-preview-head/**'
@@ -17,9 +19,9 @@ jobs:
timeout-minutes: 10
name: lint
runs-on: ${{ github.repository == 'stainless-sdks/asktable-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }}
- if: github.event_name == 'push' || github.event.pull_request.head.repo.fork
+ if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata')
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Install Rye
run: |
@@ -36,15 +38,15 @@ jobs:
run: ./scripts/lint
build:
- if: github.repository == 'stainless-sdks/asktable-python' && (github.event_name == 'push' || github.event.pull_request.head.repo.fork)
+ if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata')
timeout-minutes: 10
name: build
permissions:
contents: read
id-token: write
- runs-on: depot-ubuntu-24.04
+ runs-on: ${{ github.repository == 'stainless-sdks/asktable-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Install Rye
run: |
@@ -61,12 +63,18 @@ jobs:
run: rye build
- name: Get GitHub OIDC Token
+ if: |-
+ github.repository == 'stainless-sdks/asktable-python' &&
+ !startsWith(github.ref, 'refs/heads/stl/')
id: github-oidc
- uses: actions/github-script@v6
+ uses: actions/github-script@v8
with:
script: core.setOutput('github_token', await core.getIDToken());
- name: Upload tarball
+ if: |-
+ github.repository == 'stainless-sdks/asktable-python' &&
+ !startsWith(github.ref, 'refs/heads/stl/')
env:
URL: https://pkg.stainless.com/s
AUTH: ${{ steps.github-oidc.outputs.github_token }}
@@ -79,7 +87,7 @@ jobs:
runs-on: ${{ github.repository == 'stainless-sdks/asktable-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }}
if: github.event_name == 'push' || github.event.pull_request.head.repo.fork
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Install Rye
run: |
diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml
index 188841d6..ddad4e66 100644
--- a/.github/workflows/publish-pypi.yml
+++ b/.github/workflows/publish-pypi.yml
@@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Install Rye
run: |
diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml
index 1800bc5b..54ce1661 100644
--- a/.github/workflows/release-doctor.yml
+++ b/.github/workflows/release-doctor.yml
@@ -12,7 +12,7 @@ jobs:
if: github.repository == 'DataMini/asktable-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next')
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v6
- name: Check release environment
run: |
diff --git a/.gitignore b/.gitignore
index 87797408..3824f4c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,5 @@
.prism.log
-.vscode
+.stdy.log
_dev
__pycache__
diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index f425d970..8d050425 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
{
- ".": "5.5.0"
+ ".": "5.6.0"
}
\ No newline at end of file
diff --git a/.stats.yml b/.stats.yml
index b3408abe..73a42028 100644
--- a/.stats.yml
+++ b/.stats.yml
@@ -1,4 +1,4 @@
-configured_endpoints: 107
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/datamini%2Fasktable-420512609e3f9f33f8a5b2d0086d4d3152b78935f1dc689cf4c5adf245241ba8.yml
-openapi_spec_hash: a0055c3c329900b7a66dc27f4bea86cb
+configured_endpoints: 101
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/datamini%2Fasktable-0bdad9406cb0b164ac74e5ccf8a11eb97212f97814c1c2b961af8d3b4e690665.yml
+openapi_spec_hash: 2df6d34240afb9f4e4028574fff176d7
config_hash: acdf4142177ed1932c2d82372693f811
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 00000000..5b010307
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,3 @@
+{
+ "python.analysis.importFormat": "relative",
+}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 320a4033..d3e77319 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,82 @@
# Changelog
+## 5.6.0 (2026-04-01)
+
+Full Changelog: [v5.5.0...v5.6.0](https://github.com/DataMini/asktable-python/compare/v5.5.0...v5.6.0)
+
+### Features
+
+* **api:** api update ([cbf5c8b](https://github.com/DataMini/asktable-python/commit/cbf5c8baec50e7040b3661ebac4109d3e7a0c974))
+* **api:** api update ([5a4459d](https://github.com/DataMini/asktable-python/commit/5a4459db1b4bf749a120fd8365d6755b98a6849c))
+* **api:** api update ([2ac5002](https://github.com/DataMini/asktable-python/commit/2ac50023a3cf7a9ce750e6f74a5b2b0b1ca58f05))
+* **api:** api update ([2ad193d](https://github.com/DataMini/asktable-python/commit/2ad193d7d26f51f8e2080b2c7018865eec6346b5))
+* **api:** api update ([8f315ae](https://github.com/DataMini/asktable-python/commit/8f315ae44dd5f63bb6ee94eeb8a05db4be061185))
+* **api:** api update ([e5b4763](https://github.com/DataMini/asktable-python/commit/e5b4763c4be305b5e8eb00bfc4ccce4ac21b0859))
+* **api:** api update ([d1ef26f](https://github.com/DataMini/asktable-python/commit/d1ef26f8728272e1be6c1f82012ec15bf3fda39f))
+* **api:** api update ([6d705b0](https://github.com/DataMini/asktable-python/commit/6d705b07546e449d03e5e0f70f859a49c8db14ec))
+* **api:** api update ([783819b](https://github.com/DataMini/asktable-python/commit/783819b560f7f0b9b26a3177acbd1174de6cd259))
+* **api:** api update ([5981a58](https://github.com/DataMini/asktable-python/commit/5981a58a11a85d7a1d8341a563f51137719c7850))
+* **api:** api update ([871a8c7](https://github.com/DataMini/asktable-python/commit/871a8c7c65874d07e0329f8490df11f2e8daa0fe))
+* **api:** api update ([dc5a071](https://github.com/DataMini/asktable-python/commit/dc5a07103bfc42c3f4e5acba1a61cb06b1c2a714))
+* **api:** api update ([1784353](https://github.com/DataMini/asktable-python/commit/1784353bb71b8c263b54e1e3ad95d7f25f1c5bea))
+* **api:** api update ([9260b13](https://github.com/DataMini/asktable-python/commit/9260b13ed921f7ea0f9615999375e92327e6ae98))
+* **api:** api update ([2acb60f](https://github.com/DataMini/asktable-python/commit/2acb60fc6c0bbb12713548b388f3289e85efb2fb))
+* **api:** api update ([9a4f19a](https://github.com/DataMini/asktable-python/commit/9a4f19a8ae3655969fd42c89ddce37e344fecd34))
+* **api:** api update ([b4fe8f6](https://github.com/DataMini/asktable-python/commit/b4fe8f6225f6190443c96098dcd368be97ec7e44))
+* **api:** api update ([4271a76](https://github.com/DataMini/asktable-python/commit/4271a76c22284d1b2a1bdd2a0a658afba2bcc181))
+* **api:** api update ([1176bed](https://github.com/DataMini/asktable-python/commit/1176beda5149dba11a79fc7e02988f74f6e60aae))
+* **api:** api update ([02a8fff](https://github.com/DataMini/asktable-python/commit/02a8fff21477f2c32241a09141bb4095c0060d30))
+* **api:** api update ([8add1bf](https://github.com/DataMini/asktable-python/commit/8add1bf8ed03a6e674c63e405a0cbf3f3d06b104))
+* **api:** api update ([9ec8ffd](https://github.com/DataMini/asktable-python/commit/9ec8ffda5236139d9241cd8507b7798b9312b3dd))
+* **api:** api update ([5dbbf4f](https://github.com/DataMini/asktable-python/commit/5dbbf4fd77e617963eeaca8fd57054ddb3ebad05))
+* **api:** api update ([343d8d1](https://github.com/DataMini/asktable-python/commit/343d8d1db4e22208b3d3b335f2d51de166a64a22))
+* **api:** api update ([c5b1360](https://github.com/DataMini/asktable-python/commit/c5b136000d8771c1b8a9a8b3843316d12c7ba6d9))
+* **api:** api update ([9492d82](https://github.com/DataMini/asktable-python/commit/9492d823c21d636d68e654e485ef99ab07344b47))
+* **api:** api update ([692c5e4](https://github.com/DataMini/asktable-python/commit/692c5e4a06ed72d630cae83806a89eb36316e647))
+* **api:** api update ([a62c00a](https://github.com/DataMini/asktable-python/commit/a62c00ae12cbc0efdbcb4bdf02480ddbb36d693a))
+* **api:** api update ([94adaea](https://github.com/DataMini/asktable-python/commit/94adaeae5c0a3ab51b8d4f9ef9acba27d87efc06))
+* **api:** api update ([d79fd22](https://github.com/DataMini/asktable-python/commit/d79fd224c090d22b32cc02776c5fd32ea56d2a7b))
+* **api:** api update ([d3cbda0](https://github.com/DataMini/asktable-python/commit/d3cbda00e41261e559ba2111b843b1b10f9fb772))
+* **api:** api update ([8e94324](https://github.com/DataMini/asktable-python/commit/8e94324216695bc96c20ed8b066a342d35b1f377))
+* **api:** api update ([689b9c0](https://github.com/DataMini/asktable-python/commit/689b9c0c7863e30ea3a614607c1aac22f5745b52))
+* **api:** api update ([8e2933a](https://github.com/DataMini/asktable-python/commit/8e2933a2a07175e5b2a817f9243df5952b19a9fa))
+* **api:** api update ([8fa327a](https://github.com/DataMini/asktable-python/commit/8fa327a7bb92dc4b4aeb81ff356989c13712166d))
+* **api:** api update ([7a17247](https://github.com/DataMini/asktable-python/commit/7a17247ed3d0cb95ec279c1627b51dfb2ce48572))
+* **api:** api update ([fd21534](https://github.com/DataMini/asktable-python/commit/fd2153419e2ba1424b40398fef454d01db6d4a79))
+* **client:** support file upload requests ([e9bac63](https://github.com/DataMini/asktable-python/commit/e9bac63f9b86123f21df0343e44bd9423e053bbe))
+* improve future compat with pydantic v3 ([7d6836d](https://github.com/DataMini/asktable-python/commit/7d6836dc486cd6287e806f18177b2c4afb1be2e5))
+* **types:** replace List[str] with SequenceNotStr in params ([be4a6d6](https://github.com/DataMini/asktable-python/commit/be4a6d685ff133354c4b242992de4a80f475c2d4))
+
+
+### Bug Fixes
+
+* avoid newer type syntax ([2bc84ae](https://github.com/DataMini/asktable-python/commit/2bc84ae95415f7377dcbf554faf6d057605f5c74))
+* **parsing:** ignore empty metadata ([8c48f1b](https://github.com/DataMini/asktable-python/commit/8c48f1b05dbebb99a432ab9fd7b57f8aed109d60))
+* **parsing:** parse extra field types ([40c9351](https://github.com/DataMini/asktable-python/commit/40c9351059a44df1f640f5791a126e175ebadad6))
+
+
+### Chores
+
+* **internal:** add Sequence related utils ([d34ae74](https://github.com/DataMini/asktable-python/commit/d34ae74d7dd281b8b1bc806aec5965a042550d88))
+* **internal:** change ci workflow machines ([1781814](https://github.com/DataMini/asktable-python/commit/17818149ddfaa3397db71e1a6a2500b997576a97))
+* **internal:** codegen related update ([d60ba62](https://github.com/DataMini/asktable-python/commit/d60ba627627abf7310d0464d679d332ef9ba6e65))
+* **internal:** codegen related update ([f1cea4d](https://github.com/DataMini/asktable-python/commit/f1cea4d395932285e627b2695d2b95b3cc880296))
+* **internal:** codegen related update ([4277012](https://github.com/DataMini/asktable-python/commit/42770122e37df0e03d7f5643da5aef8ab61e8a55))
+* **internal:** codegen related update ([0c6162b](https://github.com/DataMini/asktable-python/commit/0c6162b65b8b1034dd6f9c65aff9020f41fd6af9))
+* **internal:** codegen related update ([86b895b](https://github.com/DataMini/asktable-python/commit/86b895bc21b209f651ab062637ca506a34e96992))
+* **internal:** fix ruff target version ([47ae330](https://github.com/DataMini/asktable-python/commit/47ae33089939da844b9fc6f96ea1d7a56d57887e))
+* **internal:** move mypy configurations to `pyproject.toml` file ([3a81ab1](https://github.com/DataMini/asktable-python/commit/3a81ab10fc9090dd6e0c850ebf4d2bc5dd0774aa))
+* **internal:** update comment in script ([595c402](https://github.com/DataMini/asktable-python/commit/595c4022caf668b57ad4dab50ec2e8a7dc3227af))
+* **internal:** update pydantic dependency ([7768ab5](https://github.com/DataMini/asktable-python/commit/7768ab57521d3e09e550013c14b188e6aeb62fd1))
+* **internal:** update pyright exclude list ([5bf3c78](https://github.com/DataMini/asktable-python/commit/5bf3c78a9d79882f1c2e7e4245187cbb1813229d))
+* **project:** add settings file for vscode ([1641a3d](https://github.com/DataMini/asktable-python/commit/1641a3d8c4a5647a81b6292b3fd8805ab3132bb8))
+* **tests:** bump steady to v0.19.7 ([7887929](https://github.com/DataMini/asktable-python/commit/7887929ff15541ebb8120765c55f84a6c3bd39d3))
+* **tests:** bump steady to v0.20.2 ([c48a104](https://github.com/DataMini/asktable-python/commit/c48a104834af9699b011fa5891cb4c1941a5bb27))
+* **tests:** simplify `get_platform` test ([f8251b5](https://github.com/DataMini/asktable-python/commit/f8251b5a76926a6603865967d8e94071a72f5d26))
+* **types:** change optional parameter type from NotGiven to Omit ([e2ab3d3](https://github.com/DataMini/asktable-python/commit/e2ab3d3508972ea2ac5df4ab1824036070eaf732))
+* update @stainless-api/prism-cli to v5.15.0 ([5d3abad](https://github.com/DataMini/asktable-python/commit/5d3abad79640464784e731af282d02600606db98))
+* update github action ([653ff06](https://github.com/DataMini/asktable-python/commit/653ff06315c440c09e931828916b8ff38a41d6bd))
+
## 5.5.0 (2025-07-19)
Full Changelog: [v5.4.0...v5.5.0](https://github.com/DataMini/asktable-python/compare/v5.4.0...v5.5.0)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 58c9d1e9..0c4ed922 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -85,11 +85,10 @@ $ pip install ./path-to-wheel-file.whl
## Running tests
-Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests.
+Most tests require you to [set up a mock server](https://github.com/dgellow/steady) against the OpenAPI spec to run the tests.
```sh
-# you will need npm installed
-$ npx prism mock path/to/your/openapi.yml
+$ ./scripts/mock
```
```sh
diff --git a/LICENSE b/LICENSE
index fed4ca4d..881cc1fc 100644
--- a/LICENSE
+++ b/LICENSE
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
- Copyright 2025 Asktable
+ Copyright 2026 Asktable
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
diff --git a/README.md b/README.md
index cab856b6..aa944739 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
[)](https://pypi.org/project/asktable/)
-The Asktable Python library provides convenient access to the Asktable REST API from any Python 3.8+
+The Asktable Python library provides convenient access to the Asktable 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).
@@ -83,6 +83,7 @@ pip install asktable[aiohttp]
Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:
```python
+import os
import asyncio
from asktable import DefaultAioHttpClient
from asktable import AsyncAsktable
@@ -90,7 +91,7 @@ from asktable import AsyncAsktable
async def main() -> None:
async with AsyncAsktable(
- api_key="My API Key",
+ api_key=os.environ.get("ASKTABLE_API_KEY"), # This is the default and can be omitted
http_client=DefaultAioHttpClient(),
) as client:
datasource = await client.datasources.create(
@@ -190,24 +191,6 @@ response = client.sys.projects.api_keys.create_token(
print(response.chat_role)
```
-## File uploads
-
-Request parameters that correspond to file uploads can be passed as `bytes`, or 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 asktable import Asktable
-
-client = Asktable()
-
-client.datasources.add_file(
- datasource_id="datasource_id",
- 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 `asktable.APIConnectionError` is raised.
@@ -469,7 +452,7 @@ print(asktable.__version__)
## Requirements
-Python 3.8 or higher.
+Python 3.9 or higher.
## Contributing
diff --git a/api.md b/api.md
index 4d02c1ed..011dc2e3 100644
--- a/api.md
+++ b/api.md
@@ -6,22 +6,18 @@ from asktable.types import Policy
# Sys
-Types:
-
-```python
-from asktable.types import SyUpdateConfigResponse
-```
-
-Methods:
-
-- client.sys.update_config(\*\*params) -> SyUpdateConfigResponse
-
## Projects
Types:
```python
-from asktable.types.sys import APIKey, ModelGroup, Project, ProjectModelGroupsResponse
+from asktable.types.sys import (
+ APIKey,
+ Project,
+ ProjectExportResponse,
+ ProjectImportResponse,
+ ProjectModelGroupsResponse,
+)
```
Methods:
@@ -31,8 +27,8 @@ Methods:
- client.sys.projects.update(project_id, \*\*params) -> Project
- client.sys.projects.list(\*\*params) -> SyncPage[Project]
- client.sys.projects.delete(project_id) -> object
-- client.sys.projects.export(project_id) -> object
-- client.sys.projects.import\_(\*\*params) -> object
+- client.sys.projects.export(project_id) -> ProjectExportResponse
+- client.sys.projects.import\_(\*\*params) -> ProjectImportResponse
- client.sys.projects.model_groups() -> ProjectModelGroupsResponse
### APIKeys
@@ -40,7 +36,11 @@ Methods:
Types:
```python
-from asktable.types.sys.projects import APIKeyCreateResponse, APIKeyListResponse
+from asktable.types.sys.projects import (
+ APIKeyCreateResponse,
+ APIKeyListResponse,
+ APIKeyCreateTokenResponse,
+)
```
Methods:
@@ -48,7 +48,7 @@ Methods:
- client.sys.projects.api_keys.create(project_id, \*\*params) -> APIKeyCreateResponse
- client.sys.projects.api_keys.list(project_id) -> APIKeyListResponse
- client.sys.projects.api_keys.delete(key_id, \*, project_id) -> None
-- client.sys.projects.api_keys.create_token(project_id, \*\*params) -> object
+- client.sys.projects.api_keys.create_token(project_id, \*\*params) -> APIKeyCreateTokenResponse
# Securetunnels
@@ -72,7 +72,7 @@ Methods:
Types:
```python
-from asktable.types import Role, RoleGetPolicesResponse
+from asktable.types import Role, RoleGetPolicesResponse, RoleGetVariablesResponse
```
Methods:
@@ -83,7 +83,7 @@ Methods:
- client.roles.list(\*\*params) -> SyncPage[Role]
- client.roles.delete(role_id) -> object
- client.roles.get_polices(role_id) -> RoleGetPolicesResponse
-- client.roles.get_variables(role_id, \*\*params) -> object
+- client.roles.get_variables(role_id, \*\*params) -> RoleGetVariablesResponse
# Policies
@@ -100,14 +100,21 @@ Methods:
Types:
```python
-from asktable.types import AIMessage, Chat, ToolMessage, UserMessage, ChatRetrieveResponse
+from asktable.types import (
+ AIMessage,
+ ToolMessage,
+ UserMessage,
+ ChatCreateResponse,
+ ChatRetrieveResponse,
+ ChatListResponse,
+)
```
Methods:
-- client.chats.create(\*\*params) -> Chat
+- client.chats.create(\*\*params) -> ChatCreateResponse
- client.chats.retrieve(chat_id) -> ChatRetrieveResponse
-- client.chats.list(\*\*params) -> SyncPage[Chat]
+- client.chats.list(\*\*params) -> SyncPage[ChatListResponse]
- client.chats.delete(chat_id) -> None
## Messages
@@ -161,9 +168,15 @@ Methods:
## UploadParams
+Types:
+
+```python
+from asktable.types.datasources import UploadParamCreateResponse
+```
+
Methods:
-- client.datasources.upload_params.create(\*\*params) -> object
+- client.datasources.upload_params.create(\*\*params) -> UploadParamCreateResponse
## Indexes
@@ -178,7 +191,7 @@ Methods:
Types:
```python
-from asktable.types import Chatbot
+from asktable.types import Chatbot, BotInviteResponse
```
Methods:
@@ -188,19 +201,19 @@ Methods:
- client.bots.update(bot_id, \*\*params) -> Chatbot
- client.bots.list(\*\*params) -> SyncPage[Chatbot]
- client.bots.delete(bot_id) -> object
-- client.bots.invite(bot_id, \*\*params) -> object
+- client.bots.invite(bot_id, \*\*params) -> BotInviteResponse
# Auth
Types:
```python
-from asktable.types import AuthMeResponse
+from asktable.types import AuthCreateTokenResponse, AuthMeResponse
```
Methods:
-- client.auth.create_token(\*\*params) -> object
+- client.auth.create_token(\*\*params) -> AuthCreateTokenResponse
- client.auth.me() -> AuthMeResponse
# Answers
@@ -229,12 +242,6 @@ Methods:
- client.sqls.create(\*\*params) -> QueryResponse
- client.sqls.list(\*\*params) -> SyncPage[QueryResponse]
-# Caches
-
-Methods:
-
-- client.caches.delete(cache_id) -> None
-
# Integration
Types:
@@ -283,21 +290,6 @@ Methods:
- client.preferences.update(\*\*params) -> PreferenceUpdateResponse
- client.preferences.delete() -> object
-# Trainings
-
-Types:
-
-```python
-from asktable.types import TrainingCreateResponse, TrainingUpdateResponse, TrainingListResponse
-```
-
-Methods:
-
-- client.trainings.create(\*\*params) -> TrainingCreateResponse
-- client.trainings.update(id, \*\*params) -> TrainingUpdateResponse
-- client.trainings.list(\*\*params) -> SyncPage[TrainingListResponse]
-- client.trainings.delete(id, \*\*params) -> object
-
# Project
Types:
diff --git a/mypy.ini b/mypy.ini
deleted file mode 100644
index b0156385..00000000
--- a/mypy.ini
+++ /dev/null
@@ -1,50 +0,0 @@
-[mypy]
-pretty = True
-show_error_codes = True
-
-# Exclude _files.py because mypy isn't smart enough to apply
-# the correct type narrowing and as this is an internal module
-# it's fine to just use Pyright.
-#
-# We also exclude our `tests` as mypy doesn't always infer
-# types correctly and Pyright will still catch any type errors.
-exclude = ^(src/asktable/_files\.py|_dev/.*\.py|tests/.*)$
-
-strict_equality = True
-implicit_reexport = True
-check_untyped_defs = True
-no_implicit_optional = True
-
-warn_return_any = True
-warn_unreachable = True
-warn_unused_configs = True
-
-# Turn these options off as it could cause conflicts
-# with the Pyright options.
-warn_unused_ignores = False
-warn_redundant_casts = False
-
-disallow_any_generics = True
-disallow_untyped_defs = True
-disallow_untyped_calls = True
-disallow_subclassing_any = True
-disallow_incomplete_defs = True
-disallow_untyped_decorators = True
-cache_fine_grained = True
-
-# By default, mypy reports an error if you assign a value to the result
-# of a function call that doesn't return anything. We do this in our test
-# cases:
-# ```
-# result = ...
-# assert result is None
-# ```
-# Changing this codegen to make mypy happy would increase complexity
-# and would not be worth it.
-disable_error_code = func-returns-value,overload-cannot-match
-
-# https://github.com/python/mypy/issues/12162
-[mypy.overrides]
-module = "black.files.*"
-ignore_errors = true
-ignore_missing_imports = true
diff --git a/pyproject.toml b/pyproject.toml
index 371a4680..5211d694 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,30 +1,32 @@
[project]
name = "asktable"
-version = "5.5.0"
+version = "5.6.0"
description = "The official Python library for the Asktable API"
dynamic = ["readme"]
license = "Apache-2.0"
authors = [
{ name = "Asktable", email = "hi@datamini.ai" },
]
+
dependencies = [
- "httpx>=0.23.0, <1",
- "pydantic>=1.9.0, <3",
- "typing-extensions>=4.10, <5",
- "anyio>=3.5.0, <5",
- "distro>=1.7.0, <2",
- "sniffio",
+ "httpx>=0.23.0, <1",
+ "pydantic>=1.9.0, <3",
+ "typing-extensions>=4.14, <5",
+ "anyio>=3.5.0, <5",
+ "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",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
"Operating System :: OS Independent",
"Operating System :: POSIX",
"Operating System :: MacOS",
@@ -39,14 +41,14 @@ Homepage = "https://github.com/DataMini/asktable-python"
Repository = "https://github.com/DataMini/asktable-python"
[project.optional-dependencies]
-aiohttp = ["aiohttp", "httpx_aiohttp>=0.1.8"]
+aiohttp = ["aiohttp", "httpx_aiohttp>=0.1.9"]
[tool.rye]
managed = true
# version pins are in requirements-dev.lock
dev-dependencies = [
"pyright==1.1.399",
- "mypy",
+ "mypy==1.17",
"respx",
"pytest",
"pytest-asyncio",
@@ -56,7 +58,6 @@ dev-dependencies = [
"dirty-equals>=0.6.0",
"importlib-metadata>=6.7.0",
"rich>=13.7.1",
- "nest_asyncio==1.6.0",
"pytest-xdist>=3.6.1",
]
@@ -68,7 +69,7 @@ format = { chain = [
# run formatting again to fix any inconsistencies when imports are stripped
"format:ruff",
]}
-"format:docs" = "python scripts/utils/ruffen-docs.py README.md api.md"
+"format:docs" = "bash -c 'python scripts/utils/ruffen-docs.py README.md $(find . -type f -name api.md)'"
"format:ruff" = "ruff format"
"lint" = { chain = [
@@ -142,12 +143,13 @@ 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",
".venv",
".nox",
+ ".git",
]
reportImplicitOverride = true
@@ -156,10 +158,62 @@ reportOverlappingOverload = false
reportImportCycles = false
reportPrivateUsage = false
+[tool.mypy]
+pretty = true
+show_error_codes = true
+
+# Exclude _files.py because mypy isn't smart enough to apply
+# the correct type narrowing and as this is an internal module
+# it's fine to just use Pyright.
+#
+# We also exclude our `tests` as mypy doesn't always infer
+# types correctly and Pyright will still catch any type errors.
+exclude = ['src/asktable/_files.py', '_dev/.*.py', 'tests/.*']
+
+strict_equality = true
+implicit_reexport = true
+check_untyped_defs = true
+no_implicit_optional = true
+
+warn_return_any = true
+warn_unreachable = true
+warn_unused_configs = true
+
+# Turn these options off as it could cause conflicts
+# with the Pyright options.
+warn_unused_ignores = false
+warn_redundant_casts = false
+
+disallow_any_generics = true
+disallow_untyped_defs = true
+disallow_untyped_calls = true
+disallow_subclassing_any = true
+disallow_incomplete_defs = true
+disallow_untyped_decorators = true
+cache_fine_grained = true
+
+# By default, mypy reports an error if you assign a value to the result
+# of a function call that doesn't return anything. We do this in our test
+# cases:
+# ```
+# result = ...
+# assert result is None
+# ```
+# Changing this codegen to make mypy happy would increase complexity
+# and would not be worth it.
+disable_error_code = "func-returns-value,overload-cannot-match"
+
+# https://github.com/python/mypy/issues/12162
+[[tool.mypy.overrides]]
+module = "black.files.*"
+ignore_errors = true
+ignore_missing_imports = true
+
+
[tool.ruff]
line-length = 120
output-format = "grouped"
-target-version = "py37"
+target-version = "py38"
[tool.ruff.format]
docstring-code-format = true
@@ -172,6 +226,8 @@ select = [
"B",
# remove unused imports
"F401",
+ # check for missing future annotations
+ "FA102",
# bare except statements
"E722",
# unused arguments
@@ -194,6 +250,8 @@ unfixable = [
"T203",
]
+extend-safe-fixes = ["FA102"]
+
[tool.ruff.lint.flake8-tidy-imports.banned-api]
"functools.lru_cache".msg = "This function does not retain type information for the wrapped function's arguments; The `lru_cache` function from `_utils` should be used instead"
diff --git a/requirements-dev.lock b/requirements-dev.lock
index 9701ab71..55d68a97 100644
--- a/requirements-dev.lock
+++ b/requirements-dev.lock
@@ -12,40 +12,45 @@
-e file:.
aiohappyeyeballs==2.6.1
# via aiohttp
-aiohttp==3.12.8
+aiohttp==3.13.3
# via asktable
# via httpx-aiohttp
-aiosignal==1.3.2
+aiosignal==1.4.0
# via aiohttp
-annotated-types==0.6.0
+annotated-types==0.7.0
# via pydantic
-anyio==4.4.0
+anyio==4.12.1
# via asktable
# via httpx
-argcomplete==3.1.2
+argcomplete==3.6.3
# via nox
async-timeout==5.0.1
# via aiohttp
-attrs==25.3.0
+attrs==25.4.0
# via aiohttp
-certifi==2023.7.22
+ # via nox
+backports-asyncio-runner==1.2.0
+ # via pytest-asyncio
+certifi==2026.1.4
# via httpcore
# via httpx
-colorlog==6.7.0
+colorlog==6.10.1
+ # via nox
+dependency-groups==1.3.1
# via nox
-dirty-equals==0.6.0
-distlib==0.3.7
+dirty-equals==0.11
+distlib==0.4.0
# via virtualenv
-distro==1.8.0
+distro==1.9.0
# via asktable
-exceptiongroup==1.2.2
+exceptiongroup==1.3.1
# via anyio
# via pytest
-execnet==2.1.1
+execnet==2.1.2
# via pytest-xdist
-filelock==3.12.4
+filelock==3.19.1
# via virtualenv
-frozenlist==1.6.2
+frozenlist==1.8.0
# via aiohttp
# via aiosignal
h11==0.16.0
@@ -56,80 +61,89 @@ httpx==0.28.1
# via asktable
# via httpx-aiohttp
# via respx
-httpx-aiohttp==0.1.8
+httpx-aiohttp==0.1.12
# via asktable
-idna==3.4
+humanize==4.13.0
+ # via nox
+idna==3.11
# via anyio
# via httpx
# via yarl
-importlib-metadata==7.0.0
-iniconfig==2.0.0
+importlib-metadata==8.7.1
+iniconfig==2.1.0
# via pytest
markdown-it-py==3.0.0
# via rich
mdurl==0.1.2
# via markdown-it-py
-multidict==6.4.4
+multidict==6.7.0
# via aiohttp
# via yarl
-mypy==1.14.1
-mypy-extensions==1.0.0
+mypy==1.17.0
+mypy-extensions==1.1.0
# via mypy
-nest-asyncio==1.6.0
-nodeenv==1.8.0
+nodeenv==1.10.0
# via pyright
-nox==2023.4.22
-packaging==23.2
+nox==2025.11.12
+packaging==25.0
+ # via dependency-groups
# via nox
# via pytest
-platformdirs==3.11.0
+pathspec==1.0.3
+ # via mypy
+platformdirs==4.4.0
# via virtualenv
-pluggy==1.5.0
+pluggy==1.6.0
# via pytest
-propcache==0.3.1
+propcache==0.4.1
# via aiohttp
# via yarl
-pydantic==2.10.3
+pydantic==2.12.5
# via asktable
-pydantic-core==2.27.1
+pydantic-core==2.41.5
# via pydantic
-pygments==2.18.0
+pygments==2.19.2
+ # via pytest
# via rich
pyright==1.1.399
-pytest==8.3.3
+pytest==8.4.2
# via pytest-asyncio
# via pytest-xdist
-pytest-asyncio==0.24.0
-pytest-xdist==3.7.0
-python-dateutil==2.8.2
+pytest-asyncio==1.2.0
+pytest-xdist==3.8.0
+python-dateutil==2.9.0.post0
# via time-machine
-pytz==2023.3.post1
- # via dirty-equals
respx==0.22.0
-rich==13.7.1
-ruff==0.9.4
-setuptools==68.2.2
- # via nodeenv
-six==1.16.0
+rich==14.2.0
+ruff==0.14.13
+six==1.17.0
# via python-dateutil
-sniffio==1.3.0
- # via anyio
+sniffio==1.3.1
# via asktable
-time-machine==2.9.0
-tomli==2.0.2
+time-machine==2.19.0
+tomli==2.4.0
+ # via dependency-groups
# via mypy
+ # via nox
# via pytest
-typing-extensions==4.12.2
+typing-extensions==4.15.0
+ # via aiosignal
# via anyio
# via asktable
+ # via exceptiongroup
# via multidict
# via mypy
# via pydantic
# via pydantic-core
# via pyright
-virtualenv==20.24.5
+ # via pytest-asyncio
+ # via typing-inspection
+ # via virtualenv
+typing-inspection==0.4.2
+ # via pydantic
+virtualenv==20.36.1
# via nox
-yarl==1.20.0
+yarl==1.22.0
# via aiohttp
-zipp==3.17.0
+zipp==3.23.0
# via importlib-metadata
diff --git a/requirements.lock b/requirements.lock
index ac6e943f..7a238212 100644
--- a/requirements.lock
+++ b/requirements.lock
@@ -12,28 +12,28 @@
-e file:.
aiohappyeyeballs==2.6.1
# via aiohttp
-aiohttp==3.12.8
+aiohttp==3.13.3
# via asktable
# via httpx-aiohttp
-aiosignal==1.3.2
+aiosignal==1.4.0
# via aiohttp
-annotated-types==0.6.0
+annotated-types==0.7.0
# via pydantic
-anyio==4.4.0
+anyio==4.12.1
# via asktable
# via httpx
async-timeout==5.0.1
# via aiohttp
-attrs==25.3.0
+attrs==25.4.0
# via aiohttp
-certifi==2023.7.22
+certifi==2026.1.4
# via httpcore
# via httpx
-distro==1.8.0
+distro==1.9.0
# via asktable
-exceptiongroup==1.2.2
+exceptiongroup==1.3.1
# via anyio
-frozenlist==1.6.2
+frozenlist==1.8.0
# via aiohttp
# via aiosignal
h11==0.16.0
@@ -43,30 +43,34 @@ httpcore==1.0.9
httpx==0.28.1
# via asktable
# via httpx-aiohttp
-httpx-aiohttp==0.1.8
+httpx-aiohttp==0.1.12
# via asktable
-idna==3.4
+idna==3.11
# via anyio
# via httpx
# via yarl
-multidict==6.4.4
+multidict==6.7.0
# via aiohttp
# via yarl
-propcache==0.3.1
+propcache==0.4.1
# via aiohttp
# via yarl
-pydantic==2.10.3
+pydantic==2.12.5
# via asktable
-pydantic-core==2.27.1
+pydantic-core==2.41.5
# via pydantic
-sniffio==1.3.0
- # via anyio
+sniffio==1.3.1
# via asktable
-typing-extensions==4.12.2
+typing-extensions==4.15.0
+ # via aiosignal
# via anyio
# via asktable
+ # via exceptiongroup
# via multidict
# via pydantic
# via pydantic-core
-yarl==1.20.0
+ # via typing-inspection
+typing-inspection==0.4.2
+ # via pydantic
+yarl==1.22.0
# via aiohttp
diff --git a/scripts/bootstrap b/scripts/bootstrap
index e84fe62c..b430fee3 100755
--- a/scripts/bootstrap
+++ b/scripts/bootstrap
@@ -4,10 +4,18 @@ set -e
cd "$(dirname "$0")/.."
-if ! command -v rye >/dev/null 2>&1 && [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ]; then
+if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "$SKIP_BREW" != "1" ] && [ -t 0 ]; then
brew bundle check >/dev/null 2>&1 || {
- echo "==> Installing Homebrew dependencies…"
- brew bundle
+ echo -n "==> Install Homebrew dependencies? (y/N): "
+ read -r response
+ case "$response" in
+ [yY][eE][sS]|[yY])
+ brew bundle
+ ;;
+ *)
+ ;;
+ esac
+ echo
}
fi
diff --git a/scripts/lint b/scripts/lint
index c49721d9..6d495229 100755
--- a/scripts/lint
+++ b/scripts/lint
@@ -4,8 +4,13 @@ set -e
cd "$(dirname "$0")/.."
-echo "==> Running lints"
-rye run lint
+if [ "$1" = "--fix" ]; then
+ echo "==> Running lints with --fix"
+ rye run fix:ruff
+else
+ echo "==> Running lints"
+ rye run lint
+fi
echo "==> Making sure it imports"
rye run python -c 'import asktable'
diff --git a/scripts/mock b/scripts/mock
index d2814ae6..7c58865f 100755
--- a/scripts/mock
+++ b/scripts/mock
@@ -19,23 +19,34 @@ fi
echo "==> Starting mock server with URL ${URL}"
-# Run prism mock on the given spec
+# Run steady mock on the given spec
if [ "$1" == "--daemon" ]; then
- npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" &> .prism.log &
+ # Pre-install the package so the download doesn't eat into the startup timeout
+ npm exec --package=@stdy/cli@0.20.2 -- steady --version
- # Wait for server to come online
+ npm exec --package=@stdy/cli@0.20.2 -- steady --host 127.0.0.1 -p 4010 --validator-query-array-format=repeat --validator-form-array-format=repeat --validator-query-object-format=brackets --validator-form-object-format=brackets "$URL" &> .stdy.log &
+
+ # Wait for server to come online via health endpoint (max 30s)
echo -n "Waiting for server"
- while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do
+ attempts=0
+ while ! curl --silent --fail "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1; do
+ if ! kill -0 $! 2>/dev/null; then
+ echo
+ cat .stdy.log
+ exit 1
+ fi
+ attempts=$((attempts + 1))
+ if [ "$attempts" -ge 300 ]; then
+ echo
+ echo "Timed out waiting for Steady server to start"
+ cat .stdy.log
+ exit 1
+ fi
echo -n "."
sleep 0.1
done
- if grep -q "✖ fatal" ".prism.log"; then
- cat .prism.log
- exit 1
- fi
-
echo
else
- npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL"
+ npm exec --package=@stdy/cli@0.20.2 -- steady --host 127.0.0.1 -p 4010 --validator-query-array-format=repeat --validator-form-array-format=repeat --validator-query-object-format=brackets --validator-form-object-format=brackets "$URL"
fi
diff --git a/scripts/test b/scripts/test
index 2b878456..87cdeac2 100755
--- a/scripts/test
+++ b/scripts/test
@@ -9,8 +9,8 @@ GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
-function prism_is_running() {
- curl --silent "http://localhost:4010" >/dev/null 2>&1
+function steady_is_running() {
+ curl --silent "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1
}
kill_server_on_port() {
@@ -25,7 +25,7 @@ function is_overriding_api_base_url() {
[ -n "$TEST_API_BASE_URL" ]
}
-if ! is_overriding_api_base_url && ! prism_is_running ; then
+if ! is_overriding_api_base_url && ! steady_is_running ; then
# When we exit this script, make sure to kill the background mock server process
trap 'kill_server_on_port 4010' EXIT
@@ -36,19 +36,19 @@ fi
if is_overriding_api_base_url ; then
echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}"
echo
-elif ! prism_is_running ; then
- echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server"
+elif ! steady_is_running ; then
+ echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Steady server"
echo -e "running against your OpenAPI spec."
echo
echo -e "To run the server, pass in the path or url of your OpenAPI"
- echo -e "spec to the prism command:"
+ echo -e "spec to the steady command:"
echo
- echo -e " \$ ${YELLOW}npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock path/to/your.openapi.yml${NC}"
+ echo -e " \$ ${YELLOW}npm exec --package=@stdy/cli@0.20.2 -- steady path/to/your.openapi.yml --host 127.0.0.1 -p 4010 --validator-query-array-format=repeat --validator-form-array-format=repeat --validator-query-object-format=brackets --validator-form-object-format=brackets${NC}"
echo
exit 1
else
- echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}"
+ echo -e "${GREEN}✔ Mock steady server is running with your OpenAPI spec${NC}"
echo
fi
diff --git a/src/asktable/__init__.py b/src/asktable/__init__.py
index 03765db6..38566e5b 100644
--- a/src/asktable/__init__.py
+++ b/src/asktable/__init__.py
@@ -3,7 +3,7 @@
import typing as _t
from . import types
-from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes
+from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes, omit, not_given
from ._utils import file_from_path
from ._client import (
Client,
@@ -48,7 +48,9 @@
"ProxiesTypes",
"NotGiven",
"NOT_GIVEN",
+ "not_given",
"Omit",
+ "omit",
"AsktableError",
"APIError",
"APIStatusError",
diff --git a/src/asktable/_base_client.py b/src/asktable/_base_client.py
index 4678a3ee..d9e44713 100644
--- a/src/asktable/_base_client.py
+++ b/src/asktable/_base_client.py
@@ -9,6 +9,7 @@
import inspect
import logging
import platform
+import warnings
import email.utils
from types import TracebackType
from random import random
@@ -42,7 +43,6 @@
from ._qs import Querystring
from ._files import to_httpx_files, async_to_httpx_files
from ._types import (
- NOT_GIVEN,
Body,
Omit,
Query,
@@ -52,14 +52,17 @@
ResponseT,
AnyMapping,
PostParser,
+ BinaryTypes,
RequestFiles,
HttpxSendArgs,
RequestOptions,
+ AsyncBinaryTypes,
HttpxRequestFiles,
ModelBuilderProtocol,
+ not_given,
)
from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping
-from ._compat import PYDANTIC_V2, model_copy, model_dump
+from ._compat import PYDANTIC_V1, model_copy, model_dump
from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type
from ._response import (
APIResponse,
@@ -83,6 +86,7 @@
APIConnectionError,
APIResponseValidationError,
)
+from ._utils._json import openapi_dumps
log: logging.Logger = logging.getLogger(__name__)
@@ -145,9 +149,9 @@ def __init__(
def __init__(
self,
*,
- url: URL | NotGiven = NOT_GIVEN,
- json: Body | NotGiven = NOT_GIVEN,
- params: Query | NotGiven = NOT_GIVEN,
+ url: URL | NotGiven = not_given,
+ json: Body | NotGiven = not_given,
+ params: Query | NotGiven = not_given,
) -> None:
self.url = url
self.json = json
@@ -232,7 +236,7 @@ def _set_private_attributes(
model: Type[_T],
options: FinalRequestOptions,
) -> None:
- if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None:
+ if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None:
self.__pydantic_private__ = {}
self._model = model
@@ -320,7 +324,7 @@ def _set_private_attributes(
client: AsyncAPIClient,
options: FinalRequestOptions,
) -> None:
- if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None:
+ if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None:
self.__pydantic_private__ = {}
self._model = model
@@ -477,8 +481,19 @@ def _build_request(
retries_taken: int = 0,
) -> httpx.Request:
if log.isEnabledFor(logging.DEBUG):
- log.debug("Request options: %s", model_dump(options, exclude_unset=True))
-
+ log.debug(
+ "Request options: %s",
+ model_dump(
+ options,
+ exclude_unset=True,
+ # Pydantic v1 can't dump every type we support in content, so we exclude it for now.
+ exclude={
+ "content",
+ }
+ if PYDANTIC_V1
+ else {},
+ ),
+ )
kwargs: dict[str, Any] = {}
json_data = options.json_data
@@ -532,7 +547,18 @@ def _build_request(
is_body_allowed = options.method.lower() != "get"
if is_body_allowed:
- kwargs["json"] = json_data if is_given(json_data) else None
+ if options.content is not None and json_data is not None:
+ raise TypeError("Passing both `content` and `json_data` is not supported")
+ if options.content is not None and files is not None:
+ raise TypeError("Passing both `content` and `files` is not supported")
+ if options.content is not None:
+ kwargs["content"] = options.content
+ elif isinstance(json_data, bytes):
+ kwargs["content"] = json_data
+ elif not files:
+ # Don't set content when JSON is sent as multipart/form-data,
+ # since httpx's content param overrides other body arguments
+ kwargs["content"] = openapi_dumps(json_data) if is_given(json_data) and json_data is not None else None
kwargs["files"] = files
else:
headers.pop("Content-Type", None)
@@ -592,7 +618,7 @@ def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalReques
# we internally support defining a temporary header to override the
# default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response`
# see _response.py for implementation details
- override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, NOT_GIVEN)
+ override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, not_given)
if is_given(override_cast_to):
options.headers = headers
return cast(Type[ResponseT], override_cast_to)
@@ -822,7 +848,7 @@ def __init__(
version: str,
base_url: str | URL,
max_retries: int = DEFAULT_MAX_RETRIES,
- timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | Timeout | None | NotGiven = not_given,
http_client: httpx.Client | None = None,
custom_headers: Mapping[str, str] | None = None,
custom_query: Mapping[str, object] | None = None,
@@ -1191,6 +1217,7 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: Literal[False] = False,
@@ -1203,6 +1230,7 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: Literal[True],
@@ -1216,6 +1244,7 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: bool,
@@ -1228,13 +1257,25 @@ def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
files: RequestFiles | None = None,
stream: bool = False,
stream_cls: type[_StreamT] | None = None,
) -> ResponseT | _StreamT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="post", url=path, json_data=body, files=to_httpx_files(files), **options
+ method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
)
return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
@@ -1244,9 +1285,24 @@ def patch(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
+ files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
- opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options)
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ opts = FinalRequestOptions.construct(
+ method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
+ )
return self.request(cast_to, opts)
def put(
@@ -1255,11 +1311,23 @@ def put(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="put", url=path, json_data=body, files=to_httpx_files(files), **options
+ method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
)
return self.request(cast_to, opts)
@@ -1269,9 +1337,19 @@ def delete(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: BinaryTypes | None = None,
options: RequestOptions = {},
) -> ResponseT:
- opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
return self.request(cast_to, opts)
def get_api_list(
@@ -1353,7 +1431,7 @@ def __init__(
base_url: str | URL,
_strict_response_validation: bool,
max_retries: int = DEFAULT_MAX_RETRIES,
- timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | Timeout | None | NotGiven = not_given,
http_client: httpx.AsyncClient | None = None,
custom_headers: Mapping[str, str] | None = None,
custom_query: Mapping[str, object] | None = None,
@@ -1711,6 +1789,7 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: Literal[False] = False,
@@ -1723,6 +1802,7 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: Literal[True],
@@ -1736,6 +1816,7 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: bool,
@@ -1748,13 +1829,25 @@ async def post(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
stream: bool = False,
stream_cls: type[_AsyncStreamT] | None = None,
) -> ResponseT | _AsyncStreamT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="post", url=path, json_data=body, files=await async_to_httpx_files(files), **options
+ method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
)
return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
@@ -1764,9 +1857,29 @@ async def patch(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
+ files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
- opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options)
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ opts = FinalRequestOptions.construct(
+ method="patch",
+ url=path,
+ json_data=body,
+ content=content,
+ files=await async_to_httpx_files(files),
+ **options,
+ )
return await self.request(cast_to, opts)
async def put(
@@ -1775,11 +1888,23 @@ async def put(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
files: RequestFiles | None = None,
options: RequestOptions = {},
) -> ResponseT:
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if files is not None and content is not None:
+ raise TypeError("Passing both `files` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
opts = FinalRequestOptions.construct(
- method="put", url=path, json_data=body, files=await async_to_httpx_files(files), **options
+ method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
)
return await self.request(cast_to, opts)
@@ -1789,9 +1914,19 @@ async def delete(
*,
cast_to: Type[ResponseT],
body: Body | None = None,
+ content: AsyncBinaryTypes | None = None,
options: RequestOptions = {},
) -> ResponseT:
- opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options)
+ if body is not None and content is not None:
+ raise TypeError("Passing both `body` and `content` is not supported")
+ if isinstance(body, bytes):
+ warnings.warn(
+ "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
+ "Please pass raw bytes via the `content` parameter instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
return await self.request(cast_to, opts)
def get_api_list(
@@ -1815,8 +1950,8 @@ def make_request_options(
extra_query: Query | None = None,
extra_body: Body | None = None,
idempotency_key: str | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
- post_parser: PostParser | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ post_parser: PostParser | NotGiven = not_given,
) -> RequestOptions:
"""Create a dict of type RequestOptions without keys of NotGiven values."""
options: RequestOptions = {}
diff --git a/src/asktable/_client.py b/src/asktable/_client.py
index 5c06a135..554f1c03 100644
--- a/src/asktable/_client.py
+++ b/src/asktable/_client.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import os
-from typing import Any, Union, Mapping
+from typing import TYPE_CHECKING, Any, Mapping
from typing_extensions import Self, override
import httpx
@@ -11,35 +11,17 @@
from . import _exceptions
from ._qs import Querystring
from ._types import (
- NOT_GIVEN,
Omit,
Timeout,
NotGiven,
Transport,
ProxiesTypes,
RequestOptions,
+ not_given,
)
from ._utils import is_given, get_async_library
+from ._compat import cached_property
from ._version import __version__
-from .resources import (
- auth,
- bots,
- sqls,
- files,
- roles,
- caches,
- polish,
- scores,
- answers,
- project,
- policies,
- trainings,
- dataframes,
- integration,
- preferences,
- securetunnels,
- business_glossary,
-)
from ._streaming import Stream as Stream, AsyncStream as AsyncStream
from ._exceptions import AsktableError, APIStatusError
from ._base_client import (
@@ -47,11 +29,50 @@
SyncAPIClient,
AsyncAPIClient,
)
-from .resources.ats import ats
-from .resources.sys import sys
-from .resources.user import user
-from .resources.chats import chats
-from .resources.datasources import datasources
+
+if TYPE_CHECKING:
+ from .resources import (
+ ats,
+ sys,
+ auth,
+ bots,
+ sqls,
+ user,
+ chats,
+ files,
+ roles,
+ polish,
+ scores,
+ answers,
+ project,
+ policies,
+ dataframes,
+ datasources,
+ integration,
+ preferences,
+ securetunnels,
+ business_glossary,
+ )
+ from .resources.auth import AuthResource, AsyncAuthResource
+ from .resources.bots import BotsResource, AsyncBotsResource
+ from .resources.sqls import SqlsResource, AsyncSqlsResource
+ from .resources.files import FilesResource, AsyncFilesResource
+ from .resources.roles import RolesResource, AsyncRolesResource
+ from .resources.polish import PolishResource, AsyncPolishResource
+ from .resources.scores import ScoresResource, AsyncScoresResource
+ from .resources.answers import AnswersResource, AsyncAnswersResource
+ from .resources.ats.ats import ATSResource, AsyncATSResource
+ from .resources.project import ProjectResource, AsyncProjectResource
+ from .resources.sys.sys import SysResource, AsyncSysResource
+ from .resources.policies import PoliciesResource, AsyncPoliciesResource
+ from .resources.user.user import UserResource, AsyncUserResource
+ from .resources.dataframes import DataframesResource, AsyncDataframesResource
+ from .resources.chats.chats import ChatsResource, AsyncChatsResource
+ from .resources.integration import IntegrationResource, AsyncIntegrationResource
+ from .resources.preferences import PreferencesResource, AsyncPreferencesResource
+ from .resources.securetunnels import SecuretunnelsResource, AsyncSecuretunnelsResource
+ from .resources.business_glossary import BusinessGlossaryResource, AsyncBusinessGlossaryResource
+ from .resources.datasources.datasources import DatasourcesResource, AsyncDatasourcesResource
__all__ = [
"Timeout",
@@ -66,31 +87,6 @@
class Asktable(SyncAPIClient):
- sys: sys.SysResource
- securetunnels: securetunnels.SecuretunnelsResource
- roles: roles.RolesResource
- policies: policies.PoliciesResource
- chats: chats.ChatsResource
- datasources: datasources.DatasourcesResource
- bots: bots.BotsResource
- auth: auth.AuthResource
- answers: answers.AnswersResource
- sqls: sqls.SqlsResource
- caches: caches.CachesResource
- integration: integration.IntegrationResource
- business_glossary: business_glossary.BusinessGlossaryResource
- preferences: preferences.PreferencesResource
- trainings: trainings.TrainingsResource
- project: project.ProjectResource
- scores: scores.ScoresResource
- files: files.FilesResource
- dataframes: dataframes.DataframesResource
- polish: polish.PolishResource
- user: user.UserResource
- ats: ats.ATSResource
- with_raw_response: AsktableWithRawResponse
- with_streaming_response: AsktableWithStreamedResponse
-
# client options
api_key: str
@@ -99,7 +95,7 @@ def __init__(
*,
api_key: str | None = None,
base_url: str | httpx.URL | None = None,
- timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
+ timeout: float | Timeout | None | NotGiven = not_given,
max_retries: int = DEFAULT_MAX_RETRIES,
default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
@@ -145,30 +141,150 @@ def __init__(
_strict_response_validation=_strict_response_validation,
)
- self.sys = sys.SysResource(self)
- self.securetunnels = securetunnels.SecuretunnelsResource(self)
- self.roles = roles.RolesResource(self)
- self.policies = policies.PoliciesResource(self)
- self.chats = chats.ChatsResource(self)
- self.datasources = datasources.DatasourcesResource(self)
- self.bots = bots.BotsResource(self)
- self.auth = auth.AuthResource(self)
- self.answers = answers.AnswersResource(self)
- self.sqls = sqls.SqlsResource(self)
- self.caches = caches.CachesResource(self)
- self.integration = integration.IntegrationResource(self)
- self.business_glossary = business_glossary.BusinessGlossaryResource(self)
- self.preferences = preferences.PreferencesResource(self)
- self.trainings = trainings.TrainingsResource(self)
- self.project = project.ProjectResource(self)
- self.scores = scores.ScoresResource(self)
- self.files = files.FilesResource(self)
- self.dataframes = dataframes.DataframesResource(self)
- self.polish = polish.PolishResource(self)
- self.user = user.UserResource(self)
- self.ats = ats.ATSResource(self)
- self.with_raw_response = AsktableWithRawResponse(self)
- self.with_streaming_response = AsktableWithStreamedResponse(self)
+ @cached_property
+ def sys(self) -> SysResource:
+ from .resources.sys import SysResource
+
+ return SysResource(self)
+
+ @cached_property
+ def securetunnels(self) -> SecuretunnelsResource:
+ """安全隧道"""
+ from .resources.securetunnels import SecuretunnelsResource
+
+ return SecuretunnelsResource(self)
+
+ @cached_property
+ def roles(self) -> RolesResource:
+ """角色管理"""
+ from .resources.roles import RolesResource
+
+ return RolesResource(self)
+
+ @cached_property
+ def policies(self) -> PoliciesResource:
+ """策略管理"""
+ from .resources.policies import PoliciesResource
+
+ return PoliciesResource(self)
+
+ @cached_property
+ def chats(self) -> ChatsResource:
+ """聊天管理"""
+ from .resources.chats import ChatsResource
+
+ return ChatsResource(self)
+
+ @cached_property
+ def datasources(self) -> DatasourcesResource:
+ """数据源管理"""
+ from .resources.datasources import DatasourcesResource
+
+ return DatasourcesResource(self)
+
+ @cached_property
+ def bots(self) -> BotsResource:
+ """AI 数据助手"""
+ from .resources.bots import BotsResource
+
+ return BotsResource(self)
+
+ @cached_property
+ def auth(self) -> AuthResource:
+ """AskTable 系统认证管理"""
+ from .resources.auth import AuthResource
+
+ return AuthResource(self)
+
+ @cached_property
+ def answers(self) -> AnswersResource:
+ """单轮对话"""
+ from .resources.answers import AnswersResource
+
+ return AnswersResource(self)
+
+ @cached_property
+ def sqls(self) -> SqlsResource:
+ """单轮对话"""
+ from .resources.sqls import SqlsResource
+
+ return SqlsResource(self)
+
+ @cached_property
+ def integration(self) -> IntegrationResource:
+ """与第三方平台集成"""
+ from .resources.integration import IntegrationResource
+
+ return IntegrationResource(self)
+
+ @cached_property
+ def business_glossary(self) -> BusinessGlossaryResource:
+ """业务术语管理"""
+ from .resources.business_glossary import BusinessGlossaryResource
+
+ return BusinessGlossaryResource(self)
+
+ @cached_property
+ def preferences(self) -> PreferencesResource:
+ """偏好设置"""
+ from .resources.preferences import PreferencesResource
+
+ return PreferencesResource(self)
+
+ @cached_property
+ def project(self) -> ProjectResource:
+ """我的项目"""
+ from .resources.project import ProjectResource
+
+ return ProjectResource(self)
+
+ @cached_property
+ def scores(self) -> ScoresResource:
+ """评分"""
+ from .resources.scores import ScoresResource
+
+ return ScoresResource(self)
+
+ @cached_property
+ def files(self) -> FilesResource:
+ """数据源管理"""
+ from .resources.files import FilesResource
+
+ return FilesResource(self)
+
+ @cached_property
+ def dataframes(self) -> DataframesResource:
+ from .resources.dataframes import DataframesResource
+
+ return DataframesResource(self)
+
+ @cached_property
+ def polish(self) -> PolishResource:
+ """润色"""
+ from .resources.polish import PolishResource
+
+ return PolishResource(self)
+
+ @cached_property
+ def user(self) -> UserResource:
+ from .resources.user import UserResource
+
+ return UserResource(self)
+
+ @cached_property
+ def ats(self) -> ATSResource:
+ """测试系统"""
+ from .resources.ats import ATSResource
+
+ return ATSResource(self)
+
+ @cached_property
+ def with_raw_response(self) -> AsktableWithRawResponse:
+ return AsktableWithRawResponse(self)
+
+ @cached_property
+ def with_streaming_response(self) -> AsktableWithStreamedResponse:
+ return AsktableWithStreamedResponse(self)
@property
@override
@@ -195,9 +311,9 @@ def copy(
*,
api_key: str | None = None,
base_url: str | httpx.URL | None = None,
- timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | Timeout | None | NotGiven = not_given,
http_client: httpx.Client | None = None,
- max_retries: int | NotGiven = NOT_GIVEN,
+ max_retries: int | NotGiven = not_given,
default_headers: Mapping[str, str] | None = None,
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
@@ -276,31 +392,6 @@ def _make_status_error(
class AsyncAsktable(AsyncAPIClient):
- sys: sys.AsyncSysResource
- securetunnels: securetunnels.AsyncSecuretunnelsResource
- roles: roles.AsyncRolesResource
- policies: policies.AsyncPoliciesResource
- chats: chats.AsyncChatsResource
- datasources: datasources.AsyncDatasourcesResource
- bots: bots.AsyncBotsResource
- auth: auth.AsyncAuthResource
- answers: answers.AsyncAnswersResource
- sqls: sqls.AsyncSqlsResource
- caches: caches.AsyncCachesResource
- integration: integration.AsyncIntegrationResource
- business_glossary: business_glossary.AsyncBusinessGlossaryResource
- preferences: preferences.AsyncPreferencesResource
- trainings: trainings.AsyncTrainingsResource
- project: project.AsyncProjectResource
- scores: scores.AsyncScoresResource
- files: files.AsyncFilesResource
- dataframes: dataframes.AsyncDataframesResource
- polish: polish.AsyncPolishResource
- user: user.AsyncUserResource
- ats: ats.AsyncATSResource
- with_raw_response: AsyncAsktableWithRawResponse
- with_streaming_response: AsyncAsktableWithStreamedResponse
-
# client options
api_key: str
@@ -309,7 +400,7 @@ def __init__(
*,
api_key: str | None = None,
base_url: str | httpx.URL | None = None,
- timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
+ timeout: float | Timeout | None | NotGiven = not_given,
max_retries: int = DEFAULT_MAX_RETRIES,
default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
@@ -355,30 +446,150 @@ def __init__(
_strict_response_validation=_strict_response_validation,
)
- self.sys = sys.AsyncSysResource(self)
- self.securetunnels = securetunnels.AsyncSecuretunnelsResource(self)
- self.roles = roles.AsyncRolesResource(self)
- self.policies = policies.AsyncPoliciesResource(self)
- self.chats = chats.AsyncChatsResource(self)
- self.datasources = datasources.AsyncDatasourcesResource(self)
- self.bots = bots.AsyncBotsResource(self)
- self.auth = auth.AsyncAuthResource(self)
- self.answers = answers.AsyncAnswersResource(self)
- self.sqls = sqls.AsyncSqlsResource(self)
- self.caches = caches.AsyncCachesResource(self)
- self.integration = integration.AsyncIntegrationResource(self)
- self.business_glossary = business_glossary.AsyncBusinessGlossaryResource(self)
- self.preferences = preferences.AsyncPreferencesResource(self)
- self.trainings = trainings.AsyncTrainingsResource(self)
- self.project = project.AsyncProjectResource(self)
- self.scores = scores.AsyncScoresResource(self)
- self.files = files.AsyncFilesResource(self)
- self.dataframes = dataframes.AsyncDataframesResource(self)
- self.polish = polish.AsyncPolishResource(self)
- self.user = user.AsyncUserResource(self)
- self.ats = ats.AsyncATSResource(self)
- self.with_raw_response = AsyncAsktableWithRawResponse(self)
- self.with_streaming_response = AsyncAsktableWithStreamedResponse(self)
+ @cached_property
+ def sys(self) -> AsyncSysResource:
+ from .resources.sys import AsyncSysResource
+
+ return AsyncSysResource(self)
+
+ @cached_property
+ def securetunnels(self) -> AsyncSecuretunnelsResource:
+ """安全隧道"""
+ from .resources.securetunnels import AsyncSecuretunnelsResource
+
+ return AsyncSecuretunnelsResource(self)
+
+ @cached_property
+ def roles(self) -> AsyncRolesResource:
+ """角色管理"""
+ from .resources.roles import AsyncRolesResource
+
+ return AsyncRolesResource(self)
+
+ @cached_property
+ def policies(self) -> AsyncPoliciesResource:
+ """策略管理"""
+ from .resources.policies import AsyncPoliciesResource
+
+ return AsyncPoliciesResource(self)
+
+ @cached_property
+ def chats(self) -> AsyncChatsResource:
+ """聊天管理"""
+ from .resources.chats import AsyncChatsResource
+
+ return AsyncChatsResource(self)
+
+ @cached_property
+ def datasources(self) -> AsyncDatasourcesResource:
+ """数据源管理"""
+ from .resources.datasources import AsyncDatasourcesResource
+
+ return AsyncDatasourcesResource(self)
+
+ @cached_property
+ def bots(self) -> AsyncBotsResource:
+ """AI 数据助手"""
+ from .resources.bots import AsyncBotsResource
+
+ return AsyncBotsResource(self)
+
+ @cached_property
+ def auth(self) -> AsyncAuthResource:
+ """AskTable 系统认证管理"""
+ from .resources.auth import AsyncAuthResource
+
+ return AsyncAuthResource(self)
+
+ @cached_property
+ def answers(self) -> AsyncAnswersResource:
+ """单轮对话"""
+ from .resources.answers import AsyncAnswersResource
+
+ return AsyncAnswersResource(self)
+
+ @cached_property
+ def sqls(self) -> AsyncSqlsResource:
+ """单轮对话"""
+ from .resources.sqls import AsyncSqlsResource
+
+ return AsyncSqlsResource(self)
+
+ @cached_property
+ def integration(self) -> AsyncIntegrationResource:
+ """与第三方平台集成"""
+ from .resources.integration import AsyncIntegrationResource
+
+ return AsyncIntegrationResource(self)
+
+ @cached_property
+ def business_glossary(self) -> AsyncBusinessGlossaryResource:
+ """业务术语管理"""
+ from .resources.business_glossary import AsyncBusinessGlossaryResource
+
+ return AsyncBusinessGlossaryResource(self)
+
+ @cached_property
+ def preferences(self) -> AsyncPreferencesResource:
+ """偏好设置"""
+ from .resources.preferences import AsyncPreferencesResource
+
+ return AsyncPreferencesResource(self)
+
+ @cached_property
+ def project(self) -> AsyncProjectResource:
+ """我的项目"""
+ from .resources.project import AsyncProjectResource
+
+ return AsyncProjectResource(self)
+
+ @cached_property
+ def scores(self) -> AsyncScoresResource:
+ """评分"""
+ from .resources.scores import AsyncScoresResource
+
+ return AsyncScoresResource(self)
+
+ @cached_property
+ def files(self) -> AsyncFilesResource:
+ """数据源管理"""
+ from .resources.files import AsyncFilesResource
+
+ return AsyncFilesResource(self)
+
+ @cached_property
+ def dataframes(self) -> AsyncDataframesResource:
+ from .resources.dataframes import AsyncDataframesResource
+
+ return AsyncDataframesResource(self)
+
+ @cached_property
+ def polish(self) -> AsyncPolishResource:
+ """润色"""
+ from .resources.polish import AsyncPolishResource
+
+ return AsyncPolishResource(self)
+
+ @cached_property
+ def user(self) -> AsyncUserResource:
+ from .resources.user import AsyncUserResource
+
+ return AsyncUserResource(self)
+
+ @cached_property
+ def ats(self) -> AsyncATSResource:
+ """测试系统"""
+ from .resources.ats import AsyncATSResource
+
+ return AsyncATSResource(self)
+
+ @cached_property
+ def with_raw_response(self) -> AsyncAsktableWithRawResponse:
+ return AsyncAsktableWithRawResponse(self)
+
+ @cached_property
+ def with_streaming_response(self) -> AsyncAsktableWithStreamedResponse:
+ return AsyncAsktableWithStreamedResponse(self)
@property
@override
@@ -405,9 +616,9 @@ def copy(
*,
api_key: str | None = None,
base_url: str | httpx.URL | None = None,
- timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | Timeout | None | NotGiven = not_given,
http_client: httpx.AsyncClient | None = None,
- max_retries: int | NotGiven = NOT_GIVEN,
+ max_retries: int | NotGiven = not_given,
default_headers: Mapping[str, str] | None = None,
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
@@ -486,113 +697,579 @@ def _make_status_error(
class AsktableWithRawResponse:
+ _client: Asktable
+
def __init__(self, client: Asktable) -> None:
- self.sys = sys.SysResourceWithRawResponse(client.sys)
- self.securetunnels = securetunnels.SecuretunnelsResourceWithRawResponse(client.securetunnels)
- self.roles = roles.RolesResourceWithRawResponse(client.roles)
- self.policies = policies.PoliciesResourceWithRawResponse(client.policies)
- self.chats = chats.ChatsResourceWithRawResponse(client.chats)
- self.datasources = datasources.DatasourcesResourceWithRawResponse(client.datasources)
- self.bots = bots.BotsResourceWithRawResponse(client.bots)
- self.auth = auth.AuthResourceWithRawResponse(client.auth)
- self.answers = answers.AnswersResourceWithRawResponse(client.answers)
- self.sqls = sqls.SqlsResourceWithRawResponse(client.sqls)
- self.caches = caches.CachesResourceWithRawResponse(client.caches)
- self.integration = integration.IntegrationResourceWithRawResponse(client.integration)
- self.business_glossary = business_glossary.BusinessGlossaryResourceWithRawResponse(client.business_glossary)
- self.preferences = preferences.PreferencesResourceWithRawResponse(client.preferences)
- self.trainings = trainings.TrainingsResourceWithRawResponse(client.trainings)
- self.project = project.ProjectResourceWithRawResponse(client.project)
- self.scores = scores.ScoresResourceWithRawResponse(client.scores)
- self.files = files.FilesResourceWithRawResponse(client.files)
- self.dataframes = dataframes.DataframesResourceWithRawResponse(client.dataframes)
- self.polish = polish.PolishResourceWithRawResponse(client.polish)
- self.user = user.UserResourceWithRawResponse(client.user)
- self.ats = ats.ATSResourceWithRawResponse(client.ats)
+ self._client = client
+
+ @cached_property
+ def sys(self) -> sys.SysResourceWithRawResponse:
+ from .resources.sys import SysResourceWithRawResponse
+
+ return SysResourceWithRawResponse(self._client.sys)
+
+ @cached_property
+ def securetunnels(self) -> securetunnels.SecuretunnelsResourceWithRawResponse:
+ """安全隧道"""
+ from .resources.securetunnels import SecuretunnelsResourceWithRawResponse
+
+ return SecuretunnelsResourceWithRawResponse(self._client.securetunnels)
+
+ @cached_property
+ def roles(self) -> roles.RolesResourceWithRawResponse:
+ """角色管理"""
+ from .resources.roles import RolesResourceWithRawResponse
+
+ return RolesResourceWithRawResponse(self._client.roles)
+
+ @cached_property
+ def policies(self) -> policies.PoliciesResourceWithRawResponse:
+ """策略管理"""
+ from .resources.policies import PoliciesResourceWithRawResponse
+
+ return PoliciesResourceWithRawResponse(self._client.policies)
+
+ @cached_property
+ def chats(self) -> chats.ChatsResourceWithRawResponse:
+ """聊天管理"""
+ from .resources.chats import ChatsResourceWithRawResponse
+
+ return ChatsResourceWithRawResponse(self._client.chats)
+
+ @cached_property
+ def datasources(self) -> datasources.DatasourcesResourceWithRawResponse:
+ """数据源管理"""
+ from .resources.datasources import DatasourcesResourceWithRawResponse
+
+ return DatasourcesResourceWithRawResponse(self._client.datasources)
+
+ @cached_property
+ def bots(self) -> bots.BotsResourceWithRawResponse:
+ """AI 数据助手"""
+ from .resources.bots import BotsResourceWithRawResponse
+
+ return BotsResourceWithRawResponse(self._client.bots)
+
+ @cached_property
+ def auth(self) -> auth.AuthResourceWithRawResponse:
+ """AskTable 系统认证管理"""
+ from .resources.auth import AuthResourceWithRawResponse
+
+ return AuthResourceWithRawResponse(self._client.auth)
+
+ @cached_property
+ def answers(self) -> answers.AnswersResourceWithRawResponse:
+ """单轮对话"""
+ from .resources.answers import AnswersResourceWithRawResponse
+
+ return AnswersResourceWithRawResponse(self._client.answers)
+
+ @cached_property
+ def sqls(self) -> sqls.SqlsResourceWithRawResponse:
+ """单轮对话"""
+ from .resources.sqls import SqlsResourceWithRawResponse
+
+ return SqlsResourceWithRawResponse(self._client.sqls)
+
+ @cached_property
+ def integration(self) -> integration.IntegrationResourceWithRawResponse:
+ """与第三方平台集成"""
+ from .resources.integration import IntegrationResourceWithRawResponse
+
+ return IntegrationResourceWithRawResponse(self._client.integration)
+
+ @cached_property
+ def business_glossary(self) -> business_glossary.BusinessGlossaryResourceWithRawResponse:
+ """业务术语管理"""
+ from .resources.business_glossary import BusinessGlossaryResourceWithRawResponse
+
+ return BusinessGlossaryResourceWithRawResponse(self._client.business_glossary)
+
+ @cached_property
+ def preferences(self) -> preferences.PreferencesResourceWithRawResponse:
+ """偏好设置"""
+ from .resources.preferences import PreferencesResourceWithRawResponse
+
+ return PreferencesResourceWithRawResponse(self._client.preferences)
+
+ @cached_property
+ def project(self) -> project.ProjectResourceWithRawResponse:
+ """我的项目"""
+ from .resources.project import ProjectResourceWithRawResponse
+
+ return ProjectResourceWithRawResponse(self._client.project)
+
+ @cached_property
+ def scores(self) -> scores.ScoresResourceWithRawResponse:
+ """评分"""
+ from .resources.scores import ScoresResourceWithRawResponse
+
+ return ScoresResourceWithRawResponse(self._client.scores)
+
+ @cached_property
+ def files(self) -> files.FilesResourceWithRawResponse:
+ """数据源管理"""
+ from .resources.files import FilesResourceWithRawResponse
+
+ return FilesResourceWithRawResponse(self._client.files)
+
+ @cached_property
+ def dataframes(self) -> dataframes.DataframesResourceWithRawResponse:
+ from .resources.dataframes import DataframesResourceWithRawResponse
+
+ return DataframesResourceWithRawResponse(self._client.dataframes)
+
+ @cached_property
+ def polish(self) -> polish.PolishResourceWithRawResponse:
+ """润色"""
+ from .resources.polish import PolishResourceWithRawResponse
+
+ return PolishResourceWithRawResponse(self._client.polish)
+
+ @cached_property
+ def user(self) -> user.UserResourceWithRawResponse:
+ from .resources.user import UserResourceWithRawResponse
+
+ return UserResourceWithRawResponse(self._client.user)
+
+ @cached_property
+ def ats(self) -> ats.ATSResourceWithRawResponse:
+ """测试系统"""
+ from .resources.ats import ATSResourceWithRawResponse
+
+ return ATSResourceWithRawResponse(self._client.ats)
class AsyncAsktableWithRawResponse:
+ _client: AsyncAsktable
+
def __init__(self, client: AsyncAsktable) -> None:
- self.sys = sys.AsyncSysResourceWithRawResponse(client.sys)
- self.securetunnels = securetunnels.AsyncSecuretunnelsResourceWithRawResponse(client.securetunnels)
- self.roles = roles.AsyncRolesResourceWithRawResponse(client.roles)
- self.policies = policies.AsyncPoliciesResourceWithRawResponse(client.policies)
- self.chats = chats.AsyncChatsResourceWithRawResponse(client.chats)
- self.datasources = datasources.AsyncDatasourcesResourceWithRawResponse(client.datasources)
- self.bots = bots.AsyncBotsResourceWithRawResponse(client.bots)
- self.auth = auth.AsyncAuthResourceWithRawResponse(client.auth)
- self.answers = answers.AsyncAnswersResourceWithRawResponse(client.answers)
- self.sqls = sqls.AsyncSqlsResourceWithRawResponse(client.sqls)
- self.caches = caches.AsyncCachesResourceWithRawResponse(client.caches)
- self.integration = integration.AsyncIntegrationResourceWithRawResponse(client.integration)
- self.business_glossary = business_glossary.AsyncBusinessGlossaryResourceWithRawResponse(
- client.business_glossary
- )
- self.preferences = preferences.AsyncPreferencesResourceWithRawResponse(client.preferences)
- self.trainings = trainings.AsyncTrainingsResourceWithRawResponse(client.trainings)
- self.project = project.AsyncProjectResourceWithRawResponse(client.project)
- self.scores = scores.AsyncScoresResourceWithRawResponse(client.scores)
- self.files = files.AsyncFilesResourceWithRawResponse(client.files)
- self.dataframes = dataframes.AsyncDataframesResourceWithRawResponse(client.dataframes)
- self.polish = polish.AsyncPolishResourceWithRawResponse(client.polish)
- self.user = user.AsyncUserResourceWithRawResponse(client.user)
- self.ats = ats.AsyncATSResourceWithRawResponse(client.ats)
+ self._client = client
+
+ @cached_property
+ def sys(self) -> sys.AsyncSysResourceWithRawResponse:
+ from .resources.sys import AsyncSysResourceWithRawResponse
+
+ return AsyncSysResourceWithRawResponse(self._client.sys)
+
+ @cached_property
+ def securetunnels(self) -> securetunnels.AsyncSecuretunnelsResourceWithRawResponse:
+ """安全隧道"""
+ from .resources.securetunnels import AsyncSecuretunnelsResourceWithRawResponse
+
+ return AsyncSecuretunnelsResourceWithRawResponse(self._client.securetunnels)
+
+ @cached_property
+ def roles(self) -> roles.AsyncRolesResourceWithRawResponse:
+ """角色管理"""
+ from .resources.roles import AsyncRolesResourceWithRawResponse
+
+ return AsyncRolesResourceWithRawResponse(self._client.roles)
+
+ @cached_property
+ def policies(self) -> policies.AsyncPoliciesResourceWithRawResponse:
+ """策略管理"""
+ from .resources.policies import AsyncPoliciesResourceWithRawResponse
+
+ return AsyncPoliciesResourceWithRawResponse(self._client.policies)
+
+ @cached_property
+ def chats(self) -> chats.AsyncChatsResourceWithRawResponse:
+ """聊天管理"""
+ from .resources.chats import AsyncChatsResourceWithRawResponse
+
+ return AsyncChatsResourceWithRawResponse(self._client.chats)
+
+ @cached_property
+ def datasources(self) -> datasources.AsyncDatasourcesResourceWithRawResponse:
+ """数据源管理"""
+ from .resources.datasources import AsyncDatasourcesResourceWithRawResponse
+
+ return AsyncDatasourcesResourceWithRawResponse(self._client.datasources)
+
+ @cached_property
+ def bots(self) -> bots.AsyncBotsResourceWithRawResponse:
+ """AI 数据助手"""
+ from .resources.bots import AsyncBotsResourceWithRawResponse
+
+ return AsyncBotsResourceWithRawResponse(self._client.bots)
+
+ @cached_property
+ def auth(self) -> auth.AsyncAuthResourceWithRawResponse:
+ """AskTable 系统认证管理"""
+ from .resources.auth import AsyncAuthResourceWithRawResponse
+
+ return AsyncAuthResourceWithRawResponse(self._client.auth)
+
+ @cached_property
+ def answers(self) -> answers.AsyncAnswersResourceWithRawResponse:
+ """单轮对话"""
+ from .resources.answers import AsyncAnswersResourceWithRawResponse
+
+ return AsyncAnswersResourceWithRawResponse(self._client.answers)
+
+ @cached_property
+ def sqls(self) -> sqls.AsyncSqlsResourceWithRawResponse:
+ """单轮对话"""
+ from .resources.sqls import AsyncSqlsResourceWithRawResponse
+
+ return AsyncSqlsResourceWithRawResponse(self._client.sqls)
+
+ @cached_property
+ def integration(self) -> integration.AsyncIntegrationResourceWithRawResponse:
+ """与第三方平台集成"""
+ from .resources.integration import AsyncIntegrationResourceWithRawResponse
+
+ return AsyncIntegrationResourceWithRawResponse(self._client.integration)
+
+ @cached_property
+ def business_glossary(self) -> business_glossary.AsyncBusinessGlossaryResourceWithRawResponse:
+ """业务术语管理"""
+ from .resources.business_glossary import AsyncBusinessGlossaryResourceWithRawResponse
+
+ return AsyncBusinessGlossaryResourceWithRawResponse(self._client.business_glossary)
+
+ @cached_property
+ def preferences(self) -> preferences.AsyncPreferencesResourceWithRawResponse:
+ """偏好设置"""
+ from .resources.preferences import AsyncPreferencesResourceWithRawResponse
+
+ return AsyncPreferencesResourceWithRawResponse(self._client.preferences)
+
+ @cached_property
+ def project(self) -> project.AsyncProjectResourceWithRawResponse:
+ """我的项目"""
+ from .resources.project import AsyncProjectResourceWithRawResponse
+
+ return AsyncProjectResourceWithRawResponse(self._client.project)
+
+ @cached_property
+ def scores(self) -> scores.AsyncScoresResourceWithRawResponse:
+ """评分"""
+ from .resources.scores import AsyncScoresResourceWithRawResponse
+
+ return AsyncScoresResourceWithRawResponse(self._client.scores)
+
+ @cached_property
+ def files(self) -> files.AsyncFilesResourceWithRawResponse:
+ """数据源管理"""
+ from .resources.files import AsyncFilesResourceWithRawResponse
+
+ return AsyncFilesResourceWithRawResponse(self._client.files)
+
+ @cached_property
+ def dataframes(self) -> dataframes.AsyncDataframesResourceWithRawResponse:
+ from .resources.dataframes import AsyncDataframesResourceWithRawResponse
+
+ return AsyncDataframesResourceWithRawResponse(self._client.dataframes)
+
+ @cached_property
+ def polish(self) -> polish.AsyncPolishResourceWithRawResponse:
+ """润色"""
+ from .resources.polish import AsyncPolishResourceWithRawResponse
+
+ return AsyncPolishResourceWithRawResponse(self._client.polish)
+
+ @cached_property
+ def user(self) -> user.AsyncUserResourceWithRawResponse:
+ from .resources.user import AsyncUserResourceWithRawResponse
+
+ return AsyncUserResourceWithRawResponse(self._client.user)
+
+ @cached_property
+ def ats(self) -> ats.AsyncATSResourceWithRawResponse:
+ """测试系统"""
+ from .resources.ats import AsyncATSResourceWithRawResponse
+
+ return AsyncATSResourceWithRawResponse(self._client.ats)
class AsktableWithStreamedResponse:
+ _client: Asktable
+
def __init__(self, client: Asktable) -> None:
- self.sys = sys.SysResourceWithStreamingResponse(client.sys)
- self.securetunnels = securetunnels.SecuretunnelsResourceWithStreamingResponse(client.securetunnels)
- self.roles = roles.RolesResourceWithStreamingResponse(client.roles)
- self.policies = policies.PoliciesResourceWithStreamingResponse(client.policies)
- self.chats = chats.ChatsResourceWithStreamingResponse(client.chats)
- self.datasources = datasources.DatasourcesResourceWithStreamingResponse(client.datasources)
- self.bots = bots.BotsResourceWithStreamingResponse(client.bots)
- self.auth = auth.AuthResourceWithStreamingResponse(client.auth)
- self.answers = answers.AnswersResourceWithStreamingResponse(client.answers)
- self.sqls = sqls.SqlsResourceWithStreamingResponse(client.sqls)
- self.caches = caches.CachesResourceWithStreamingResponse(client.caches)
- self.integration = integration.IntegrationResourceWithStreamingResponse(client.integration)
- self.business_glossary = business_glossary.BusinessGlossaryResourceWithStreamingResponse(
- client.business_glossary
- )
- self.preferences = preferences.PreferencesResourceWithStreamingResponse(client.preferences)
- self.trainings = trainings.TrainingsResourceWithStreamingResponse(client.trainings)
- self.project = project.ProjectResourceWithStreamingResponse(client.project)
- self.scores = scores.ScoresResourceWithStreamingResponse(client.scores)
- self.files = files.FilesResourceWithStreamingResponse(client.files)
- self.dataframes = dataframes.DataframesResourceWithStreamingResponse(client.dataframes)
- self.polish = polish.PolishResourceWithStreamingResponse(client.polish)
- self.user = user.UserResourceWithStreamingResponse(client.user)
- self.ats = ats.ATSResourceWithStreamingResponse(client.ats)
+ self._client = client
+
+ @cached_property
+ def sys(self) -> sys.SysResourceWithStreamingResponse:
+ from .resources.sys import SysResourceWithStreamingResponse
+
+ return SysResourceWithStreamingResponse(self._client.sys)
+
+ @cached_property
+ def securetunnels(self) -> securetunnels.SecuretunnelsResourceWithStreamingResponse:
+ """安全隧道"""
+ from .resources.securetunnels import SecuretunnelsResourceWithStreamingResponse
+
+ return SecuretunnelsResourceWithStreamingResponse(self._client.securetunnels)
+
+ @cached_property
+ def roles(self) -> roles.RolesResourceWithStreamingResponse:
+ """角色管理"""
+ from .resources.roles import RolesResourceWithStreamingResponse
+
+ return RolesResourceWithStreamingResponse(self._client.roles)
+
+ @cached_property
+ def policies(self) -> policies.PoliciesResourceWithStreamingResponse:
+ """策略管理"""
+ from .resources.policies import PoliciesResourceWithStreamingResponse
+
+ return PoliciesResourceWithStreamingResponse(self._client.policies)
+
+ @cached_property
+ def chats(self) -> chats.ChatsResourceWithStreamingResponse:
+ """聊天管理"""
+ from .resources.chats import ChatsResourceWithStreamingResponse
+
+ return ChatsResourceWithStreamingResponse(self._client.chats)
+
+ @cached_property
+ def datasources(self) -> datasources.DatasourcesResourceWithStreamingResponse:
+ """数据源管理"""
+ from .resources.datasources import DatasourcesResourceWithStreamingResponse
+
+ return DatasourcesResourceWithStreamingResponse(self._client.datasources)
+
+ @cached_property
+ def bots(self) -> bots.BotsResourceWithStreamingResponse:
+ """AI 数据助手"""
+ from .resources.bots import BotsResourceWithStreamingResponse
+
+ return BotsResourceWithStreamingResponse(self._client.bots)
+
+ @cached_property
+ def auth(self) -> auth.AuthResourceWithStreamingResponse:
+ """AskTable 系统认证管理"""
+ from .resources.auth import AuthResourceWithStreamingResponse
+
+ return AuthResourceWithStreamingResponse(self._client.auth)
+
+ @cached_property
+ def answers(self) -> answers.AnswersResourceWithStreamingResponse:
+ """单轮对话"""
+ from .resources.answers import AnswersResourceWithStreamingResponse
+
+ return AnswersResourceWithStreamingResponse(self._client.answers)
+
+ @cached_property
+ def sqls(self) -> sqls.SqlsResourceWithStreamingResponse:
+ """单轮对话"""
+ from .resources.sqls import SqlsResourceWithStreamingResponse
+
+ return SqlsResourceWithStreamingResponse(self._client.sqls)
+
+ @cached_property
+ def integration(self) -> integration.IntegrationResourceWithStreamingResponse:
+ """与第三方平台集成"""
+ from .resources.integration import IntegrationResourceWithStreamingResponse
+
+ return IntegrationResourceWithStreamingResponse(self._client.integration)
+
+ @cached_property
+ def business_glossary(self) -> business_glossary.BusinessGlossaryResourceWithStreamingResponse:
+ """业务术语管理"""
+ from .resources.business_glossary import BusinessGlossaryResourceWithStreamingResponse
+
+ return BusinessGlossaryResourceWithStreamingResponse(self._client.business_glossary)
+
+ @cached_property
+ def preferences(self) -> preferences.PreferencesResourceWithStreamingResponse:
+ """偏好设置"""
+ from .resources.preferences import PreferencesResourceWithStreamingResponse
+
+ return PreferencesResourceWithStreamingResponse(self._client.preferences)
+
+ @cached_property
+ def project(self) -> project.ProjectResourceWithStreamingResponse:
+ """我的项目"""
+ from .resources.project import ProjectResourceWithStreamingResponse
+
+ return ProjectResourceWithStreamingResponse(self._client.project)
+
+ @cached_property
+ def scores(self) -> scores.ScoresResourceWithStreamingResponse:
+ """评分"""
+ from .resources.scores import ScoresResourceWithStreamingResponse
+
+ return ScoresResourceWithStreamingResponse(self._client.scores)
+
+ @cached_property
+ def files(self) -> files.FilesResourceWithStreamingResponse:
+ """数据源管理"""
+ from .resources.files import FilesResourceWithStreamingResponse
+
+ return FilesResourceWithStreamingResponse(self._client.files)
+
+ @cached_property
+ def dataframes(self) -> dataframes.DataframesResourceWithStreamingResponse:
+ from .resources.dataframes import DataframesResourceWithStreamingResponse
+
+ return DataframesResourceWithStreamingResponse(self._client.dataframes)
+
+ @cached_property
+ def polish(self) -> polish.PolishResourceWithStreamingResponse:
+ """润色"""
+ from .resources.polish import PolishResourceWithStreamingResponse
+
+ return PolishResourceWithStreamingResponse(self._client.polish)
+
+ @cached_property
+ def user(self) -> user.UserResourceWithStreamingResponse:
+ from .resources.user import UserResourceWithStreamingResponse
+
+ return UserResourceWithStreamingResponse(self._client.user)
+
+ @cached_property
+ def ats(self) -> ats.ATSResourceWithStreamingResponse:
+ """测试系统"""
+ from .resources.ats import ATSResourceWithStreamingResponse
+
+ return ATSResourceWithStreamingResponse(self._client.ats)
class AsyncAsktableWithStreamedResponse:
+ _client: AsyncAsktable
+
def __init__(self, client: AsyncAsktable) -> None:
- self.sys = sys.AsyncSysResourceWithStreamingResponse(client.sys)
- self.securetunnels = securetunnels.AsyncSecuretunnelsResourceWithStreamingResponse(client.securetunnels)
- self.roles = roles.AsyncRolesResourceWithStreamingResponse(client.roles)
- self.policies = policies.AsyncPoliciesResourceWithStreamingResponse(client.policies)
- self.chats = chats.AsyncChatsResourceWithStreamingResponse(client.chats)
- self.datasources = datasources.AsyncDatasourcesResourceWithStreamingResponse(client.datasources)
- self.bots = bots.AsyncBotsResourceWithStreamingResponse(client.bots)
- self.auth = auth.AsyncAuthResourceWithStreamingResponse(client.auth)
- self.answers = answers.AsyncAnswersResourceWithStreamingResponse(client.answers)
- self.sqls = sqls.AsyncSqlsResourceWithStreamingResponse(client.sqls)
- self.caches = caches.AsyncCachesResourceWithStreamingResponse(client.caches)
- self.integration = integration.AsyncIntegrationResourceWithStreamingResponse(client.integration)
- self.business_glossary = business_glossary.AsyncBusinessGlossaryResourceWithStreamingResponse(
- client.business_glossary
- )
- self.preferences = preferences.AsyncPreferencesResourceWithStreamingResponse(client.preferences)
- self.trainings = trainings.AsyncTrainingsResourceWithStreamingResponse(client.trainings)
- self.project = project.AsyncProjectResourceWithStreamingResponse(client.project)
- self.scores = scores.AsyncScoresResourceWithStreamingResponse(client.scores)
- self.files = files.AsyncFilesResourceWithStreamingResponse(client.files)
- self.dataframes = dataframes.AsyncDataframesResourceWithStreamingResponse(client.dataframes)
- self.polish = polish.AsyncPolishResourceWithStreamingResponse(client.polish)
- self.user = user.AsyncUserResourceWithStreamingResponse(client.user)
- self.ats = ats.AsyncATSResourceWithStreamingResponse(client.ats)
+ self._client = client
+
+ @cached_property
+ def sys(self) -> sys.AsyncSysResourceWithStreamingResponse:
+ from .resources.sys import AsyncSysResourceWithStreamingResponse
+
+ return AsyncSysResourceWithStreamingResponse(self._client.sys)
+
+ @cached_property
+ def securetunnels(self) -> securetunnels.AsyncSecuretunnelsResourceWithStreamingResponse:
+ """安全隧道"""
+ from .resources.securetunnels import AsyncSecuretunnelsResourceWithStreamingResponse
+
+ return AsyncSecuretunnelsResourceWithStreamingResponse(self._client.securetunnels)
+
+ @cached_property
+ def roles(self) -> roles.AsyncRolesResourceWithStreamingResponse:
+ """角色管理"""
+ from .resources.roles import AsyncRolesResourceWithStreamingResponse
+
+ return AsyncRolesResourceWithStreamingResponse(self._client.roles)
+
+ @cached_property
+ def policies(self) -> policies.AsyncPoliciesResourceWithStreamingResponse:
+ """策略管理"""
+ from .resources.policies import AsyncPoliciesResourceWithStreamingResponse
+
+ return AsyncPoliciesResourceWithStreamingResponse(self._client.policies)
+
+ @cached_property
+ def chats(self) -> chats.AsyncChatsResourceWithStreamingResponse:
+ """聊天管理"""
+ from .resources.chats import AsyncChatsResourceWithStreamingResponse
+
+ return AsyncChatsResourceWithStreamingResponse(self._client.chats)
+
+ @cached_property
+ def datasources(self) -> datasources.AsyncDatasourcesResourceWithStreamingResponse:
+ """数据源管理"""
+ from .resources.datasources import AsyncDatasourcesResourceWithStreamingResponse
+
+ return AsyncDatasourcesResourceWithStreamingResponse(self._client.datasources)
+
+ @cached_property
+ def bots(self) -> bots.AsyncBotsResourceWithStreamingResponse:
+ """AI 数据助手"""
+ from .resources.bots import AsyncBotsResourceWithStreamingResponse
+
+ return AsyncBotsResourceWithStreamingResponse(self._client.bots)
+
+ @cached_property
+ def auth(self) -> auth.AsyncAuthResourceWithStreamingResponse:
+ """AskTable 系统认证管理"""
+ from .resources.auth import AsyncAuthResourceWithStreamingResponse
+
+ return AsyncAuthResourceWithStreamingResponse(self._client.auth)
+
+ @cached_property
+ def answers(self) -> answers.AsyncAnswersResourceWithStreamingResponse:
+ """单轮对话"""
+ from .resources.answers import AsyncAnswersResourceWithStreamingResponse
+
+ return AsyncAnswersResourceWithStreamingResponse(self._client.answers)
+
+ @cached_property
+ def sqls(self) -> sqls.AsyncSqlsResourceWithStreamingResponse:
+ """单轮对话"""
+ from .resources.sqls import AsyncSqlsResourceWithStreamingResponse
+
+ return AsyncSqlsResourceWithStreamingResponse(self._client.sqls)
+
+ @cached_property
+ def integration(self) -> integration.AsyncIntegrationResourceWithStreamingResponse:
+ """与第三方平台集成"""
+ from .resources.integration import AsyncIntegrationResourceWithStreamingResponse
+
+ return AsyncIntegrationResourceWithStreamingResponse(self._client.integration)
+
+ @cached_property
+ def business_glossary(self) -> business_glossary.AsyncBusinessGlossaryResourceWithStreamingResponse:
+ """业务术语管理"""
+ from .resources.business_glossary import AsyncBusinessGlossaryResourceWithStreamingResponse
+
+ return AsyncBusinessGlossaryResourceWithStreamingResponse(self._client.business_glossary)
+
+ @cached_property
+ def preferences(self) -> preferences.AsyncPreferencesResourceWithStreamingResponse:
+ """偏好设置"""
+ from .resources.preferences import AsyncPreferencesResourceWithStreamingResponse
+
+ return AsyncPreferencesResourceWithStreamingResponse(self._client.preferences)
+
+ @cached_property
+ def project(self) -> project.AsyncProjectResourceWithStreamingResponse:
+ """我的项目"""
+ from .resources.project import AsyncProjectResourceWithStreamingResponse
+
+ return AsyncProjectResourceWithStreamingResponse(self._client.project)
+
+ @cached_property
+ def scores(self) -> scores.AsyncScoresResourceWithStreamingResponse:
+ """评分"""
+ from .resources.scores import AsyncScoresResourceWithStreamingResponse
+
+ return AsyncScoresResourceWithStreamingResponse(self._client.scores)
+
+ @cached_property
+ def files(self) -> files.AsyncFilesResourceWithStreamingResponse:
+ """数据源管理"""
+ from .resources.files import AsyncFilesResourceWithStreamingResponse
+
+ return AsyncFilesResourceWithStreamingResponse(self._client.files)
+
+ @cached_property
+ def dataframes(self) -> dataframes.AsyncDataframesResourceWithStreamingResponse:
+ from .resources.dataframes import AsyncDataframesResourceWithStreamingResponse
+
+ return AsyncDataframesResourceWithStreamingResponse(self._client.dataframes)
+
+ @cached_property
+ def polish(self) -> polish.AsyncPolishResourceWithStreamingResponse:
+ """润色"""
+ from .resources.polish import AsyncPolishResourceWithStreamingResponse
+
+ return AsyncPolishResourceWithStreamingResponse(self._client.polish)
+
+ @cached_property
+ def user(self) -> user.AsyncUserResourceWithStreamingResponse:
+ from .resources.user import AsyncUserResourceWithStreamingResponse
+
+ return AsyncUserResourceWithStreamingResponse(self._client.user)
+
+ @cached_property
+ def ats(self) -> ats.AsyncATSResourceWithStreamingResponse:
+ """测试系统"""
+ from .resources.ats import AsyncATSResourceWithStreamingResponse
+
+ return AsyncATSResourceWithStreamingResponse(self._client.ats)
Client = Asktable
diff --git a/src/asktable/_compat.py b/src/asktable/_compat.py
index 92d9ee61..e6690a4f 100644
--- a/src/asktable/_compat.py
+++ b/src/asktable/_compat.py
@@ -2,7 +2,7 @@
from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
from datetime import date, datetime
-from typing_extensions import Self, Literal
+from typing_extensions import Self, Literal, TypedDict
import pydantic
from pydantic.fields import FieldInfo
@@ -12,14 +12,13 @@
_T = TypeVar("_T")
_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
-# --------------- Pydantic v2 compatibility ---------------
+# --------------- Pydantic v2, v3 compatibility ---------------
# Pyright incorrectly reports some of our functions as overriding a method when they don't
# pyright: reportIncompatibleMethodOverride=false
-PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
+PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
-# v1 re-exports
if TYPE_CHECKING:
def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
@@ -44,90 +43,96 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
...
else:
- if PYDANTIC_V2:
- from pydantic.v1.typing import (
+ # v1 re-exports
+ if PYDANTIC_V1:
+ from pydantic.typing import (
get_args as get_args,
is_union as is_union,
get_origin as get_origin,
is_typeddict as is_typeddict,
is_literal_type as is_literal_type,
)
- from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
+ from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
else:
- from pydantic.typing import (
+ from ._utils import (
get_args as get_args,
is_union as is_union,
get_origin as get_origin,
+ parse_date as parse_date,
is_typeddict as is_typeddict,
+ parse_datetime as parse_datetime,
is_literal_type as is_literal_type,
)
- from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
# refactored config
if TYPE_CHECKING:
from pydantic import ConfigDict as ConfigDict
else:
- if PYDANTIC_V2:
- from pydantic import ConfigDict
- else:
+ if PYDANTIC_V1:
# TODO: provide an error message here?
ConfigDict = None
+ else:
+ from pydantic import ConfigDict as ConfigDict
# renamed methods / properties
def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
- if PYDANTIC_V2:
- return model.model_validate(value)
- else:
+ if PYDANTIC_V1:
return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
+ else:
+ return model.model_validate(value)
def field_is_required(field: FieldInfo) -> bool:
- if PYDANTIC_V2:
- return field.is_required()
- return field.required # type: ignore
+ if PYDANTIC_V1:
+ return field.required # type: ignore
+ return field.is_required()
def field_get_default(field: FieldInfo) -> Any:
value = field.get_default()
- if PYDANTIC_V2:
- from pydantic_core import PydanticUndefined
-
- if value == PydanticUndefined:
- return None
+ if PYDANTIC_V1:
return value
+ from pydantic_core import PydanticUndefined
+
+ if value == PydanticUndefined:
+ return None
return value
def field_outer_type(field: FieldInfo) -> Any:
- if PYDANTIC_V2:
- return field.annotation
- return field.outer_type_ # type: ignore
+ if PYDANTIC_V1:
+ return field.outer_type_ # type: ignore
+ return field.annotation
def get_model_config(model: type[pydantic.BaseModel]) -> Any:
- if PYDANTIC_V2:
- return model.model_config
- return model.__config__ # type: ignore
+ if PYDANTIC_V1:
+ return model.__config__ # type: ignore
+ return model.model_config
def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
- if PYDANTIC_V2:
- return model.model_fields
- return model.__fields__ # type: ignore
+ if PYDANTIC_V1:
+ return model.__fields__ # type: ignore
+ return model.model_fields
def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
- if PYDANTIC_V2:
- return model.model_copy(deep=deep)
- return model.copy(deep=deep) # type: ignore
+ if PYDANTIC_V1:
+ return model.copy(deep=deep) # type: ignore
+ return model.model_copy(deep=deep)
def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
- if PYDANTIC_V2:
- return model.model_dump_json(indent=indent)
- return model.json(indent=indent) # type: ignore
+ if PYDANTIC_V1:
+ return model.json(indent=indent) # type: ignore
+ return model.model_dump_json(indent=indent)
+
+
+class _ModelDumpKwargs(TypedDict, total=False):
+ by_alias: bool
def model_dump(
@@ -138,30 +143,33 @@ def model_dump(
exclude_defaults: bool = False,
warnings: bool = True,
mode: Literal["json", "python"] = "python",
+ by_alias: bool | None = None,
) -> dict[str, Any]:
- if PYDANTIC_V2 or hasattr(model, "model_dump"):
+ if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
+ kwargs: _ModelDumpKwargs = {}
+ if by_alias is not None:
+ kwargs["by_alias"] = by_alias
return model.model_dump(
mode=mode,
exclude=exclude,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
# warnings are not supported in Pydantic v1
- warnings=warnings if PYDANTIC_V2 else True,
+ warnings=True if PYDANTIC_V1 else warnings,
+ **kwargs,
)
return cast(
"dict[str, Any]",
model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
- exclude=exclude,
- exclude_unset=exclude_unset,
- exclude_defaults=exclude_defaults,
+ exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias)
),
)
def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
- if PYDANTIC_V2:
- return model.model_validate(data)
- return model.parse_obj(data) # pyright: ignore[reportDeprecated]
+ if PYDANTIC_V1:
+ return model.parse_obj(data) # pyright: ignore[reportDeprecated]
+ return model.model_validate(data)
# generic models
@@ -170,17 +178,16 @@ def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
class GenericModel(pydantic.BaseModel): ...
else:
- if PYDANTIC_V2:
+ if PYDANTIC_V1:
+ import pydantic.generics
+
+ class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
+ else:
# there no longer needs to be a distinction in v2 but
# we still have to create our own subclass to avoid
# inconsistent MRO ordering errors
class GenericModel(pydantic.BaseModel): ...
- else:
- import pydantic.generics
-
- class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
-
# cached properties
if TYPE_CHECKING:
diff --git a/src/asktable/_files.py b/src/asktable/_files.py
index 25ff804f..cc14c14f 100644
--- a/src/asktable/_files.py
+++ b/src/asktable/_files.py
@@ -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. See https://github.com/DataMini/asktable-python/tree/main#file-uploads"
+ f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead."
) from None
@@ -69,12 +69,12 @@ def _transform_file(file: FileTypes) -> HttpxFileTypes:
return file
if is_tuple_t(file):
- return (file[0], _read_file_content(file[1]), *file[2:])
+ return (file[0], read_file_content(file[1]), *file[2:])
raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
-def _read_file_content(file: FileContent) -> HttpxFileContent:
+def read_file_content(file: FileContent) -> HttpxFileContent:
if isinstance(file, os.PathLike):
return pathlib.Path(file).read_bytes()
return file
@@ -111,12 +111,12 @@ async def _async_transform_file(file: FileTypes) -> HttpxFileTypes:
return file
if is_tuple_t(file):
- return (file[0], await _async_read_file_content(file[1]), *file[2:])
+ return (file[0], await async_read_file_content(file[1]), *file[2:])
raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
-async def _async_read_file_content(file: FileContent) -> HttpxFileContent:
+async def async_read_file_content(file: FileContent) -> HttpxFileContent:
if isinstance(file, os.PathLike):
return await anyio.Path(file).read_bytes()
diff --git a/src/asktable/_models.py b/src/asktable/_models.py
index 528d5680..29070e05 100644
--- a/src/asktable/_models.py
+++ b/src/asktable/_models.py
@@ -2,7 +2,21 @@
import os
import inspect
-from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast
+import weakref
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Any,
+ Type,
+ Union,
+ Generic,
+ TypeVar,
+ Callable,
+ Iterable,
+ Optional,
+ AsyncIterable,
+ cast,
+)
from datetime import date, datetime
from typing_extensions import (
List,
@@ -50,7 +64,7 @@
strip_annotated_type,
)
from ._compat import (
- PYDANTIC_V2,
+ PYDANTIC_V1,
ConfigDict,
GenericModel as BaseGenericModel,
get_args,
@@ -81,11 +95,7 @@ class _ConfigProtocol(Protocol):
class BaseModel(pydantic.BaseModel):
- if PYDANTIC_V2:
- model_config: ClassVar[ConfigDict] = ConfigDict(
- extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
- )
- else:
+ if PYDANTIC_V1:
@property
@override
@@ -95,6 +105,10 @@ def model_fields_set(self) -> set[str]:
class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
extra: Any = pydantic.Extra.allow # type: ignore
+ else:
+ model_config: ClassVar[ConfigDict] = ConfigDict(
+ extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
+ )
def to_dict(
self,
@@ -208,28 +222,32 @@ def construct( # pyright: ignore[reportIncompatibleMethodOverride]
else:
fields_values[name] = field_get_default(field)
+ extra_field_type = _get_extra_fields_type(__cls)
+
_extra = {}
for key, value in values.items():
if key not in model_fields:
- if PYDANTIC_V2:
- _extra[key] = value
- else:
+ parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value
+
+ if PYDANTIC_V1:
_fields_set.add(key)
- fields_values[key] = value
+ fields_values[key] = parsed
+ else:
+ _extra[key] = parsed
object.__setattr__(m, "__dict__", fields_values)
- if PYDANTIC_V2:
- # these properties are copied from Pydantic's `model_construct()` method
- object.__setattr__(m, "__pydantic_private__", None)
- object.__setattr__(m, "__pydantic_extra__", _extra)
- object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
- else:
+ if PYDANTIC_V1:
# init_private_attributes() does not exist in v2
m._init_private_attributes() # type: ignore
# copied from Pydantic v1's `construct()` method
object.__setattr__(m, "__fields_set__", _fields_set)
+ else:
+ # these properties are copied from Pydantic's `model_construct()` method
+ object.__setattr__(m, "__pydantic_private__", None)
+ object.__setattr__(m, "__pydantic_extra__", _extra)
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
return m
@@ -239,7 +257,7 @@ def construct( # pyright: ignore[reportIncompatibleMethodOverride]
# although not in practice
model_construct = construct
- if not PYDANTIC_V2:
+ if PYDANTIC_V1:
# we define aliases for some of the new pydantic v2 methods so
# that we can just document these methods without having to specify
# a specific pydantic version as some users may not know which
@@ -252,13 +270,15 @@ def model_dump(
mode: Literal["json", "python"] | str = "python",
include: IncEx | None = None,
exclude: IncEx | None = None,
- by_alias: bool = False,
+ context: Any | None = None,
+ by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
+ exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal["none", "warn", "error"] = True,
- context: dict[str, Any] | None = None,
+ fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
) -> dict[str, Any]:
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
@@ -267,16 +287,24 @@ def model_dump(
Args:
mode: The mode in which `to_python` should run.
- If mode is 'json', the dictionary will only contain JSON serializable types.
- If mode is 'python', the dictionary may contain any Python objects.
- include: A list of fields to include in the output.
- exclude: A list of fields to exclude from the output.
+ If mode is 'json', the output will only contain JSON serializable types.
+ If mode is 'python', the output may contain non-JSON-serializable Python objects.
+ include: A set of fields to include in the output.
+ exclude: A set of fields to exclude from the output.
+ context: Additional context to pass to the serializer.
by_alias: Whether to use the field's alias in the dictionary key if defined.
- exclude_unset: Whether to exclude fields that are unset or None from the output.
- exclude_defaults: Whether to exclude fields that are set to their default value from the output.
- exclude_none: Whether to exclude fields that have a value of `None` from the output.
- round_trip: Whether to enable serialization and deserialization round-trip support.
- warnings: Whether to log warnings when invalid fields are encountered.
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
+ exclude_defaults: Whether to exclude fields that are set to their default value.
+ exclude_none: Whether to exclude fields that have a value of `None`.
+ exclude_computed_fields: Whether to exclude computed fields.
+ While this can be useful for round-tripping, it is usually recommended to use the dedicated
+ `round_trip` parameter instead.
+ round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
+ warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
+ "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+ fallback: A function to call when an unknown value is encountered. If not provided,
+ a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+ serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
Returns:
A dictionary representation of the model.
@@ -291,31 +319,38 @@ def model_dump(
raise ValueError("context is only supported in Pydantic v2")
if serialize_as_any != False:
raise ValueError("serialize_as_any is only supported in Pydantic v2")
+ if fallback is not None:
+ raise ValueError("fallback is only supported in Pydantic v2")
+ if exclude_computed_fields != False:
+ raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
dumped = super().dict( # pyright: ignore[reportDeprecated]
include=include,
exclude=exclude,
- by_alias=by_alias,
+ by_alias=by_alias if by_alias is not None else False,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
)
- return cast(dict[str, Any], json_safe(dumped)) if mode == "json" else dumped
+ return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped
@override
def model_dump_json(
self,
*,
indent: int | None = None,
+ ensure_ascii: bool = False,
include: IncEx | None = None,
exclude: IncEx | None = None,
- by_alias: bool = False,
+ context: Any | None = None,
+ by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
+ exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal["none", "warn", "error"] = True,
- context: dict[str, Any] | None = None,
+ fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
) -> str:
"""Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
@@ -344,11 +379,17 @@ def model_dump_json(
raise ValueError("context is only supported in Pydantic v2")
if serialize_as_any != False:
raise ValueError("serialize_as_any is only supported in Pydantic v2")
+ if fallback is not None:
+ raise ValueError("fallback is only supported in Pydantic v2")
+ if ensure_ascii != False:
+ raise ValueError("ensure_ascii is only supported in Pydantic v2")
+ if exclude_computed_fields != False:
+ raise ValueError("exclude_computed_fields is only supported in Pydantic v2")
return super().json( # type: ignore[reportDeprecated]
indent=indent,
include=include,
exclude=exclude,
- by_alias=by_alias,
+ by_alias=by_alias if by_alias is not None else False,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
@@ -359,10 +400,10 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
if value is None:
return field_get_default(field)
- if PYDANTIC_V2:
- type_ = field.annotation
- else:
+ if PYDANTIC_V1:
type_ = cast(type, field.outer_type_) # type: ignore
+ else:
+ type_ = field.annotation # type: ignore
if type_ is None:
raise RuntimeError(f"Unexpected field type is None for {key}")
@@ -370,6 +411,23 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None))
+def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None:
+ if PYDANTIC_V1:
+ # TODO
+ return None
+
+ schema = cls.__pydantic_core_schema__
+ if schema["type"] == "model":
+ fields = schema["schema"]
+ if fields["type"] == "model-fields":
+ extras = fields.get("extras_schema")
+ if extras and "cls" in extras:
+ # mypy can't narrow the type
+ return extras["cls"] # type: ignore[no-any-return]
+
+ return None
+
+
def is_basemodel(type_: type) -> bool:
"""Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
if is_union(type_):
@@ -439,7 +497,7 @@ def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]
type_ = type_.__value__ # type: ignore[unreachable]
# unwrap `Annotated[T, ...]` -> `T`
- if metadata is not None:
+ if metadata is not None and len(metadata) > 0:
meta: tuple[Any, ...] = tuple(metadata)
elif is_annotated_type(type_):
meta = get_args(type_)[1:]
@@ -546,6 +604,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.
@@ -588,8 +649,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
@@ -607,30 +669,30 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,
for variant in get_args(union):
variant = strip_annotated_type(variant)
if is_basemodel_type(variant):
- if PYDANTIC_V2:
- field = _extract_field_schema_pv2(variant, discriminator_field_name)
- if not field:
+ if PYDANTIC_V1:
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
+ if not field_info:
continue
# Note: if one variant defines an alias then they all should
- discriminator_alias = field.get("serialization_alias")
-
- field_schema = field["schema"]
+ discriminator_alias = field_info.alias
- if field_schema["type"] == "literal":
- for entry in cast("LiteralSchema", field_schema)["expected"]:
+ if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation):
+ for entry in get_args(annotation):
if isinstance(entry, str):
mapping[entry] = variant
else:
- field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
- if not field_info:
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
+ if not field:
continue
# Note: if one variant defines an alias then they all should
- discriminator_alias = field_info.alias
+ discriminator_alias = field.get("serialization_alias")
- if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation):
- for entry in get_args(annotation):
+ field_schema = field["schema"]
+
+ if field_schema["type"] == "literal":
+ for entry in cast("LiteralSchema", field_schema)["expected"]:
if isinstance(entry, str):
mapping[entry] = variant
@@ -642,7 +704,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
@@ -693,7 +755,7 @@ class GenericModel(BaseGenericModel, BaseModel):
pass
-if PYDANTIC_V2:
+if not PYDANTIC_V1:
from pydantic import TypeAdapter as _TypeAdapter
_CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter))
@@ -738,6 +800,7 @@ class FinalRequestOptionsInput(TypedDict, total=False):
timeout: float | Timeout | None
files: HttpxRequestFiles | None
idempotency_key: str
+ content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None]
json_data: Body
extra_json: AnyMapping
follow_redirects: bool
@@ -756,17 +819,18 @@ class FinalRequestOptions(pydantic.BaseModel):
post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
follow_redirects: Union[bool, None] = None
+ content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None
# It should be noted that we cannot use `json` here as that would override
# a BaseModel method in an incompatible fashion.
json_data: Union[Body, None] = None
extra_json: Union[AnyMapping, None] = None
- if PYDANTIC_V2:
- model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
- else:
+ if PYDANTIC_V1:
class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
arbitrary_types_allowed: bool = True
+ else:
+ model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
def get_max_retries(self, max_retries: int) -> int:
if isinstance(self.max_retries, NotGiven):
@@ -799,9 +863,9 @@ def construct( # type: ignore
key: strip_not_given(value)
for key, value in values.items()
}
- if PYDANTIC_V2:
- return super().model_construct(_fields_set, **kwargs)
- return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
+ if PYDANTIC_V1:
+ return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
+ return super().model_construct(_fields_set, **kwargs)
if not TYPE_CHECKING:
# type checkers incorrectly complain about this assignment
diff --git a/src/asktable/_qs.py b/src/asktable/_qs.py
index 274320ca..de8c99bc 100644
--- a/src/asktable/_qs.py
+++ b/src/asktable/_qs.py
@@ -4,7 +4,7 @@
from urllib.parse import parse_qs, urlencode
from typing_extensions import Literal, get_args
-from ._types import NOT_GIVEN, NotGiven, NotGivenOr
+from ._types import NotGiven, not_given
from ._utils import flatten
_T = TypeVar("_T")
@@ -41,8 +41,8 @@ def stringify(
self,
params: Params,
*,
- array_format: NotGivenOr[ArrayFormat] = NOT_GIVEN,
- nested_format: NotGivenOr[NestedFormat] = NOT_GIVEN,
+ array_format: ArrayFormat | NotGiven = not_given,
+ nested_format: NestedFormat | NotGiven = not_given,
) -> str:
return urlencode(
self.stringify_items(
@@ -56,8 +56,8 @@ def stringify_items(
self,
params: Params,
*,
- array_format: NotGivenOr[ArrayFormat] = NOT_GIVEN,
- nested_format: NotGivenOr[NestedFormat] = NOT_GIVEN,
+ array_format: ArrayFormat | NotGiven = not_given,
+ nested_format: NestedFormat | NotGiven = not_given,
) -> list[tuple[str, str]]:
opts = Options(
qs=self,
@@ -101,7 +101,10 @@ def _stringify_item(
items.extend(self._stringify_item(key, item, opts))
return items
elif array_format == "indices":
- raise NotImplementedError("The array indices format is not supported yet")
+ items = []
+ for i, item in enumerate(value):
+ items.extend(self._stringify_item(f"{key}[{i}]", item, opts))
+ return items
elif array_format == "brackets":
items = []
key = key + "[]"
@@ -143,8 +146,8 @@ def __init__(
self,
qs: Querystring = _qs,
*,
- array_format: NotGivenOr[ArrayFormat] = NOT_GIVEN,
- nested_format: NotGivenOr[NestedFormat] = NOT_GIVEN,
+ array_format: ArrayFormat | NotGiven = not_given,
+ nested_format: NestedFormat | NotGiven = not_given,
) -> None:
self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format
self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format
diff --git a/src/asktable/_response.py b/src/asktable/_response.py
index 0c91a6f9..de559384 100644
--- a/src/asktable/_response.py
+++ b/src/asktable/_response.py
@@ -152,6 +152,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
),
response=self.http_response,
client=cast(Any, self._client),
+ options=self._options,
),
)
@@ -162,6 +163,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
cast_to=extract_stream_chunk_type(self._stream_cls),
response=self.http_response,
client=cast(Any, self._client),
+ options=self._options,
),
)
@@ -175,6 +177,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
cast_to=cast_to,
response=self.http_response,
client=cast(Any, self._client),
+ options=self._options,
),
)
diff --git a/src/asktable/_streaming.py b/src/asktable/_streaming.py
index d37e4a40..978574ca 100644
--- a/src/asktable/_streaming.py
+++ b/src/asktable/_streaming.py
@@ -4,7 +4,7 @@
import json
import inspect
from types import TracebackType
-from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, AsyncIterator, cast
+from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast
from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable
import httpx
@@ -13,6 +13,7 @@
if TYPE_CHECKING:
from ._client import Asktable, AsyncAsktable
+ from ._models import FinalRequestOptions
_T = TypeVar("_T")
@@ -22,7 +23,7 @@ class Stream(Generic[_T]):
"""Provides the core interface to iterate over a synchronous stream response."""
response: httpx.Response
-
+ _options: Optional[FinalRequestOptions] = None
_decoder: SSEBytesDecoder
def __init__(
@@ -31,10 +32,12 @@ def __init__(
cast_to: type[_T],
response: httpx.Response,
client: Asktable,
+ options: Optional[FinalRequestOptions] = None,
) -> None:
self.response = response
self._cast_to = cast_to
self._client = client
+ self._options = options
self._decoder = client._make_sse_decoder()
self._iterator = self.__stream__()
@@ -54,12 +57,12 @@ def __stream__(self) -> Iterator[_T]:
process_data = self._client._process_response_data
iterator = self._iter_events()
- 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:
- ...
+ try:
+ for sse in iterator:
+ yield process_data(data=sse.json(), cast_to=cast_to, response=response)
+ finally:
+ # Ensure the response is closed even if the consumer doesn't read all data
+ response.close()
def __enter__(self) -> Self:
return self
@@ -85,7 +88,7 @@ class AsyncStream(Generic[_T]):
"""Provides the core interface to iterate over an asynchronous stream response."""
response: httpx.Response
-
+ _options: Optional[FinalRequestOptions] = None
_decoder: SSEDecoder | SSEBytesDecoder
def __init__(
@@ -94,10 +97,12 @@ def __init__(
cast_to: type[_T],
response: httpx.Response,
client: AsyncAsktable,
+ options: Optional[FinalRequestOptions] = None,
) -> None:
self.response = response
self._cast_to = cast_to
self._client = client
+ self._options = options
self._decoder = client._make_sse_decoder()
self._iterator = self.__stream__()
@@ -118,12 +123,12 @@ async def __stream__(self) -> AsyncIterator[_T]:
process_data = self._client._process_response_data
iterator = self._iter_events()
- 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:
- ...
+ try:
+ async for sse in iterator:
+ yield process_data(data=sse.json(), cast_to=cast_to, response=response)
+ finally:
+ # Ensure the response is closed even if the consumer doesn't read all data
+ await response.aclose()
async def __aenter__(self) -> Self:
return self
diff --git a/src/asktable/_types.py b/src/asktable/_types.py
index 6a08b156..2cfbd939 100644
--- a/src/asktable/_types.py
+++ b/src/asktable/_types.py
@@ -13,10 +13,23 @@
Mapping,
TypeVar,
Callable,
+ Iterable,
+ Iterator,
Optional,
Sequence,
+ AsyncIterable,
+)
+from typing_extensions import (
+ Set,
+ Literal,
+ Protocol,
+ TypeAlias,
+ TypedDict,
+ SupportsIndex,
+ overload,
+ override,
+ runtime_checkable,
)
-from typing_extensions import Set, Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable
import httpx
import pydantic
@@ -45,6 +58,13 @@
else:
Base64FileInput = Union[IO[bytes], PathLike]
FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
+
+
+# Used for sending raw binary data / streaming data in request bodies
+# e.g. for file uploads without multipart encoding
+BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]]
+AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]]
+
FileTypes = Union[
# file (or bytes)
FileContent,
@@ -106,18 +126,21 @@ class RequestOptions(TypedDict, total=False):
# Sentinel class used until PEP 0661 is accepted
class NotGiven:
"""
- A sentinel singleton class used to distinguish omitted keyword arguments
- from those passed in with the value None (which may have different behavior).
+ For parameters with a meaningful None value, we need to distinguish between
+ the user explicitly passing None, and the user not passing the parameter at
+ all.
+
+ User code shouldn't need to use not_given directly.
For example:
```py
- def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ...
+ def create(timeout: Timeout | None | NotGiven = not_given): ...
- get(timeout=1) # 1s timeout
- get(timeout=None) # No timeout
- get() # Default timeout behavior, which may not be statically known at the method definition.
+ create(timeout=1) # 1s timeout
+ create(timeout=None) # No timeout
+ create() # Default timeout behavior
```
"""
@@ -129,13 +152,14 @@ def __repr__(self) -> str:
return "NOT_GIVEN"
-NotGivenOr = Union[_T, NotGiven]
+not_given = NotGiven()
+# for backwards compatibility:
NOT_GIVEN = NotGiven()
class Omit:
- """In certain situations you need to be able to represent a case where a default value has
- to be explicitly removed and `None` is not an appropriate substitute, for example:
+ """
+ To explicitly omit something from being sent in a request, use `omit`.
```py
# as the default `Content-Type` header is `application/json` that will be sent
@@ -145,8 +169,8 @@ class Omit:
# to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
client.post(..., headers={"Content-Type": "multipart/form-data"})
- # instead you can remove the default `application/json` header by passing Omit
- client.post(..., headers={"Content-Type": Omit()})
+ # instead you can remove the default `application/json` header by passing omit
+ client.post(..., headers={"Content-Type": omit})
```
"""
@@ -154,6 +178,9 @@ def __bool__(self) -> Literal[False]:
return False
+omit = Omit()
+
+
@runtime_checkable
class ModelBuilderProtocol(Protocol):
@classmethod
@@ -217,3 +244,27 @@ class _GenericAlias(Protocol):
class HttpxSendArgs(TypedDict, total=False):
auth: httpx.Auth
follow_redirects: bool
+
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+
+if TYPE_CHECKING:
+ # This works because str.__contains__ does not accept object (either in typeshed or at runtime)
+ # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285
+ #
+ # Note: index() and count() methods are intentionally omitted to allow pyright to properly
+ # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr.
+ class SequenceNotStr(Protocol[_T_co]):
+ @overload
+ def __getitem__(self, index: SupportsIndex, /) -> _T_co: ...
+ @overload
+ def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ...
+ def __contains__(self, value: object, /) -> bool: ...
+ def __len__(self) -> int: ...
+ def __iter__(self) -> Iterator[_T_co]: ...
+ def __reversed__(self) -> Iterator[_T_co]: ...
+else:
+ # just point this to a normal `Sequence` at runtime to avoid having to special case
+ # deserializing our custom sequence type
+ SequenceNotStr = Sequence
diff --git a/src/asktable/_utils/__init__.py b/src/asktable/_utils/__init__.py
index d4fda26f..10cb66d2 100644
--- a/src/asktable/_utils/__init__.py
+++ b/src/asktable/_utils/__init__.py
@@ -1,3 +1,4 @@
+from ._path import path_template as path_template
from ._sync import asyncify as asyncify
from ._proxy import LazyProxy as LazyProxy
from ._utils import (
@@ -10,7 +11,6 @@
lru_cache as lru_cache,
is_mapping as is_mapping,
is_tuple_t as is_tuple_t,
- parse_date as parse_date,
is_iterable as is_iterable,
is_sequence as is_sequence,
coerce_float as coerce_float,
@@ -23,7 +23,6 @@
coerce_boolean as coerce_boolean,
coerce_integer as coerce_integer,
file_from_path as file_from_path,
- parse_datetime as parse_datetime,
strip_not_given as strip_not_given,
deepcopy_minimal as deepcopy_minimal,
get_async_library as get_async_library,
@@ -32,12 +31,20 @@
maybe_coerce_boolean as maybe_coerce_boolean,
maybe_coerce_integer as maybe_coerce_integer,
)
+from ._compat import (
+ get_args as get_args,
+ is_union as is_union,
+ get_origin as get_origin,
+ is_typeddict as is_typeddict,
+ is_literal_type as is_literal_type,
+)
from ._typing import (
is_list_type as is_list_type,
is_union_type as is_union_type,
extract_type_arg as extract_type_arg,
is_iterable_type as is_iterable_type,
is_required_type as is_required_type,
+ is_sequence_type as is_sequence_type,
is_annotated_type as is_annotated_type,
is_type_alias_type as is_type_alias_type,
strip_annotated_type as strip_annotated_type,
@@ -55,3 +62,4 @@
function_has_argument as function_has_argument,
assert_signatures_in_sync as assert_signatures_in_sync,
)
+from ._datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
diff --git a/src/asktable/_utils/_compat.py b/src/asktable/_utils/_compat.py
new file mode 100644
index 00000000..2c70b299
--- /dev/null
+++ b/src/asktable/_utils/_compat.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+import sys
+import typing_extensions
+from typing import Any, Type, Union, Literal, Optional
+from datetime import date, datetime
+from typing_extensions import get_args as _get_args, get_origin as _get_origin
+
+from .._types import StrBytesIntFloat
+from ._datetime_parse import parse_date as _parse_date, parse_datetime as _parse_datetime
+
+_LITERAL_TYPES = {Literal, typing_extensions.Literal}
+
+
+def get_args(tp: type[Any]) -> tuple[Any, ...]:
+ return _get_args(tp)
+
+
+def get_origin(tp: type[Any]) -> type[Any] | None:
+ return _get_origin(tp)
+
+
+def is_union(tp: Optional[Type[Any]]) -> bool:
+ if sys.version_info < (3, 10):
+ return tp is Union # type: ignore[comparison-overlap]
+ else:
+ import types
+
+ return tp is Union or tp is types.UnionType # type: ignore[comparison-overlap]
+
+
+def is_typeddict(tp: Type[Any]) -> bool:
+ return typing_extensions.is_typeddict(tp)
+
+
+def is_literal_type(tp: Type[Any]) -> bool:
+ return get_origin(tp) in _LITERAL_TYPES
+
+
+def parse_date(value: Union[date, StrBytesIntFloat]) -> date:
+ return _parse_date(value)
+
+
+def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
+ return _parse_datetime(value)
diff --git a/src/asktable/_utils/_datetime_parse.py b/src/asktable/_utils/_datetime_parse.py
new file mode 100644
index 00000000..7cb9d9e6
--- /dev/null
+++ b/src/asktable/_utils/_datetime_parse.py
@@ -0,0 +1,136 @@
+"""
+This file contains code from https://github.com/pydantic/pydantic/blob/main/pydantic/v1/datetime_parse.py
+without the Pydantic v1 specific errors.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Dict, Union, Optional
+from datetime import date, datetime, timezone, timedelta
+
+from .._types import StrBytesIntFloat
+
+date_expr = r"(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})"
+time_expr = (
+ r"(?P\d{1,2}):(?P\d{1,2})"
+ r"(?::(?P\d{1,2})(?:\.(?P\d{1,6})\d{0,6})?)?"
+ r"(?PZ|[+-]\d{2}(?::?\d{2})?)?$"
+)
+
+date_re = re.compile(f"{date_expr}$")
+datetime_re = re.compile(f"{date_expr}[T ]{time_expr}")
+
+
+EPOCH = datetime(1970, 1, 1)
+# if greater than this, the number is in ms, if less than or equal it's in seconds
+# (in seconds this is 11th October 2603, in ms it's 20th August 1970)
+MS_WATERSHED = int(2e10)
+# slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9
+MAX_NUMBER = int(3e20)
+
+
+def _get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]:
+ if isinstance(value, (int, float)):
+ return value
+ try:
+ return float(value)
+ except ValueError:
+ return None
+ except TypeError:
+ raise TypeError(f"invalid type; expected {native_expected_type}, string, bytes, int or float") from None
+
+
+def _from_unix_seconds(seconds: Union[int, float]) -> datetime:
+ if seconds > MAX_NUMBER:
+ return datetime.max
+ elif seconds < -MAX_NUMBER:
+ return datetime.min
+
+ while abs(seconds) > MS_WATERSHED:
+ seconds /= 1000
+ dt = EPOCH + timedelta(seconds=seconds)
+ return dt.replace(tzinfo=timezone.utc)
+
+
+def _parse_timezone(value: Optional[str]) -> Union[None, int, timezone]:
+ if value == "Z":
+ return timezone.utc
+ elif value is not None:
+ offset_mins = int(value[-2:]) if len(value) > 3 else 0
+ offset = 60 * int(value[1:3]) + offset_mins
+ if value[0] == "-":
+ offset = -offset
+ return timezone(timedelta(minutes=offset))
+ else:
+ return None
+
+
+def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
+ """
+ Parse a datetime/int/float/string and return a datetime.datetime.
+
+ This function supports time zone offsets. When the input contains one,
+ the output uses a timezone with a fixed offset from UTC.
+
+ Raise ValueError if the input is well formatted but not a valid datetime.
+ Raise ValueError if the input isn't well formatted.
+ """
+ if isinstance(value, datetime):
+ return value
+
+ number = _get_numeric(value, "datetime")
+ if number is not None:
+ return _from_unix_seconds(number)
+
+ if isinstance(value, bytes):
+ value = value.decode()
+
+ assert not isinstance(value, (float, int))
+
+ match = datetime_re.match(value)
+ if match is None:
+ raise ValueError("invalid datetime format")
+
+ kw = match.groupdict()
+ if kw["microsecond"]:
+ kw["microsecond"] = kw["microsecond"].ljust(6, "0")
+
+ tzinfo = _parse_timezone(kw.pop("tzinfo"))
+ kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
+ kw_["tzinfo"] = tzinfo
+
+ return datetime(**kw_) # type: ignore
+
+
+def parse_date(value: Union[date, StrBytesIntFloat]) -> date:
+ """
+ Parse a date/int/float/string and return a datetime.date.
+
+ Raise ValueError if the input is well formatted but not a valid date.
+ Raise ValueError if the input isn't well formatted.
+ """
+ if isinstance(value, date):
+ if isinstance(value, datetime):
+ return value.date()
+ else:
+ return value
+
+ number = _get_numeric(value, "date")
+ if number is not None:
+ return _from_unix_seconds(number).date()
+
+ if isinstance(value, bytes):
+ value = value.decode()
+
+ assert not isinstance(value, (float, int))
+ match = date_re.match(value)
+ if match is None:
+ raise ValueError("invalid date format")
+
+ kw = {k: int(v) for k, v in match.groupdict().items()}
+
+ try:
+ return date(**kw)
+ except ValueError:
+ raise ValueError("invalid date format") from None
diff --git a/src/asktable/_utils/_json.py b/src/asktable/_utils/_json.py
new file mode 100644
index 00000000..60584214
--- /dev/null
+++ b/src/asktable/_utils/_json.py
@@ -0,0 +1,35 @@
+import json
+from typing import Any
+from datetime import datetime
+from typing_extensions import override
+
+import pydantic
+
+from .._compat import model_dump
+
+
+def openapi_dumps(obj: Any) -> bytes:
+ """
+ Serialize an object to UTF-8 encoded JSON bytes.
+
+ Extends the standard json.dumps with support for additional types
+ commonly used in the SDK, such as `datetime`, `pydantic.BaseModel`, etc.
+ """
+ return json.dumps(
+ obj,
+ cls=_CustomEncoder,
+ # Uses the same defaults as httpx's JSON serialization
+ ensure_ascii=False,
+ separators=(",", ":"),
+ allow_nan=False,
+ ).encode()
+
+
+class _CustomEncoder(json.JSONEncoder):
+ @override
+ def default(self, o: Any) -> Any:
+ if isinstance(o, datetime):
+ return o.isoformat()
+ if isinstance(o, pydantic.BaseModel):
+ return model_dump(o, exclude_unset=True, mode="json", by_alias=True)
+ return super().default(o)
diff --git a/src/asktable/_utils/_path.py b/src/asktable/_utils/_path.py
new file mode 100644
index 00000000..4d6e1e4c
--- /dev/null
+++ b/src/asktable/_utils/_path.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import re
+from typing import (
+ Any,
+ Mapping,
+ Callable,
+)
+from urllib.parse import quote
+
+# Matches '.' or '..' where each dot is either literal or percent-encoded (%2e / %2E).
+_DOT_SEGMENT_RE = re.compile(r"^(?:\.|%2[eE]){1,2}$")
+
+_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
+
+
+def _quote_path_segment_part(value: str) -> str:
+ """Percent-encode `value` for use in a URI path segment.
+
+ Considers characters not in `pchar` set from RFC 3986 §3.3 to be unsafe.
+ https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
+ """
+ # quote() already treats unreserved characters (letters, digits, and -._~)
+ # as safe, so we only need to add sub-delims, ':', and '@'.
+ # Notably, unlike the default `safe` for quote(), / is unsafe and must be quoted.
+ return quote(value, safe="!$&'()*+,;=:@")
+
+
+def _quote_query_part(value: str) -> str:
+ """Percent-encode `value` for use in a URI query string.
+
+ Considers &, = and characters not in `query` set from RFC 3986 §3.4 to be unsafe.
+ https://datatracker.ietf.org/doc/html/rfc3986#section-3.4
+ """
+ return quote(value, safe="!$'()*+,;:@/?")
+
+
+def _quote_fragment_part(value: str) -> str:
+ """Percent-encode `value` for use in a URI fragment.
+
+ Considers characters not in `fragment` set from RFC 3986 §3.5 to be unsafe.
+ https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
+ """
+ return quote(value, safe="!$&'()*+,;=:@/?")
+
+
+def _interpolate(
+ template: str,
+ values: Mapping[str, Any],
+ quoter: Callable[[str], str],
+) -> str:
+ """Replace {name} placeholders in `template`, quoting each value with `quoter`.
+
+ Placeholder names are looked up in `values`.
+
+ Raises:
+ KeyError: If a placeholder is not found in `values`.
+ """
+ # re.split with a capturing group returns alternating
+ # [text, name, text, name, ..., text] elements.
+ parts = _PLACEHOLDER_RE.split(template)
+
+ for i in range(1, len(parts), 2):
+ name = parts[i]
+ if name not in values:
+ raise KeyError(f"a value for placeholder {{{name}}} was not provided")
+ val = values[name]
+ if val is None:
+ parts[i] = "null"
+ elif isinstance(val, bool):
+ parts[i] = "true" if val else "false"
+ else:
+ parts[i] = quoter(str(values[name]))
+
+ return "".join(parts)
+
+
+def path_template(template: str, /, **kwargs: Any) -> str:
+ """Interpolate {name} placeholders in `template` from keyword arguments.
+
+ Args:
+ template: The template string containing {name} placeholders.
+ **kwargs: Keyword arguments to interpolate into the template.
+
+ Returns:
+ The template with placeholders interpolated and percent-encoded.
+
+ Safe characters for percent-encoding are dependent on the URI component.
+ Placeholders in path and fragment portions are percent-encoded where the `segment`
+ and `fragment` sets from RFC 3986 respectively are considered safe.
+ Placeholders in the query portion are percent-encoded where the `query` set from
+ RFC 3986 §3.3 is considered safe except for = and & characters.
+
+ Raises:
+ KeyError: If a placeholder is not found in `kwargs`.
+ ValueError: If resulting path contains /./ or /../ segments (including percent-encoded dot-segments).
+ """
+ # Split the template into path, query, and fragment portions.
+ fragment_template: str | None = None
+ query_template: str | None = None
+
+ rest = template
+ if "#" in rest:
+ rest, fragment_template = rest.split("#", 1)
+ if "?" in rest:
+ rest, query_template = rest.split("?", 1)
+ path_template = rest
+
+ # Interpolate each portion with the appropriate quoting rules.
+ path_result = _interpolate(path_template, kwargs, _quote_path_segment_part)
+
+ # Reject dot-segments (. and ..) in the final assembled path. The check
+ # runs after interpolation so that adjacent placeholders or a mix of static
+ # text and placeholders that together form a dot-segment are caught.
+ # Also reject percent-encoded dot-segments to protect against incorrectly
+ # implemented normalization in servers/proxies.
+ for segment in path_result.split("/"):
+ if _DOT_SEGMENT_RE.match(segment):
+ raise ValueError(f"Constructed path {path_result!r} contains dot-segment {segment!r} which is not allowed")
+
+ result = path_result
+ if query_template is not None:
+ result += "?" + _interpolate(query_template, kwargs, _quote_query_part)
+ if fragment_template is not None:
+ result += "#" + _interpolate(fragment_template, kwargs, _quote_fragment_part)
+
+ return result
diff --git a/src/asktable/_utils/_sync.py b/src/asktable/_utils/_sync.py
index ad7ec71b..f6027c18 100644
--- a/src/asktable/_utils/_sync.py
+++ b/src/asktable/_utils/_sync.py
@@ -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
@@ -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),
@@ -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:
diff --git a/src/asktable/_utils/_transform.py b/src/asktable/_utils/_transform.py
index b0cc20a7..52075492 100644
--- a/src/asktable/_utils/_transform.py
+++ b/src/asktable/_utils/_transform.py
@@ -16,18 +16,20 @@
lru_cache,
is_mapping,
is_iterable,
+ is_sequence,
)
from .._files import is_base64_file_input
+from ._compat import get_origin, is_typeddict
from ._typing import (
is_list_type,
is_union_type,
extract_type_arg,
is_iterable_type,
is_required_type,
+ is_sequence_type,
is_annotated_type,
strip_annotated_type,
)
-from .._compat import get_origin, model_dump, is_typeddict
_T = TypeVar("_T")
@@ -167,6 +169,8 @@ def _transform_recursive(
Defaults to the same value as the `annotation` argument.
"""
+ from .._compat import model_dump
+
if inner_type is None:
inner_type = annotation
@@ -184,6 +188,8 @@ def _transform_recursive(
(is_list_type(stripped_type) and is_list(data))
# Iterable[T]
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
+ # Sequence[T]
+ or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str))
):
# dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
# intended as an iterable, so we don't transform it.
@@ -262,7 +268,7 @@ def _transform_typeddict(
annotations = get_type_hints(expected_type, include_extras=True)
for key, value in data.items():
if not is_given(value):
- # we don't need to include `NotGiven` values here as they'll
+ # we don't need to include omitted values here as they'll
# be stripped out before the request is sent anyway
continue
@@ -329,6 +335,8 @@ async def _async_transform_recursive(
Defaults to the same value as the `annotation` argument.
"""
+ from .._compat import model_dump
+
if inner_type is None:
inner_type = annotation
@@ -346,6 +354,8 @@ async def _async_transform_recursive(
(is_list_type(stripped_type) and is_list(data))
# Iterable[T]
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
+ # Sequence[T]
+ or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str))
):
# dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
# intended as an iterable, so we don't transform it.
@@ -424,7 +434,7 @@ async def _async_transform_typeddict(
annotations = get_type_hints(expected_type, include_extras=True)
for key, value in data.items():
if not is_given(value):
- # we don't need to include `NotGiven` values here as they'll
+ # we don't need to include omitted values here as they'll
# be stripped out before the request is sent anyway
continue
diff --git a/src/asktable/_utils/_typing.py b/src/asktable/_utils/_typing.py
index 1bac9542..193109f3 100644
--- a/src/asktable/_utils/_typing.py
+++ b/src/asktable/_utils/_typing.py
@@ -15,7 +15,7 @@
from ._utils import lru_cache
from .._types import InheritsGeneric
-from .._compat import is_union as _is_union
+from ._compat import is_union as _is_union
def is_annotated_type(typ: type) -> bool:
@@ -26,6 +26,11 @@ def is_list_type(typ: type) -> bool:
return (get_origin(typ) or typ) == list
+def is_sequence_type(typ: type) -> bool:
+ origin = get_origin(typ) or typ
+ return origin == typing_extensions.Sequence or origin == typing.Sequence or origin == _c_abc.Sequence
+
+
def is_iterable_type(typ: type) -> bool:
"""If the given type is `typing.Iterable[T]`"""
origin = get_origin(typ) or typ
diff --git a/src/asktable/_utils/_utils.py b/src/asktable/_utils/_utils.py
index ea3cf3f2..eec7f4a1 100644
--- a/src/asktable/_utils/_utils.py
+++ b/src/asktable/_utils/_utils.py
@@ -21,8 +21,7 @@
import sniffio
-from .._types import NotGiven, FileTypes, NotGivenOr, HeadersLike
-from .._compat import parse_date as parse_date, parse_datetime as parse_datetime
+from .._types import Omit, NotGiven, FileTypes, HeadersLike
_T = TypeVar("_T")
_TupleT = TypeVar("_TupleT", bound=Tuple[object, ...])
@@ -64,7 +63,7 @@ def _extract_items(
try:
key = path[index]
except IndexError:
- if isinstance(obj, NotGiven):
+ if not is_given(obj):
# no value was provided - we can safely ignore
return []
@@ -127,14 +126,14 @@ def _extract_items(
return []
-def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]:
- return not isinstance(obj, NotGiven)
+def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]:
+ return not isinstance(obj, NotGiven) and not isinstance(obj, Omit)
# 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
diff --git a/src/asktable/_version.py b/src/asktable/_version.py
index 118411d8..62ce948e 100644
--- a/src/asktable/_version.py
+++ b/src/asktable/_version.py
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
__title__ = "asktable"
-__version__ = "5.5.0" # x-release-please-version
+__version__ = "5.6.0" # x-release-please-version
diff --git a/src/asktable/resources/__init__.py b/src/asktable/resources/__init__.py
index 14a5d79a..75a4ac13 100644
--- a/src/asktable/resources/__init__.py
+++ b/src/asktable/resources/__init__.py
@@ -72,14 +72,6 @@
RolesResourceWithStreamingResponse,
AsyncRolesResourceWithStreamingResponse,
)
-from .caches import (
- CachesResource,
- AsyncCachesResource,
- CachesResourceWithRawResponse,
- AsyncCachesResourceWithRawResponse,
- CachesResourceWithStreamingResponse,
- AsyncCachesResourceWithStreamingResponse,
-)
from .polish import (
PolishResource,
AsyncPolishResource,
@@ -120,14 +112,6 @@
PoliciesResourceWithStreamingResponse,
AsyncPoliciesResourceWithStreamingResponse,
)
-from .trainings import (
- TrainingsResource,
- AsyncTrainingsResource,
- TrainingsResourceWithRawResponse,
- AsyncTrainingsResourceWithRawResponse,
- TrainingsResourceWithStreamingResponse,
- AsyncTrainingsResourceWithStreamingResponse,
-)
from .dataframes import (
DataframesResource,
AsyncDataframesResource,
@@ -238,12 +222,6 @@
"AsyncSqlsResourceWithRawResponse",
"SqlsResourceWithStreamingResponse",
"AsyncSqlsResourceWithStreamingResponse",
- "CachesResource",
- "AsyncCachesResource",
- "CachesResourceWithRawResponse",
- "AsyncCachesResourceWithRawResponse",
- "CachesResourceWithStreamingResponse",
- "AsyncCachesResourceWithStreamingResponse",
"IntegrationResource",
"AsyncIntegrationResource",
"IntegrationResourceWithRawResponse",
@@ -262,12 +240,6 @@
"AsyncPreferencesResourceWithRawResponse",
"PreferencesResourceWithStreamingResponse",
"AsyncPreferencesResourceWithStreamingResponse",
- "TrainingsResource",
- "AsyncTrainingsResource",
- "TrainingsResourceWithRawResponse",
- "AsyncTrainingsResourceWithRawResponse",
- "TrainingsResourceWithStreamingResponse",
- "AsyncTrainingsResourceWithStreamingResponse",
"ProjectResource",
"AsyncProjectResource",
"ProjectResourceWithRawResponse",
diff --git a/src/asktable/resources/answers.py b/src/asktable/resources/answers.py
index 8dbd2955..80c04567 100644
--- a/src/asktable/resources/answers.py
+++ b/src/asktable/resources/answers.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
import httpx
from ..types import answer_list_params, answer_create_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -25,6 +25,8 @@
class AnswersResource(SyncAPIResource):
+ """单轮对话"""
+
@cached_property
def with_raw_response(self) -> AnswersResourceWithRawResponse:
"""
@@ -49,16 +51,16 @@ def create(
*,
datasource_id: str,
question: str,
- max_rows: Optional[int] | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
- with_json: Optional[bool] | NotGiven = NOT_GIVEN,
+ max_rows: Optional[int] | Omit = omit,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, object]] | Omit = omit,
+ with_json: Optional[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AnswerResponse:
"""
发起查询的请求
@@ -107,15 +109,15 @@ def create(
def list(
self,
*,
- datasource_id: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ datasource_id: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[AnswerResponse]:
"""
获取所有的 Q2A 记录
@@ -157,6 +159,8 @@ def list(
class AsyncAnswersResource(AsyncAPIResource):
+ """单轮对话"""
+
@cached_property
def with_raw_response(self) -> AsyncAnswersResourceWithRawResponse:
"""
@@ -181,16 +185,16 @@ async def create(
*,
datasource_id: str,
question: str,
- max_rows: Optional[int] | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
- with_json: Optional[bool] | NotGiven = NOT_GIVEN,
+ max_rows: Optional[int] | Omit = omit,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, object]] | Omit = omit,
+ with_json: Optional[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AnswerResponse:
"""
发起查询的请求
@@ -239,15 +243,15 @@ async def create(
def list(
self,
*,
- datasource_id: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ datasource_id: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[AnswerResponse, AsyncPage[AnswerResponse]]:
"""
获取所有的 Q2A 记录
diff --git a/src/asktable/resources/ats/ats.py b/src/asktable/resources/ats/ats.py
index 64276c0d..45f3ffb6 100644
--- a/src/asktable/resources/ats/ats.py
+++ b/src/asktable/resources/ats/ats.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from typing import Optional
+
import httpx
from .task import (
@@ -13,8 +15,8 @@
AsyncTaskResourceWithStreamingResponse,
)
from ...types import ats_list_params, ats_create_params, ats_delete_params, ats_update_params
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from .test_case import (
TestCaseResource,
@@ -42,12 +44,16 @@
class ATSResource(SyncAPIResource):
+ """测试系统"""
+
@cached_property
def test_case(self) -> TestCaseResource:
+ """测试系统"""
return TestCaseResource(self._client)
@cached_property
def task(self) -> TaskResource:
+ """测试系统"""
return TaskResource(self._client)
@cached_property
@@ -79,7 +85,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ATSCreateResponse:
"""
Create Test Set Endpoint
@@ -121,7 +127,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ATSRetrieveResponse:
"""
Get Test Set Endpoint
@@ -138,7 +144,7 @@ def retrieve(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._get(
- f"/v1/ats/{ats_id}",
+ path_template("/v1/ats/{ats_id}", ats_id=ats_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -155,7 +161,7 @@ def update(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ATSUpdateResponse:
"""
Update Test Set Endpoint
@@ -174,7 +180,7 @@ def update(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._patch(
- f"/v1/ats/{ats_id}",
+ path_template("/v1/ats/{ats_id}", ats_id=ats_id),
body=maybe_transform({"name": name}, ats_update_params.ATSUpdateParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
@@ -185,21 +191,21 @@ def update(
def list(
self,
*,
- datasource_id: str,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ datasource_id: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[ATSListResponse]:
"""
Get Test Sets Endpoint
Args:
- datasource_id: 数据源 ID
+ datasource_id: 数据源 ID,可选过滤条件
page: Page number
@@ -243,7 +249,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
Delete Test Set Endpoint
@@ -262,7 +268,7 @@ def delete(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._delete(
- f"/v1/ats/{ats_id}",
+ path_template("/v1/ats/{ats_id}", ats_id=ats_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -275,12 +281,16 @@ def delete(
class AsyncATSResource(AsyncAPIResource):
+ """测试系统"""
+
@cached_property
def test_case(self) -> AsyncTestCaseResource:
+ """测试系统"""
return AsyncTestCaseResource(self._client)
@cached_property
def task(self) -> AsyncTaskResource:
+ """测试系统"""
return AsyncTaskResource(self._client)
@cached_property
@@ -312,7 +322,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ATSCreateResponse:
"""
Create Test Set Endpoint
@@ -354,7 +364,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ATSRetrieveResponse:
"""
Get Test Set Endpoint
@@ -371,7 +381,7 @@ async def retrieve(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return await self._get(
- f"/v1/ats/{ats_id}",
+ path_template("/v1/ats/{ats_id}", ats_id=ats_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -388,7 +398,7 @@ async def update(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ATSUpdateResponse:
"""
Update Test Set Endpoint
@@ -407,7 +417,7 @@ async def update(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return await self._patch(
- f"/v1/ats/{ats_id}",
+ path_template("/v1/ats/{ats_id}", ats_id=ats_id),
body=await async_maybe_transform({"name": name}, ats_update_params.ATSUpdateParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
@@ -418,21 +428,21 @@ async def update(
def list(
self,
*,
- datasource_id: str,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ datasource_id: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[ATSListResponse, AsyncPage[ATSListResponse]]:
"""
Get Test Sets Endpoint
Args:
- datasource_id: 数据源 ID
+ datasource_id: 数据源 ID,可选过滤条件
page: Page number
@@ -476,7 +486,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
Delete Test Set Endpoint
@@ -495,7 +505,7 @@ async def delete(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return await self._delete(
- f"/v1/ats/{ats_id}",
+ path_template("/v1/ats/{ats_id}", ats_id=ats_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -529,10 +539,12 @@ def __init__(self, ats: ATSResource) -> None:
@cached_property
def test_case(self) -> TestCaseResourceWithRawResponse:
+ """测试系统"""
return TestCaseResourceWithRawResponse(self._ats.test_case)
@cached_property
def task(self) -> TaskResourceWithRawResponse:
+ """测试系统"""
return TaskResourceWithRawResponse(self._ats.task)
@@ -558,10 +570,12 @@ def __init__(self, ats: AsyncATSResource) -> None:
@cached_property
def test_case(self) -> AsyncTestCaseResourceWithRawResponse:
+ """测试系统"""
return AsyncTestCaseResourceWithRawResponse(self._ats.test_case)
@cached_property
def task(self) -> AsyncTaskResourceWithRawResponse:
+ """测试系统"""
return AsyncTaskResourceWithRawResponse(self._ats.task)
@@ -587,10 +601,12 @@ def __init__(self, ats: ATSResource) -> None:
@cached_property
def test_case(self) -> TestCaseResourceWithStreamingResponse:
+ """测试系统"""
return TestCaseResourceWithStreamingResponse(self._ats.test_case)
@cached_property
def task(self) -> TaskResourceWithStreamingResponse:
+ """测试系统"""
return TaskResourceWithStreamingResponse(self._ats.task)
@@ -616,8 +632,10 @@ def __init__(self, ats: AsyncATSResource) -> None:
@cached_property
def test_case(self) -> AsyncTestCaseResourceWithStreamingResponse:
+ """测试系统"""
return AsyncTestCaseResourceWithStreamingResponse(self._ats.test_case)
@cached_property
def task(self) -> AsyncTaskResourceWithStreamingResponse:
+ """测试系统"""
return AsyncTaskResourceWithStreamingResponse(self._ats.task)
diff --git a/src/asktable/resources/ats/task.py b/src/asktable/resources/ats/task.py
index 7950fed9..ef412058 100644
--- a/src/asktable/resources/ats/task.py
+++ b/src/asktable/resources/ats/task.py
@@ -2,12 +2,10 @@
from __future__ import annotations
-from typing import List
-
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
@@ -28,6 +26,8 @@
class TaskResource(SyncAPIResource):
+ """测试系统"""
+
@cached_property
def with_raw_response(self) -> TaskResourceWithRawResponse:
"""
@@ -57,7 +57,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TaskRetrieveResponse:
"""
Get Test Task Endpoint
@@ -76,7 +76,7 @@ def retrieve(
if not ats_task_id:
raise ValueError(f"Expected a non-empty value for `ats_task_id` but received {ats_task_id!r}")
return self._get(
- f"/v1/ats/{ats_id}/task/{ats_task_id}",
+ path_template("/v1/ats/{ats_id}/task/{ats_task_id}", ats_id=ats_id, ats_task_id=ats_task_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -87,14 +87,14 @@ def list(
self,
ats_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[TaskListResponse]:
"""
Get Test Tasks Endpoint
@@ -115,7 +115,7 @@ def list(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._get_api_list(
- f"/v1/ats/{ats_id}/task",
+ path_template("/v1/ats/{ats_id}/task", ats_id=ats_id),
page=SyncPage[TaskListResponse],
options=make_request_options(
extra_headers=extra_headers,
@@ -138,14 +138,14 @@ def get_case_tasks(
ats_task_id: str,
*,
ats_id: str,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TaskGetCaseTasksResponse:
"""
Get Test Case Tasks Endpoint
@@ -168,7 +168,7 @@ def get_case_tasks(
if not ats_task_id:
raise ValueError(f"Expected a non-empty value for `ats_task_id` but received {ats_task_id!r}")
return self._get(
- f"/v1/ats/{ats_id}/task/{ats_task_id}/case",
+ path_template("/v1/ats/{ats_id}/task/{ats_task_id}/case", ats_id=ats_id, ats_task_id=ats_task_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -190,13 +190,13 @@ def run(
ats_id: str,
*,
datasource_id: str,
- specific_case_ids: List[str],
+ specific_case_ids: SequenceNotStr[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TaskRunResponse:
"""
Run Task Endpoint
@@ -217,7 +217,7 @@ def run(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._post(
- f"/v1/ats/{ats_id}/task",
+ path_template("/v1/ats/{ats_id}/task", ats_id=ats_id),
body=maybe_transform(
{
"datasource_id": datasource_id,
@@ -233,6 +233,8 @@ def run(
class AsyncTaskResource(AsyncAPIResource):
+ """测试系统"""
+
@cached_property
def with_raw_response(self) -> AsyncTaskResourceWithRawResponse:
"""
@@ -262,7 +264,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TaskRetrieveResponse:
"""
Get Test Task Endpoint
@@ -281,7 +283,7 @@ async def retrieve(
if not ats_task_id:
raise ValueError(f"Expected a non-empty value for `ats_task_id` but received {ats_task_id!r}")
return await self._get(
- f"/v1/ats/{ats_id}/task/{ats_task_id}",
+ path_template("/v1/ats/{ats_id}/task/{ats_task_id}", ats_id=ats_id, ats_task_id=ats_task_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -292,14 +294,14 @@ def list(
self,
ats_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[TaskListResponse, AsyncPage[TaskListResponse]]:
"""
Get Test Tasks Endpoint
@@ -320,7 +322,7 @@ def list(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._get_api_list(
- f"/v1/ats/{ats_id}/task",
+ path_template("/v1/ats/{ats_id}/task", ats_id=ats_id),
page=AsyncPage[TaskListResponse],
options=make_request_options(
extra_headers=extra_headers,
@@ -343,14 +345,14 @@ async def get_case_tasks(
ats_task_id: str,
*,
ats_id: str,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TaskGetCaseTasksResponse:
"""
Get Test Case Tasks Endpoint
@@ -373,7 +375,7 @@ async def get_case_tasks(
if not ats_task_id:
raise ValueError(f"Expected a non-empty value for `ats_task_id` but received {ats_task_id!r}")
return await self._get(
- f"/v1/ats/{ats_id}/task/{ats_task_id}/case",
+ path_template("/v1/ats/{ats_id}/task/{ats_task_id}/case", ats_id=ats_id, ats_task_id=ats_task_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -395,13 +397,13 @@ async def run(
ats_id: str,
*,
datasource_id: str,
- specific_case_ids: List[str],
+ specific_case_ids: SequenceNotStr[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TaskRunResponse:
"""
Run Task Endpoint
@@ -422,7 +424,7 @@ async def run(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return await self._post(
- f"/v1/ats/{ats_id}/task",
+ path_template("/v1/ats/{ats_id}/task", ats_id=ats_id),
body=await async_maybe_transform(
{
"datasource_id": datasource_id,
diff --git a/src/asktable/resources/ats/test_case.py b/src/asktable/resources/ats/test_case.py
index 58852a1a..15e89424 100644
--- a/src/asktable/resources/ats/test_case.py
+++ b/src/asktable/resources/ats/test_case.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
@@ -29,6 +29,7 @@
class TestCaseResource(SyncAPIResource):
__test__ = False
+ """测试系统"""
@cached_property
def with_raw_response(self) -> TestCaseResourceWithRawResponse:
@@ -55,14 +56,14 @@ def create(
*,
expected_sql: str,
question: str,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TestCaseCreateResponse:
"""
Create Test Case Endpoint
@@ -87,7 +88,7 @@ def create(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._post(
- f"/v1/ats/{ats_id}/test-case",
+ path_template("/v1/ats/{ats_id}/test-case", ats_id=ats_id),
body=maybe_transform(
{
"expected_sql": expected_sql,
@@ -113,7 +114,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TestCaseRetrieveResponse:
"""
Get Test Case Endpoint
@@ -132,7 +133,7 @@ def retrieve(
if not atc_id:
raise ValueError(f"Expected a non-empty value for `atc_id` but received {atc_id!r}")
return self._get(
- f"/v1/ats/{ats_id}/test-case/{atc_id}",
+ path_template("/v1/ats/{ats_id}/test-case/{atc_id}", ats_id=ats_id, atc_id=atc_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -146,14 +147,14 @@ def update(
ats_id: str,
expected_sql: str,
question: str,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TestCaseUpdateResponse:
"""
Update Test Case Endpoint
@@ -180,7 +181,7 @@ def update(
if not atc_id:
raise ValueError(f"Expected a non-empty value for `atc_id` but received {atc_id!r}")
return self._patch(
- f"/v1/ats/{ats_id}/test-case/{atc_id}",
+ path_template("/v1/ats/{ats_id}/test-case/{atc_id}", ats_id=ats_id, atc_id=atc_id),
body=maybe_transform(
{
"expected_sql": expected_sql,
@@ -200,14 +201,14 @@ def list(
self,
ats_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[TestCaseListResponse]:
"""
Get Test Cases Endpoint
@@ -228,7 +229,7 @@ def list(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._get_api_list(
- f"/v1/ats/{ats_id}/test-case",
+ path_template("/v1/ats/{ats_id}/test-case", ats_id=ats_id),
page=SyncPage[TestCaseListResponse],
options=make_request_options(
extra_headers=extra_headers,
@@ -256,7 +257,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
Delete Test Case Endpoint
@@ -275,7 +276,7 @@ def delete(
if not atc_id:
raise ValueError(f"Expected a non-empty value for `atc_id` but received {atc_id!r}")
return self._delete(
- f"/v1/ats/{ats_id}/test-case/{atc_id}",
+ path_template("/v1/ats/{ats_id}/test-case/{atc_id}", ats_id=ats_id, atc_id=atc_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -284,6 +285,8 @@ def delete(
class AsyncTestCaseResource(AsyncAPIResource):
+ """测试系统"""
+
@cached_property
def with_raw_response(self) -> AsyncTestCaseResourceWithRawResponse:
"""
@@ -309,14 +312,14 @@ async def create(
*,
expected_sql: str,
question: str,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TestCaseCreateResponse:
"""
Create Test Case Endpoint
@@ -341,7 +344,7 @@ async def create(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return await self._post(
- f"/v1/ats/{ats_id}/test-case",
+ path_template("/v1/ats/{ats_id}/test-case", ats_id=ats_id),
body=await async_maybe_transform(
{
"expected_sql": expected_sql,
@@ -367,7 +370,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TestCaseRetrieveResponse:
"""
Get Test Case Endpoint
@@ -386,7 +389,7 @@ async def retrieve(
if not atc_id:
raise ValueError(f"Expected a non-empty value for `atc_id` but received {atc_id!r}")
return await self._get(
- f"/v1/ats/{ats_id}/test-case/{atc_id}",
+ path_template("/v1/ats/{ats_id}/test-case/{atc_id}", ats_id=ats_id, atc_id=atc_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -400,14 +403,14 @@ async def update(
ats_id: str,
expected_sql: str,
question: str,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> TestCaseUpdateResponse:
"""
Update Test Case Endpoint
@@ -434,7 +437,7 @@ async def update(
if not atc_id:
raise ValueError(f"Expected a non-empty value for `atc_id` but received {atc_id!r}")
return await self._patch(
- f"/v1/ats/{ats_id}/test-case/{atc_id}",
+ path_template("/v1/ats/{ats_id}/test-case/{atc_id}", ats_id=ats_id, atc_id=atc_id),
body=await async_maybe_transform(
{
"expected_sql": expected_sql,
@@ -454,14 +457,14 @@ def list(
self,
ats_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[TestCaseListResponse, AsyncPage[TestCaseListResponse]]:
"""
Get Test Cases Endpoint
@@ -482,7 +485,7 @@ def list(
if not ats_id:
raise ValueError(f"Expected a non-empty value for `ats_id` but received {ats_id!r}")
return self._get_api_list(
- f"/v1/ats/{ats_id}/test-case",
+ path_template("/v1/ats/{ats_id}/test-case", ats_id=ats_id),
page=AsyncPage[TestCaseListResponse],
options=make_request_options(
extra_headers=extra_headers,
@@ -510,7 +513,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
Delete Test Case Endpoint
@@ -529,7 +532,7 @@ async def delete(
if not atc_id:
raise ValueError(f"Expected a non-empty value for `atc_id` but received {atc_id!r}")
return await self._delete(
- f"/v1/ats/{ats_id}/test-case/{atc_id}",
+ path_template("/v1/ats/{ats_id}/test-case/{atc_id}", ats_id=ats_id, atc_id=atc_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
diff --git a/src/asktable/resources/auth.py b/src/asktable/resources/auth.py
index 065e06f1..c293a396 100644
--- a/src/asktable/resources/auth.py
+++ b/src/asktable/resources/auth.py
@@ -2,13 +2,13 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Literal
import httpx
from ..types import auth_create_token_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -20,11 +20,14 @@
)
from .._base_client import make_request_options
from ..types.auth_me_response import AuthMeResponse
+from ..types.auth_create_token_response import AuthCreateTokenResponse
__all__ = ["AuthResource", "AsyncAuthResource"]
class AuthResource(SyncAPIResource):
+ """AskTable 系统认证管理"""
+
@cached_property
def with_raw_response(self) -> AuthResourceWithRawResponse:
"""
@@ -47,17 +50,17 @@ def with_streaming_response(self) -> AuthResourceWithStreamingResponse:
def create_token(
self,
*,
- ak_role: Literal["sys", "admin", "asker", "visitor"] | NotGiven = NOT_GIVEN,
- chat_role: Optional[auth_create_token_params.ChatRole] | NotGiven = NOT_GIVEN,
- token_ttl: int | NotGiven = NOT_GIVEN,
- user_profile: Optional[object] | NotGiven = NOT_GIVEN,
+ ak_role: Literal["sys", "admin", "asker", "visitor"] | Omit = omit,
+ chat_role: Optional[auth_create_token_params.ChatRole] | Omit = omit,
+ token_ttl: int | Omit = omit,
+ user_profile: Optional[Dict[str, 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> AuthCreateTokenResponse:
"""
Create Token
@@ -92,7 +95,7 @@ def create_token(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=AuthCreateTokenResponse,
)
def me(
@@ -103,7 +106,7 @@ def me(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AuthMeResponse:
"""获取当前登录的 TokenID"""
return self._get(
@@ -116,6 +119,8 @@ def me(
class AsyncAuthResource(AsyncAPIResource):
+ """AskTable 系统认证管理"""
+
@cached_property
def with_raw_response(self) -> AsyncAuthResourceWithRawResponse:
"""
@@ -138,17 +143,17 @@ def with_streaming_response(self) -> AsyncAuthResourceWithStreamingResponse:
async def create_token(
self,
*,
- ak_role: Literal["sys", "admin", "asker", "visitor"] | NotGiven = NOT_GIVEN,
- chat_role: Optional[auth_create_token_params.ChatRole] | NotGiven = NOT_GIVEN,
- token_ttl: int | NotGiven = NOT_GIVEN,
- user_profile: Optional[object] | NotGiven = NOT_GIVEN,
+ ak_role: Literal["sys", "admin", "asker", "visitor"] | Omit = omit,
+ chat_role: Optional[auth_create_token_params.ChatRole] | Omit = omit,
+ token_ttl: int | Omit = omit,
+ user_profile: Optional[Dict[str, 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> AuthCreateTokenResponse:
"""
Create Token
@@ -183,7 +188,7 @@ async def create_token(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=AuthCreateTokenResponse,
)
async def me(
@@ -194,7 +199,7 @@ async def me(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AuthMeResponse:
"""获取当前登录的 TokenID"""
return await self._get(
diff --git a/src/asktable/resources/bots.py b/src/asktable/resources/bots.py
index a64fb2d0..d62ff428 100644
--- a/src/asktable/resources/bots.py
+++ b/src/asktable/resources/bots.py
@@ -2,13 +2,13 @@
from __future__ import annotations
-from typing import List, Iterable, Optional
+from typing import Iterable, Optional
import httpx
from ..types import bot_list_params, bot_create_params, bot_invite_params, bot_update_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from .._utils import maybe_transform, async_maybe_transform
+from .._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from .._utils import path_template, maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -20,11 +20,14 @@
from ..pagination import SyncPage, AsyncPage
from .._base_client import AsyncPaginator, make_request_options
from ..types.chatbot import Chatbot
+from ..types.bot_invite_response import BotInviteResponse
__all__ = ["BotsResource", "AsyncBotsResource"]
class BotsResource(SyncAPIResource):
+ """AI 数据助手"""
+
@cached_property
def with_raw_response(self) -> BotsResourceWithRawResponse:
"""
@@ -47,28 +50,27 @@ def with_streaming_response(self) -> BotsResourceWithStreamingResponse:
def create(
self,
*,
- datasource_ids: List[str],
+ datasource_ids: SequenceNotStr[str],
name: str,
- color_theme: Optional[str] | NotGiven = NOT_GIVEN,
- debug: bool | NotGiven = NOT_GIVEN,
- extapi_ids: List[str] | NotGiven = NOT_GIVEN,
- interaction_rules: Iterable[bot_create_params.InteractionRule] | NotGiven = NOT_GIVEN,
- magic_input: Optional[str] | NotGiven = NOT_GIVEN,
- max_rows: int | NotGiven = NOT_GIVEN,
- publish: bool | NotGiven = NOT_GIVEN,
- query_balance: Optional[int] | NotGiven = NOT_GIVEN,
- sample_questions: Optional[List[str]] | NotGiven = NOT_GIVEN,
- webhooks: List[str] | NotGiven = NOT_GIVEN,
- welcome_message: Optional[str] | NotGiven = NOT_GIVEN,
+ color_theme: Optional[str] | Omit = omit,
+ debug: bool | Omit = omit,
+ interaction_rules: Iterable[bot_create_params.InteractionRule] | Omit = omit,
+ magic_input: Optional[str] | Omit = omit,
+ max_rows: int | Omit = omit,
+ publish: bool | Omit = omit,
+ query_balance: Optional[int] | Omit = omit,
+ sample_questions: Optional[SequenceNotStr[str]] | Omit = omit,
+ webhooks: SequenceNotStr[str] | Omit = omit,
+ welcome_message: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Chatbot:
"""
- 创建一个新的 Bot
+ 创建一个新的 AI 数据助手
Args:
datasource_ids: 数据源 ID,目前只支持 1 个数据源。
@@ -79,9 +81,7 @@ def create(
debug: 调试模式
- extapi_ids: 扩展 API ID 列表,扩展 API ID 的逗号分隔列表。
-
- interaction_rules: 交互规则列表,用于定义 bot 的行为规则
+ interaction_rules: 交互规则列表,用于定义 AI 数据助手的行为规则
magic_input: 魔法提示词
@@ -89,7 +89,7 @@ def create(
publish: 是否公开
- query_balance: bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
+ query_balance: AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
sample_questions: 示例问题列表
@@ -113,7 +113,6 @@ def create(
"name": name,
"color_theme": color_theme,
"debug": debug,
- "extapi_ids": extapi_ids,
"interaction_rules": interaction_rules,
"magic_input": magic_input,
"max_rows": max_rows,
@@ -140,10 +139,10 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Chatbot:
"""
- 获取某个 Bot
+ 获取某个 AI 数据助手
Args:
extra_headers: Send extra headers
@@ -157,7 +156,7 @@ def retrieve(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return self._get(
- f"/v1/bots/{bot_id}",
+ path_template("/v1/bots/{bot_id}", bot_id=bot_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -168,29 +167,28 @@ def update(
self,
bot_id: str,
*,
- avatar_url: Optional[str] | NotGiven = NOT_GIVEN,
- color_theme: Optional[str] | NotGiven = NOT_GIVEN,
- datasource_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- debug: Optional[bool] | NotGiven = NOT_GIVEN,
- extapi_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- interaction_rules: Optional[Iterable[bot_update_params.InteractionRule]] | NotGiven = NOT_GIVEN,
- magic_input: Optional[str] | NotGiven = NOT_GIVEN,
- max_rows: Optional[int] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- publish: Optional[bool] | NotGiven = NOT_GIVEN,
- query_balance: Optional[int] | NotGiven = NOT_GIVEN,
- sample_questions: Optional[List[str]] | NotGiven = NOT_GIVEN,
- webhooks: Optional[List[str]] | NotGiven = NOT_GIVEN,
- welcome_message: Optional[str] | NotGiven = NOT_GIVEN,
+ avatar_url: Optional[str] | Omit = omit,
+ color_theme: Optional[str] | Omit = omit,
+ datasource_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ debug: Optional[bool] | Omit = omit,
+ interaction_rules: Optional[Iterable[bot_update_params.InteractionRule]] | Omit = omit,
+ magic_input: Optional[str] | Omit = omit,
+ max_rows: Optional[int] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ publish: Optional[bool] | Omit = omit,
+ query_balance: Optional[int] | Omit = omit,
+ sample_questions: Optional[SequenceNotStr[str]] | Omit = omit,
+ webhooks: Optional[SequenceNotStr[str]] | Omit = omit,
+ welcome_message: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Chatbot:
"""
- 更新某个 Bot
+ 更新某个 AI 数据助手
Args:
avatar_url: 头像 URL
@@ -201,9 +199,7 @@ def update(
debug: 调试模式
- extapi_ids: 扩展 API ID 列表,扩展 API ID 的逗号分隔列表。
-
- interaction_rules: 交互规则列表,用于定义 bot 的行为规则
+ interaction_rules: 交互规则列表,用于定义 AI 数据助手的行为规则
magic_input: 魔法提示词
@@ -213,7 +209,7 @@ def update(
publish: 是否公开
- query_balance: bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
+ query_balance: AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
sample_questions: 示例问题列表
@@ -232,14 +228,13 @@ def update(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return self._patch(
- f"/v1/bots/{bot_id}",
+ path_template("/v1/bots/{bot_id}", bot_id=bot_id),
body=maybe_transform(
{
"avatar_url": avatar_url,
"color_theme": color_theme,
"datasource_ids": datasource_ids,
"debug": debug,
- "extapi_ids": extapi_ids,
"interaction_rules": interaction_rules,
"magic_input": magic_input,
"max_rows": max_rows,
@@ -261,19 +256,19 @@ def update(
def list(
self,
*,
- bot_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ bot_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[Chatbot]:
"""
- 查询所有 Bot
+ 查询所有 AI 数据助手
Args:
bot_ids: Bot ID
@@ -322,10 +317,10 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
- 删除某个 Bot
+ 删除某个 AI 数据助手
Args:
extra_headers: Send extra headers
@@ -339,7 +334,7 @@ def delete(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return self._delete(
- f"/v1/bots/{bot_id}",
+ path_template("/v1/bots/{bot_id}", bot_id=bot_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -356,8 +351,8 @@ def invite(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> BotInviteResponse:
"""
邀请用户加入对话
@@ -373,7 +368,7 @@ def invite(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return self._post(
- f"/v1/bots/{bot_id}/invite",
+ path_template("/v1/bots/{bot_id}/invite", bot_id=bot_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -381,11 +376,13 @@ def invite(
timeout=timeout,
query=maybe_transform({"project_id": project_id}, bot_invite_params.BotInviteParams),
),
- cast_to=object,
+ cast_to=BotInviteResponse,
)
class AsyncBotsResource(AsyncAPIResource):
+ """AI 数据助手"""
+
@cached_property
def with_raw_response(self) -> AsyncBotsResourceWithRawResponse:
"""
@@ -408,28 +405,27 @@ def with_streaming_response(self) -> AsyncBotsResourceWithStreamingResponse:
async def create(
self,
*,
- datasource_ids: List[str],
+ datasource_ids: SequenceNotStr[str],
name: str,
- color_theme: Optional[str] | NotGiven = NOT_GIVEN,
- debug: bool | NotGiven = NOT_GIVEN,
- extapi_ids: List[str] | NotGiven = NOT_GIVEN,
- interaction_rules: Iterable[bot_create_params.InteractionRule] | NotGiven = NOT_GIVEN,
- magic_input: Optional[str] | NotGiven = NOT_GIVEN,
- max_rows: int | NotGiven = NOT_GIVEN,
- publish: bool | NotGiven = NOT_GIVEN,
- query_balance: Optional[int] | NotGiven = NOT_GIVEN,
- sample_questions: Optional[List[str]] | NotGiven = NOT_GIVEN,
- webhooks: List[str] | NotGiven = NOT_GIVEN,
- welcome_message: Optional[str] | NotGiven = NOT_GIVEN,
+ color_theme: Optional[str] | Omit = omit,
+ debug: bool | Omit = omit,
+ interaction_rules: Iterable[bot_create_params.InteractionRule] | Omit = omit,
+ magic_input: Optional[str] | Omit = omit,
+ max_rows: int | Omit = omit,
+ publish: bool | Omit = omit,
+ query_balance: Optional[int] | Omit = omit,
+ sample_questions: Optional[SequenceNotStr[str]] | Omit = omit,
+ webhooks: SequenceNotStr[str] | Omit = omit,
+ welcome_message: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Chatbot:
"""
- 创建一个新的 Bot
+ 创建一个新的 AI 数据助手
Args:
datasource_ids: 数据源 ID,目前只支持 1 个数据源。
@@ -440,9 +436,7 @@ async def create(
debug: 调试模式
- extapi_ids: 扩展 API ID 列表,扩展 API ID 的逗号分隔列表。
-
- interaction_rules: 交互规则列表,用于定义 bot 的行为规则
+ interaction_rules: 交互规则列表,用于定义 AI 数据助手的行为规则
magic_input: 魔法提示词
@@ -450,7 +444,7 @@ async def create(
publish: 是否公开
- query_balance: bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
+ query_balance: AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
sample_questions: 示例问题列表
@@ -474,7 +468,6 @@ async def create(
"name": name,
"color_theme": color_theme,
"debug": debug,
- "extapi_ids": extapi_ids,
"interaction_rules": interaction_rules,
"magic_input": magic_input,
"max_rows": max_rows,
@@ -501,10 +494,10 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Chatbot:
"""
- 获取某个 Bot
+ 获取某个 AI 数据助手
Args:
extra_headers: Send extra headers
@@ -518,7 +511,7 @@ async def retrieve(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return await self._get(
- f"/v1/bots/{bot_id}",
+ path_template("/v1/bots/{bot_id}", bot_id=bot_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -529,29 +522,28 @@ async def update(
self,
bot_id: str,
*,
- avatar_url: Optional[str] | NotGiven = NOT_GIVEN,
- color_theme: Optional[str] | NotGiven = NOT_GIVEN,
- datasource_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- debug: Optional[bool] | NotGiven = NOT_GIVEN,
- extapi_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- interaction_rules: Optional[Iterable[bot_update_params.InteractionRule]] | NotGiven = NOT_GIVEN,
- magic_input: Optional[str] | NotGiven = NOT_GIVEN,
- max_rows: Optional[int] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- publish: Optional[bool] | NotGiven = NOT_GIVEN,
- query_balance: Optional[int] | NotGiven = NOT_GIVEN,
- sample_questions: Optional[List[str]] | NotGiven = NOT_GIVEN,
- webhooks: Optional[List[str]] | NotGiven = NOT_GIVEN,
- welcome_message: Optional[str] | NotGiven = NOT_GIVEN,
+ avatar_url: Optional[str] | Omit = omit,
+ color_theme: Optional[str] | Omit = omit,
+ datasource_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ debug: Optional[bool] | Omit = omit,
+ interaction_rules: Optional[Iterable[bot_update_params.InteractionRule]] | Omit = omit,
+ magic_input: Optional[str] | Omit = omit,
+ max_rows: Optional[int] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ publish: Optional[bool] | Omit = omit,
+ query_balance: Optional[int] | Omit = omit,
+ sample_questions: Optional[SequenceNotStr[str]] | Omit = omit,
+ webhooks: Optional[SequenceNotStr[str]] | Omit = omit,
+ welcome_message: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Chatbot:
"""
- 更新某个 Bot
+ 更新某个 AI 数据助手
Args:
avatar_url: 头像 URL
@@ -562,9 +554,7 @@ async def update(
debug: 调试模式
- extapi_ids: 扩展 API ID 列表,扩展 API ID 的逗号分隔列表。
-
- interaction_rules: 交互规则列表,用于定义 bot 的行为规则
+ interaction_rules: 交互规则列表,用于定义 AI 数据助手的行为规则
magic_input: 魔法提示词
@@ -574,7 +564,7 @@ async def update(
publish: 是否公开
- query_balance: bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
+ query_balance: AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数
sample_questions: 示例问题列表
@@ -593,14 +583,13 @@ async def update(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return await self._patch(
- f"/v1/bots/{bot_id}",
+ path_template("/v1/bots/{bot_id}", bot_id=bot_id),
body=await async_maybe_transform(
{
"avatar_url": avatar_url,
"color_theme": color_theme,
"datasource_ids": datasource_ids,
"debug": debug,
- "extapi_ids": extapi_ids,
"interaction_rules": interaction_rules,
"magic_input": magic_input,
"max_rows": max_rows,
@@ -622,19 +611,19 @@ async def update(
def list(
self,
*,
- bot_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ bot_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Chatbot, AsyncPage[Chatbot]]:
"""
- 查询所有 Bot
+ 查询所有 AI 数据助手
Args:
bot_ids: Bot ID
@@ -683,10 +672,10 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
- 删除某个 Bot
+ 删除某个 AI 数据助手
Args:
extra_headers: Send extra headers
@@ -700,7 +689,7 @@ async def delete(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return await self._delete(
- f"/v1/bots/{bot_id}",
+ path_template("/v1/bots/{bot_id}", bot_id=bot_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -717,8 +706,8 @@ async def invite(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> BotInviteResponse:
"""
邀请用户加入对话
@@ -734,7 +723,7 @@ async def invite(
if not bot_id:
raise ValueError(f"Expected a non-empty value for `bot_id` but received {bot_id!r}")
return await self._post(
- f"/v1/bots/{bot_id}/invite",
+ path_template("/v1/bots/{bot_id}/invite", bot_id=bot_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -742,7 +731,7 @@ async def invite(
timeout=timeout,
query=await async_maybe_transform({"project_id": project_id}, bot_invite_params.BotInviteParams),
),
- cast_to=object,
+ cast_to=BotInviteResponse,
)
diff --git a/src/asktable/resources/business_glossary.py b/src/asktable/resources/business_glossary.py
index 2eed15db..20d753fc 100644
--- a/src/asktable/resources/business_glossary.py
+++ b/src/asktable/resources/business_glossary.py
@@ -2,13 +2,13 @@
from __future__ import annotations
-from typing import List, Iterable, Optional
+from typing import Dict, Iterable, Optional
import httpx
from ..types import business_glossary_list_params, business_glossary_create_params, business_glossary_update_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from .._utils import maybe_transform, async_maybe_transform
+from .._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from .._utils import path_template, maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -27,6 +27,8 @@
class BusinessGlossaryResource(SyncAPIResource):
+ """业务术语管理"""
+
@cached_property
def with_raw_response(self) -> BusinessGlossaryResourceWithRawResponse:
"""
@@ -55,7 +57,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> BusinessGlossaryCreateResponse:
"""
创建业务术语
@@ -87,7 +89,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> EntryWithDefinition:
"""
获取某个业务术语
@@ -104,7 +106,7 @@ def retrieve(
if not entry_id:
raise ValueError(f"Expected a non-empty value for `entry_id` but received {entry_id!r}")
return self._get(
- f"/v1/business-glossary/{entry_id}",
+ path_template("/v1/business-glossary/{entry_id}", entry_id=entry_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -115,17 +117,17 @@ def update(
self,
entry_id: str,
*,
- active: Optional[bool] | NotGiven = NOT_GIVEN,
- aliases: Optional[List[str]] | NotGiven = NOT_GIVEN,
- definition: Optional[str] | NotGiven = NOT_GIVEN,
- payload: Optional[object] | NotGiven = NOT_GIVEN,
- term: Optional[str] | NotGiven = NOT_GIVEN,
+ active: Optional[bool] | Omit = omit,
+ aliases: Optional[SequenceNotStr[str]] | Omit = omit,
+ definition: Optional[str] | Omit = omit,
+ payload: Optional[Dict[str, object]] | Omit = omit,
+ term: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Entry:
"""
更新业务术语
@@ -152,7 +154,7 @@ def update(
if not entry_id:
raise ValueError(f"Expected a non-empty value for `entry_id` but received {entry_id!r}")
return self._patch(
- f"/v1/business-glossary/{entry_id}",
+ path_template("/v1/business-glossary/{entry_id}", entry_id=entry_id),
body=maybe_transform(
{
"active": active,
@@ -172,15 +174,15 @@ def update(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
- term: str | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | Omit = omit,
+ term: str | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[EntryWithDefinition]:
"""
查询所有业务术语
@@ -229,7 +231,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除某个业务术语
@@ -246,7 +248,7 @@ def delete(
if not entry_id:
raise ValueError(f"Expected a non-empty value for `entry_id` but received {entry_id!r}")
return self._delete(
- f"/v1/business-glossary/{entry_id}",
+ path_template("/v1/business-glossary/{entry_id}", entry_id=entry_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -255,6 +257,8 @@ def delete(
class AsyncBusinessGlossaryResource(AsyncAPIResource):
+ """业务术语管理"""
+
@cached_property
def with_raw_response(self) -> AsyncBusinessGlossaryResourceWithRawResponse:
"""
@@ -283,7 +287,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> BusinessGlossaryCreateResponse:
"""
创建业务术语
@@ -315,7 +319,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> EntryWithDefinition:
"""
获取某个业务术语
@@ -332,7 +336,7 @@ async def retrieve(
if not entry_id:
raise ValueError(f"Expected a non-empty value for `entry_id` but received {entry_id!r}")
return await self._get(
- f"/v1/business-glossary/{entry_id}",
+ path_template("/v1/business-glossary/{entry_id}", entry_id=entry_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -343,17 +347,17 @@ async def update(
self,
entry_id: str,
*,
- active: Optional[bool] | NotGiven = NOT_GIVEN,
- aliases: Optional[List[str]] | NotGiven = NOT_GIVEN,
- definition: Optional[str] | NotGiven = NOT_GIVEN,
- payload: Optional[object] | NotGiven = NOT_GIVEN,
- term: Optional[str] | NotGiven = NOT_GIVEN,
+ active: Optional[bool] | Omit = omit,
+ aliases: Optional[SequenceNotStr[str]] | Omit = omit,
+ definition: Optional[str] | Omit = omit,
+ payload: Optional[Dict[str, object]] | Omit = omit,
+ term: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Entry:
"""
更新业务术语
@@ -380,7 +384,7 @@ async def update(
if not entry_id:
raise ValueError(f"Expected a non-empty value for `entry_id` but received {entry_id!r}")
return await self._patch(
- f"/v1/business-glossary/{entry_id}",
+ path_template("/v1/business-glossary/{entry_id}", entry_id=entry_id),
body=await async_maybe_transform(
{
"active": active,
@@ -400,15 +404,15 @@ async def update(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
- term: str | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | Omit = omit,
+ term: str | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[EntryWithDefinition, AsyncPage[EntryWithDefinition]]:
"""
查询所有业务术语
@@ -457,7 +461,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除某个业务术语
@@ -474,7 +478,7 @@ async def delete(
if not entry_id:
raise ValueError(f"Expected a non-empty value for `entry_id` but received {entry_id!r}")
return await self._delete(
- f"/v1/business-glossary/{entry_id}",
+ path_template("/v1/business-glossary/{entry_id}", entry_id=entry_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
diff --git a/src/asktable/resources/caches.py b/src/asktable/resources/caches.py
deleted file mode 100644
index b89b7d6b..00000000
--- a/src/asktable/resources/caches.py
+++ /dev/null
@@ -1,164 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-import httpx
-
-from .._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven
-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
-
-__all__ = ["CachesResource", "AsyncCachesResource"]
-
-
-class CachesResource(SyncAPIResource):
- @cached_property
- def with_raw_response(self) -> CachesResourceWithRawResponse:
- """
- 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/DataMini/asktable-python#accessing-raw-response-data-eg-headers
- """
- return CachesResourceWithRawResponse(self)
-
- @cached_property
- def with_streaming_response(self) -> CachesResourceWithStreamingResponse:
- """
- An alternative to `.with_raw_response` that doesn't eagerly read the response body.
-
- For more information, see https://www.github.com/DataMini/asktable-python#with_streaming_response
- """
- return CachesResourceWithStreamingResponse(self)
-
- def delete(
- self,
- cache_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,
- ) -> None:
- """
- 清除缓存
-
- 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 cache_id:
- raise ValueError(f"Expected a non-empty value for `cache_id` but received {cache_id!r}")
- extra_headers = {"Accept": "*/*", **(extra_headers or {})}
- return self._delete(
- f"/v1/caches/{cache_id}",
- options=make_request_options(
- extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
- ),
- cast_to=NoneType,
- )
-
-
-class AsyncCachesResource(AsyncAPIResource):
- @cached_property
- def with_raw_response(self) -> AsyncCachesResourceWithRawResponse:
- """
- 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/DataMini/asktable-python#accessing-raw-response-data-eg-headers
- """
- return AsyncCachesResourceWithRawResponse(self)
-
- @cached_property
- def with_streaming_response(self) -> AsyncCachesResourceWithStreamingResponse:
- """
- An alternative to `.with_raw_response` that doesn't eagerly read the response body.
-
- For more information, see https://www.github.com/DataMini/asktable-python#with_streaming_response
- """
- return AsyncCachesResourceWithStreamingResponse(self)
-
- async def delete(
- self,
- cache_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,
- ) -> None:
- """
- 清除缓存
-
- 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 cache_id:
- raise ValueError(f"Expected a non-empty value for `cache_id` but received {cache_id!r}")
- extra_headers = {"Accept": "*/*", **(extra_headers or {})}
- return await self._delete(
- f"/v1/caches/{cache_id}",
- options=make_request_options(
- extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
- ),
- cast_to=NoneType,
- )
-
-
-class CachesResourceWithRawResponse:
- def __init__(self, caches: CachesResource) -> None:
- self._caches = caches
-
- self.delete = to_raw_response_wrapper(
- caches.delete,
- )
-
-
-class AsyncCachesResourceWithRawResponse:
- def __init__(self, caches: AsyncCachesResource) -> None:
- self._caches = caches
-
- self.delete = async_to_raw_response_wrapper(
- caches.delete,
- )
-
-
-class CachesResourceWithStreamingResponse:
- def __init__(self, caches: CachesResource) -> None:
- self._caches = caches
-
- self.delete = to_streamed_response_wrapper(
- caches.delete,
- )
-
-
-class AsyncCachesResourceWithStreamingResponse:
- def __init__(self, caches: AsyncCachesResource) -> None:
- self._caches = caches
-
- self.delete = async_to_streamed_response_wrapper(
- caches.delete,
- )
diff --git a/src/asktable/resources/chats/chats.py b/src/asktable/resources/chats/chats.py
index fd159838..d177f703 100644
--- a/src/asktable/resources/chats/chats.py
+++ b/src/asktable/resources/chats/chats.py
@@ -7,8 +7,8 @@
import httpx
from ...types import chat_list_params, chat_create_params
-from ..._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from .messages import (
MessagesResource,
AsyncMessagesResource,
@@ -26,16 +26,20 @@
async_to_streamed_response_wrapper,
)
from ...pagination import SyncPage, AsyncPage
-from ...types.chat import Chat
from ..._base_client import AsyncPaginator, make_request_options
+from ...types.chat_list_response import ChatListResponse
+from ...types.chat_create_response import ChatCreateResponse
from ...types.chat_retrieve_response import ChatRetrieveResponse
__all__ = ["ChatsResource", "AsyncChatsResource"]
class ChatsResource(SyncAPIResource):
+ """聊天管理"""
+
@cached_property
def messages(self) -> MessagesResource:
+ """聊天管理"""
return MessagesResource(self._client)
@cached_property
@@ -60,24 +64,24 @@ def with_streaming_response(self) -> ChatsResourceWithStreamingResponse:
def create(
self,
*,
- bot_id: Optional[str] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[Dict[str, Union[str, int, bool]]] | NotGiven = NOT_GIVEN,
- user_profile: Optional[Dict[str, Union[str, int, bool]]] | NotGiven = NOT_GIVEN,
+ bot_id: Optional[str] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, Union[str, int, bool]]] | Omit = omit,
+ user_profile: Optional[Dict[str, Union[str, int, 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,
- ) -> Chat:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ChatCreateResponse:
"""
创建对话
Args:
- bot_id: 机器人 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在机器人中你可以定义
- 可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
+ bot_id: AI 数据助手 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在 AI 数据助手中
+ 你可以定义可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
name: New name for the chat
@@ -111,7 +115,7 @@ def create(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=Chat,
+ cast_to=ChatCreateResponse,
)
def retrieve(
@@ -123,7 +127,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ChatRetrieveResponse:
"""
获取某个对话
@@ -140,7 +144,7 @@ def retrieve(
if not chat_id:
raise ValueError(f"Expected a non-empty value for `chat_id` but received {chat_id!r}")
return self._get(
- f"/v1/chats/{chat_id}",
+ path_template("/v1/chats/{chat_id}", chat_id=chat_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -150,15 +154,15 @@ def retrieve(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
- ) -> SyncPage[Chat]:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> SyncPage[ChatListResponse]:
"""
查询对话列表
@@ -177,7 +181,7 @@ def list(
"""
return self._get_api_list(
"/v1/chats",
- page=SyncPage[Chat],
+ page=SyncPage[ChatListResponse],
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -191,7 +195,7 @@ def list(
chat_list_params.ChatListParams,
),
),
- model=Chat,
+ model=ChatListResponse,
)
def delete(
@@ -203,7 +207,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
删除某个对话(包含消息)
@@ -221,7 +225,7 @@ def delete(
raise ValueError(f"Expected a non-empty value for `chat_id` but received {chat_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return self._delete(
- f"/v1/chats/{chat_id}",
+ path_template("/v1/chats/{chat_id}", chat_id=chat_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -230,8 +234,11 @@ def delete(
class AsyncChatsResource(AsyncAPIResource):
+ """聊天管理"""
+
@cached_property
def messages(self) -> AsyncMessagesResource:
+ """聊天管理"""
return AsyncMessagesResource(self._client)
@cached_property
@@ -256,24 +263,24 @@ def with_streaming_response(self) -> AsyncChatsResourceWithStreamingResponse:
async def create(
self,
*,
- bot_id: Optional[str] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[Dict[str, Union[str, int, bool]]] | NotGiven = NOT_GIVEN,
- user_profile: Optional[Dict[str, Union[str, int, bool]]] | NotGiven = NOT_GIVEN,
+ bot_id: Optional[str] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, Union[str, int, bool]]] | Omit = omit,
+ user_profile: Optional[Dict[str, Union[str, int, 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,
- ) -> Chat:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ChatCreateResponse:
"""
创建对话
Args:
- bot_id: 机器人 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在机器人中你可以定义
- 可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
+ bot_id: AI 数据助手 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在 AI 数据助手中
+ 你可以定义可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
name: New name for the chat
@@ -307,7 +314,7 @@ async def create(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=Chat,
+ cast_to=ChatCreateResponse,
)
async def retrieve(
@@ -319,7 +326,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ChatRetrieveResponse:
"""
获取某个对话
@@ -336,7 +343,7 @@ async def retrieve(
if not chat_id:
raise ValueError(f"Expected a non-empty value for `chat_id` but received {chat_id!r}")
return await self._get(
- f"/v1/chats/{chat_id}",
+ path_template("/v1/chats/{chat_id}", chat_id=chat_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -346,15 +353,15 @@ async def retrieve(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
- ) -> AsyncPaginator[Chat, AsyncPage[Chat]]:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> AsyncPaginator[ChatListResponse, AsyncPage[ChatListResponse]]:
"""
查询对话列表
@@ -373,7 +380,7 @@ def list(
"""
return self._get_api_list(
"/v1/chats",
- page=AsyncPage[Chat],
+ page=AsyncPage[ChatListResponse],
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -387,7 +394,7 @@ def list(
chat_list_params.ChatListParams,
),
),
- model=Chat,
+ model=ChatListResponse,
)
async def delete(
@@ -399,7 +406,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
删除某个对话(包含消息)
@@ -417,7 +424,7 @@ async def delete(
raise ValueError(f"Expected a non-empty value for `chat_id` but received {chat_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return await self._delete(
- f"/v1/chats/{chat_id}",
+ path_template("/v1/chats/{chat_id}", chat_id=chat_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -444,6 +451,7 @@ def __init__(self, chats: ChatsResource) -> None:
@cached_property
def messages(self) -> MessagesResourceWithRawResponse:
+ """聊天管理"""
return MessagesResourceWithRawResponse(self._chats.messages)
@@ -466,6 +474,7 @@ def __init__(self, chats: AsyncChatsResource) -> None:
@cached_property
def messages(self) -> AsyncMessagesResourceWithRawResponse:
+ """聊天管理"""
return AsyncMessagesResourceWithRawResponse(self._chats.messages)
@@ -488,6 +497,7 @@ def __init__(self, chats: ChatsResource) -> None:
@cached_property
def messages(self) -> MessagesResourceWithStreamingResponse:
+ """聊天管理"""
return MessagesResourceWithStreamingResponse(self._chats.messages)
@@ -510,4 +520,5 @@ def __init__(self, chats: AsyncChatsResource) -> None:
@cached_property
def messages(self) -> AsyncMessagesResourceWithStreamingResponse:
+ """聊天管理"""
return AsyncMessagesResourceWithStreamingResponse(self._chats.messages)
diff --git a/src/asktable/resources/chats/messages.py b/src/asktable/resources/chats/messages.py
index 7c3ca18a..3820b7b3 100644
--- a/src/asktable/resources/chats/messages.py
+++ b/src/asktable/resources/chats/messages.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Any, cast
+from typing import Any, Optional, cast
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
@@ -27,6 +27,8 @@
class MessagesResource(SyncAPIResource):
+ """聊天管理"""
+
@cached_property
def with_raw_response(self) -> MessagesResourceWithRawResponse:
"""
@@ -50,18 +52,21 @@ def create(
self,
chat_id: str,
*,
- question: str,
+ query_question: Optional[str] | Omit = omit,
+ body_question: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> MessageCreateResponse:
"""
Send a message to the chat
Args:
+ body_question: 用户问题
+
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
@@ -75,13 +80,16 @@ def create(
return cast(
MessageCreateResponse,
self._post(
- f"/v1/chats/{chat_id}/messages",
+ path_template("/v1/chats/{chat_id}/messages", chat_id=chat_id),
+ body=maybe_transform({"body_question": body_question}, message_create_params.MessageCreateParams),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
- query=maybe_transform({"question": question}, message_create_params.MessageCreateParams),
+ query=maybe_transform(
+ {"query_question": query_question}, message_create_params.MessageCreateParams
+ ),
),
cast_to=cast(
Any, MessageCreateResponse
@@ -99,7 +107,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> MessageRetrieveResponse:
"""
查询某条消息
@@ -120,7 +128,7 @@ def retrieve(
return cast(
MessageRetrieveResponse,
self._get(
- f"/v1/chats/{chat_id}/messages/{message_id}",
+ path_template("/v1/chats/{chat_id}/messages/{message_id}", chat_id=chat_id, message_id=message_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -134,14 +142,14 @@ def list(
self,
chat_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[MessageListResponse]:
"""
查询所有的消息
@@ -162,7 +170,7 @@ def list(
if not chat_id:
raise ValueError(f"Expected a non-empty value for `chat_id` but received {chat_id!r}")
return self._get_api_list(
- f"/v1/chats/{chat_id}/messages",
+ path_template("/v1/chats/{chat_id}/messages", chat_id=chat_id),
page=SyncPage[MessageListResponse],
options=make_request_options(
extra_headers=extra_headers,
@@ -182,6 +190,8 @@ def list(
class AsyncMessagesResource(AsyncAPIResource):
+ """聊天管理"""
+
@cached_property
def with_raw_response(self) -> AsyncMessagesResourceWithRawResponse:
"""
@@ -205,18 +215,21 @@ async def create(
self,
chat_id: str,
*,
- question: str,
+ query_question: Optional[str] | Omit = omit,
+ body_question: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> MessageCreateResponse:
"""
Send a message to the chat
Args:
+ body_question: 用户问题
+
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
@@ -230,14 +243,17 @@ async def create(
return cast(
MessageCreateResponse,
await self._post(
- f"/v1/chats/{chat_id}/messages",
+ path_template("/v1/chats/{chat_id}/messages", chat_id=chat_id),
+ body=await async_maybe_transform(
+ {"body_question": body_question}, message_create_params.MessageCreateParams
+ ),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=await async_maybe_transform(
- {"question": question}, message_create_params.MessageCreateParams
+ {"query_question": query_question}, message_create_params.MessageCreateParams
),
),
cast_to=cast(
@@ -256,7 +272,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> MessageRetrieveResponse:
"""
查询某条消息
@@ -277,7 +293,7 @@ async def retrieve(
return cast(
MessageRetrieveResponse,
await self._get(
- f"/v1/chats/{chat_id}/messages/{message_id}",
+ path_template("/v1/chats/{chat_id}/messages/{message_id}", chat_id=chat_id, message_id=message_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -291,14 +307,14 @@ def list(
self,
chat_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[MessageListResponse, AsyncPage[MessageListResponse]]:
"""
查询所有的消息
@@ -319,7 +335,7 @@ def list(
if not chat_id:
raise ValueError(f"Expected a non-empty value for `chat_id` but received {chat_id!r}")
return self._get_api_list(
- f"/v1/chats/{chat_id}/messages",
+ path_template("/v1/chats/{chat_id}/messages", chat_id=chat_id),
page=AsyncPage[MessageListResponse],
options=make_request_options(
extra_headers=extra_headers,
diff --git a/src/asktable/resources/dataframes.py b/src/asktable/resources/dataframes.py
index 4320689d..36cee9e9 100644
--- a/src/asktable/resources/dataframes.py
+++ b/src/asktable/resources/dataframes.py
@@ -4,7 +4,8 @@
import httpx
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+from .._types import Body, Query, Headers, NotGiven, not_given
+from .._utils import path_template
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -48,7 +49,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> DataframeRetrieveResponse:
"""
Get Dataframe
@@ -65,7 +66,7 @@ def retrieve(
if not dataframe_id:
raise ValueError(f"Expected a non-empty value for `dataframe_id` but received {dataframe_id!r}")
return self._get(
- f"/v1/dataframes/{dataframe_id}",
+ path_template("/v1/dataframes/{dataframe_id}", dataframe_id=dataframe_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -102,7 +103,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> DataframeRetrieveResponse:
"""
Get Dataframe
@@ -119,7 +120,7 @@ async def retrieve(
if not dataframe_id:
raise ValueError(f"Expected a non-empty value for `dataframe_id` but received {dataframe_id!r}")
return await self._get(
- f"/v1/dataframes/{dataframe_id}",
+ path_template("/v1/dataframes/{dataframe_id}", dataframe_id=dataframe_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
diff --git a/src/asktable/resources/datasources/datasources.py b/src/asktable/resources/datasources/datasources.py
index 239b7943..556b6231 100644
--- a/src/asktable/resources/datasources/datasources.py
+++ b/src/asktable/resources/datasources/datasources.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Mapping, Optional, cast
+from typing import Dict, Optional
from typing_extensions import Literal
import httpx
@@ -30,8 +30,8 @@
IndexesResourceWithStreamingResponse,
AsyncIndexesResourceWithStreamingResponse,
)
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes
-from ..._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
@@ -58,16 +58,21 @@
class DatasourcesResource(SyncAPIResource):
+ """数据源管理"""
+
@cached_property
def meta(self) -> MetaResource:
+ """数据源管理"""
return MetaResource(self._client)
@cached_property
def upload_params(self) -> UploadParamsResource:
+ """数据源管理"""
return UploadParamsResource(self._client)
@cached_property
def indexes(self) -> IndexesResource:
+ """索引管理"""
return IndexesResource(self._client)
@cached_property
@@ -114,15 +119,27 @@ def create(
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
],
- access_config: Optional[datasource_create_params.AccessConfig] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ access_config: Optional[datasource_create_params.AccessConfig] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Datasource:
"""
创建一个新的数据源
@@ -167,7 +184,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> DatasourceRetrieveResponse:
"""
根据 id 获取指定数据源
@@ -184,7 +201,7 @@ def retrieve(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._get(
- f"/v1/datasources/{datasource_id}",
+ path_template("/v1/datasources/{datasource_id}", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -195,8 +212,8 @@ def update(
self,
datasource_id: str,
*,
- access_config: Optional[datasource_update_params.AccessConfig] | NotGiven = NOT_GIVEN,
- desc: Optional[str] | NotGiven = NOT_GIVEN,
+ access_config: Optional[datasource_update_params.AccessConfig] | Omit = omit,
+ desc: Optional[str] | Omit = omit,
engine: Optional[
Literal[
"mysql",
@@ -220,22 +237,35 @@ def update(
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
]
]
- | NotGiven = NOT_GIVEN,
- field_count: Optional[int] | NotGiven = NOT_GIVEN,
- meta_error: Optional[str] | NotGiven = NOT_GIVEN,
- meta_status: Optional[Literal["processing", "failed", "success", "unprocessed"]] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- sample_questions: Optional[str] | NotGiven = NOT_GIVEN,
- schema_count: Optional[int] | NotGiven = NOT_GIVEN,
- table_count: Optional[int] | NotGiven = NOT_GIVEN,
+ | Omit = omit,
+ field_count: Optional[int] | Omit = omit,
+ meta_status: Optional[Literal["unavailable", "available"]] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ sample_questions: Optional[SequenceNotStr[str]] | Omit = omit,
+ schema_count: Optional[int] | Omit = omit,
+ sync_error: Optional[Dict[str, object]] | Omit = omit,
+ sync_status: Optional[Literal["processing", "success", "failed", "warning"]] | Omit = omit,
+ table_count: Optional[int] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Datasource:
"""
更新指定数据源信息
@@ -249,9 +279,7 @@ def update(
field_count: 字段数量
- meta_error: 元数据处理错误
-
- meta_status: 元数据处理状态
+ meta_status: 数据源可用性
name: 数据源的名称
@@ -259,6 +287,10 @@ def update(
schema_count: 库数量
+ sync_error: 同步错误信息
+
+ sync_status: 同步状态
+
table_count: 表数量
extra_headers: Send extra headers
@@ -272,18 +304,19 @@ def update(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._patch(
- f"/v1/datasources/{datasource_id}",
+ path_template("/v1/datasources/{datasource_id}", datasource_id=datasource_id),
body=maybe_transform(
{
"access_config": access_config,
"desc": desc,
"engine": engine,
"field_count": field_count,
- "meta_error": meta_error,
"meta_status": meta_status,
"name": name,
"sample_questions": sample_questions,
"schema_count": schema_count,
+ "sync_error": sync_error,
+ "sync_status": sync_status,
"table_count": table_count,
},
datasource_update_params.DatasourceUpdateParams,
@@ -297,15 +330,15 @@ def update(
def list(
self,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[Datasource]:
"""
获取所有的数据源
@@ -352,7 +385,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
根据 id 删除指定数据源
@@ -369,7 +402,7 @@ def delete(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._delete(
- f"/v1/datasources/{datasource_id}",
+ path_template("/v1/datasources/{datasource_id}", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -380,13 +413,13 @@ def add_file(
self,
datasource_id: str,
*,
- file: FileTypes,
+ file: 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
为数据源添加文件
@@ -402,16 +435,13 @@ def add_file(
"""
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
- 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(
- f"/v1/datasources/{datasource_id}/files",
- body=maybe_transform(body, datasource_add_file_params.DatasourceAddFileParams),
- files=files,
+ path_template("/v1/datasources/{datasource_id}/files", datasource_id=datasource_id),
+ body=maybe_transform({"file": file}, datasource_add_file_params.DatasourceAddFileParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -428,7 +458,7 @@ def delete_file(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除数据源的单个文件
@@ -447,7 +477,9 @@ def delete_file(
if not file_id:
raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
return self._delete(
- f"/v1/datasources/{datasource_id}/files/{file_id}",
+ path_template(
+ "/v1/datasources/{datasource_id}/files/{file_id}", datasource_id=datasource_id, file_id=file_id
+ ),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -463,7 +495,7 @@ def retrieve_runtime_meta(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> DatasourceRetrieveRuntimeMetaResponse:
"""
获取指定数据源的运行时元数据
@@ -480,7 +512,7 @@ def retrieve_runtime_meta(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._get(
- f"/v1/datasources/{datasource_id}/runtime-meta",
+ path_template("/v1/datasources/{datasource_id}/runtime-meta", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -497,14 +529,14 @@ def update_field(
identifiable_type: Optional[
Literal["plain", "person_name", "email", "ssn", "id", "phone", "address", "company", "bank_card"]
]
- | NotGiven = NOT_GIVEN,
- visibility: Optional[bool] | NotGiven = NOT_GIVEN,
+ | Omit = omit,
+ visibility: Optional[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
更新数据源的某个字段的描述
@@ -525,7 +557,7 @@ def update_field(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._patch(
- f"/v1/datasources/{datasource_id}/field",
+ path_template("/v1/datasources/{datasource_id}/field", datasource_id=datasource_id),
body=maybe_transform(
{
"identifiable_type": identifiable_type,
@@ -552,16 +584,21 @@ def update_field(
class AsyncDatasourcesResource(AsyncAPIResource):
+ """数据源管理"""
+
@cached_property
def meta(self) -> AsyncMetaResource:
+ """数据源管理"""
return AsyncMetaResource(self._client)
@cached_property
def upload_params(self) -> AsyncUploadParamsResource:
+ """数据源管理"""
return AsyncUploadParamsResource(self._client)
@cached_property
def indexes(self) -> AsyncIndexesResource:
+ """索引管理"""
return AsyncIndexesResource(self._client)
@cached_property
@@ -608,15 +645,27 @@ async def create(
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
],
- access_config: Optional[datasource_create_params.AccessConfig] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ access_config: Optional[datasource_create_params.AccessConfig] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Datasource:
"""
创建一个新的数据源
@@ -661,7 +710,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> DatasourceRetrieveResponse:
"""
根据 id 获取指定数据源
@@ -678,7 +727,7 @@ async def retrieve(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._get(
- f"/v1/datasources/{datasource_id}",
+ path_template("/v1/datasources/{datasource_id}", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -689,8 +738,8 @@ async def update(
self,
datasource_id: str,
*,
- access_config: Optional[datasource_update_params.AccessConfig] | NotGiven = NOT_GIVEN,
- desc: Optional[str] | NotGiven = NOT_GIVEN,
+ access_config: Optional[datasource_update_params.AccessConfig] | Omit = omit,
+ desc: Optional[str] | Omit = omit,
engine: Optional[
Literal[
"mysql",
@@ -714,22 +763,35 @@ async def update(
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
]
]
- | NotGiven = NOT_GIVEN,
- field_count: Optional[int] | NotGiven = NOT_GIVEN,
- meta_error: Optional[str] | NotGiven = NOT_GIVEN,
- meta_status: Optional[Literal["processing", "failed", "success", "unprocessed"]] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- sample_questions: Optional[str] | NotGiven = NOT_GIVEN,
- schema_count: Optional[int] | NotGiven = NOT_GIVEN,
- table_count: Optional[int] | NotGiven = NOT_GIVEN,
+ | Omit = omit,
+ field_count: Optional[int] | Omit = omit,
+ meta_status: Optional[Literal["unavailable", "available"]] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ sample_questions: Optional[SequenceNotStr[str]] | Omit = omit,
+ schema_count: Optional[int] | Omit = omit,
+ sync_error: Optional[Dict[str, object]] | Omit = omit,
+ sync_status: Optional[Literal["processing", "success", "failed", "warning"]] | Omit = omit,
+ table_count: Optional[int] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Datasource:
"""
更新指定数据源信息
@@ -743,9 +805,7 @@ async def update(
field_count: 字段数量
- meta_error: 元数据处理错误
-
- meta_status: 元数据处理状态
+ meta_status: 数据源可用性
name: 数据源的名称
@@ -753,6 +813,10 @@ async def update(
schema_count: 库数量
+ sync_error: 同步错误信息
+
+ sync_status: 同步状态
+
table_count: 表数量
extra_headers: Send extra headers
@@ -766,18 +830,19 @@ async def update(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._patch(
- f"/v1/datasources/{datasource_id}",
+ path_template("/v1/datasources/{datasource_id}", datasource_id=datasource_id),
body=await async_maybe_transform(
{
"access_config": access_config,
"desc": desc,
"engine": engine,
"field_count": field_count,
- "meta_error": meta_error,
"meta_status": meta_status,
"name": name,
"sample_questions": sample_questions,
"schema_count": schema_count,
+ "sync_error": sync_error,
+ "sync_status": sync_status,
"table_count": table_count,
},
datasource_update_params.DatasourceUpdateParams,
@@ -791,15 +856,15 @@ async def update(
def list(
self,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Datasource, AsyncPage[Datasource]]:
"""
获取所有的数据源
@@ -846,7 +911,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
根据 id 删除指定数据源
@@ -863,7 +928,7 @@ async def delete(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._delete(
- f"/v1/datasources/{datasource_id}",
+ path_template("/v1/datasources/{datasource_id}", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -874,13 +939,13 @@ async def add_file(
self,
datasource_id: str,
*,
- file: FileTypes,
+ file: 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
为数据源添加文件
@@ -896,16 +961,13 @@ async def add_file(
"""
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
- 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(
- f"/v1/datasources/{datasource_id}/files",
- body=await async_maybe_transform(body, datasource_add_file_params.DatasourceAddFileParams),
- files=files,
+ path_template("/v1/datasources/{datasource_id}/files", datasource_id=datasource_id),
+ body=await async_maybe_transform({"file": file}, datasource_add_file_params.DatasourceAddFileParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -922,7 +984,7 @@ async def delete_file(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除数据源的单个文件
@@ -941,7 +1003,9 @@ async def delete_file(
if not file_id:
raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
return await self._delete(
- f"/v1/datasources/{datasource_id}/files/{file_id}",
+ path_template(
+ "/v1/datasources/{datasource_id}/files/{file_id}", datasource_id=datasource_id, file_id=file_id
+ ),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -957,7 +1021,7 @@ async def retrieve_runtime_meta(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> DatasourceRetrieveRuntimeMetaResponse:
"""
获取指定数据源的运行时元数据
@@ -974,7 +1038,7 @@ async def retrieve_runtime_meta(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._get(
- f"/v1/datasources/{datasource_id}/runtime-meta",
+ path_template("/v1/datasources/{datasource_id}/runtime-meta", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -991,14 +1055,14 @@ async def update_field(
identifiable_type: Optional[
Literal["plain", "person_name", "email", "ssn", "id", "phone", "address", "company", "bank_card"]
]
- | NotGiven = NOT_GIVEN,
- visibility: Optional[bool] | NotGiven = NOT_GIVEN,
+ | Omit = omit,
+ visibility: Optional[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
更新数据源的某个字段的描述
@@ -1019,7 +1083,7 @@ async def update_field(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._patch(
- f"/v1/datasources/{datasource_id}/field",
+ path_template("/v1/datasources/{datasource_id}/field", datasource_id=datasource_id),
body=await async_maybe_transform(
{
"identifiable_type": identifiable_type,
@@ -1079,14 +1143,17 @@ def __init__(self, datasources: DatasourcesResource) -> None:
@cached_property
def meta(self) -> MetaResourceWithRawResponse:
+ """数据源管理"""
return MetaResourceWithRawResponse(self._datasources.meta)
@cached_property
def upload_params(self) -> UploadParamsResourceWithRawResponse:
+ """数据源管理"""
return UploadParamsResourceWithRawResponse(self._datasources.upload_params)
@cached_property
def indexes(self) -> IndexesResourceWithRawResponse:
+ """索引管理"""
return IndexesResourceWithRawResponse(self._datasources.indexes)
@@ -1124,14 +1191,17 @@ def __init__(self, datasources: AsyncDatasourcesResource) -> None:
@cached_property
def meta(self) -> AsyncMetaResourceWithRawResponse:
+ """数据源管理"""
return AsyncMetaResourceWithRawResponse(self._datasources.meta)
@cached_property
def upload_params(self) -> AsyncUploadParamsResourceWithRawResponse:
+ """数据源管理"""
return AsyncUploadParamsResourceWithRawResponse(self._datasources.upload_params)
@cached_property
def indexes(self) -> AsyncIndexesResourceWithRawResponse:
+ """索引管理"""
return AsyncIndexesResourceWithRawResponse(self._datasources.indexes)
@@ -1169,14 +1239,17 @@ def __init__(self, datasources: DatasourcesResource) -> None:
@cached_property
def meta(self) -> MetaResourceWithStreamingResponse:
+ """数据源管理"""
return MetaResourceWithStreamingResponse(self._datasources.meta)
@cached_property
def upload_params(self) -> UploadParamsResourceWithStreamingResponse:
+ """数据源管理"""
return UploadParamsResourceWithStreamingResponse(self._datasources.upload_params)
@cached_property
def indexes(self) -> IndexesResourceWithStreamingResponse:
+ """索引管理"""
return IndexesResourceWithStreamingResponse(self._datasources.indexes)
@@ -1214,12 +1287,15 @@ def __init__(self, datasources: AsyncDatasourcesResource) -> None:
@cached_property
def meta(self) -> AsyncMetaResourceWithStreamingResponse:
+ """数据源管理"""
return AsyncMetaResourceWithStreamingResponse(self._datasources.meta)
@cached_property
def upload_params(self) -> AsyncUploadParamsResourceWithStreamingResponse:
+ """数据源管理"""
return AsyncUploadParamsResourceWithStreamingResponse(self._datasources.upload_params)
@cached_property
def indexes(self) -> AsyncIndexesResourceWithStreamingResponse:
+ """索引管理"""
return AsyncIndexesResourceWithStreamingResponse(self._datasources.indexes)
diff --git a/src/asktable/resources/datasources/indexes.py b/src/asktable/resources/datasources/indexes.py
index 3ffd6f4a..3d618757 100644
--- a/src/asktable/resources/datasources/indexes.py
+++ b/src/asktable/resources/datasources/indexes.py
@@ -4,8 +4,8 @@
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
@@ -23,6 +23,8 @@
class IndexesResource(SyncAPIResource):
+ """索引管理"""
+
@cached_property
def with_raw_response(self) -> IndexesResourceWithRawResponse:
"""
@@ -49,13 +51,13 @@ def create(
field_name: str,
schema_name: str,
table_name: str,
- async_process: bool | NotGiven = NOT_GIVEN,
+ async_process: 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
创建索引 Args: ds_id: 数据源 ID index: 索引创建参数,包含
@@ -79,7 +81,7 @@ def create(
if not ds_id:
raise ValueError(f"Expected a non-empty value for `ds_id` but received {ds_id!r}")
return self._post(
- f"/v1/datasources/{ds_id}/indexes",
+ path_template("/v1/datasources/{ds_id}/indexes", ds_id=ds_id),
body=maybe_transform(
{
"field_name": field_name,
@@ -102,14 +104,14 @@ def list(
self,
ds_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[Index]:
"""
获取数据源的所有索引 Args: ds_id: 数据源 ID Returns: 索引列表,包含索引的完整信
@@ -131,7 +133,7 @@ def list(
if not ds_id:
raise ValueError(f"Expected a non-empty value for `ds_id` but received {ds_id!r}")
return self._get_api_list(
- f"/v1/datasources/{ds_id}/indexes",
+ path_template("/v1/datasources/{ds_id}/indexes", ds_id=ds_id),
page=SyncPage[Index],
options=make_request_options(
extra_headers=extra_headers,
@@ -159,7 +161,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除索引 Args: ds_id: 数据源 ID index_id: 索引 ID
@@ -178,7 +180,7 @@ def delete(
if not index_id:
raise ValueError(f"Expected a non-empty value for `index_id` but received {index_id!r}")
return self._delete(
- f"/v1/datasources/{ds_id}/indexes/{index_id}",
+ path_template("/v1/datasources/{ds_id}/indexes/{index_id}", ds_id=ds_id, index_id=index_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -187,6 +189,8 @@ def delete(
class AsyncIndexesResource(AsyncAPIResource):
+ """索引管理"""
+
@cached_property
def with_raw_response(self) -> AsyncIndexesResourceWithRawResponse:
"""
@@ -213,13 +217,13 @@ async def create(
field_name: str,
schema_name: str,
table_name: str,
- async_process: bool | NotGiven = NOT_GIVEN,
+ async_process: 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
创建索引 Args: ds_id: 数据源 ID index: 索引创建参数,包含
@@ -243,7 +247,7 @@ async def create(
if not ds_id:
raise ValueError(f"Expected a non-empty value for `ds_id` but received {ds_id!r}")
return await self._post(
- f"/v1/datasources/{ds_id}/indexes",
+ path_template("/v1/datasources/{ds_id}/indexes", ds_id=ds_id),
body=await async_maybe_transform(
{
"field_name": field_name,
@@ -268,14 +272,14 @@ def list(
self,
ds_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Index, AsyncPage[Index]]:
"""
获取数据源的所有索引 Args: ds_id: 数据源 ID Returns: 索引列表,包含索引的完整信
@@ -297,7 +301,7 @@ def list(
if not ds_id:
raise ValueError(f"Expected a non-empty value for `ds_id` but received {ds_id!r}")
return self._get_api_list(
- f"/v1/datasources/{ds_id}/indexes",
+ path_template("/v1/datasources/{ds_id}/indexes", ds_id=ds_id),
page=AsyncPage[Index],
options=make_request_options(
extra_headers=extra_headers,
@@ -325,7 +329,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除索引 Args: ds_id: 数据源 ID index_id: 索引 ID
@@ -344,7 +348,7 @@ async def delete(
if not index_id:
raise ValueError(f"Expected a non-empty value for `index_id` but received {index_id!r}")
return await self._delete(
- f"/v1/datasources/{ds_id}/indexes/{index_id}",
+ path_template("/v1/datasources/{ds_id}/indexes/{index_id}", ds_id=ds_id, index_id=index_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
diff --git a/src/asktable/resources/datasources/meta.py b/src/asktable/resources/datasources/meta.py
index 431f1fba..2ec3655e 100644
--- a/src/asktable/resources/datasources/meta.py
+++ b/src/asktable/resources/datasources/meta.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Dict, List, Optional
+from typing import Dict, Optional
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ..._utils import maybe_transform, async_maybe_transform
+from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from ..._utils import path_template, maybe_transform, async_maybe_transform
from ..._compat import cached_property
from ..._resource import SyncAPIResource, AsyncAPIResource
from ..._response import (
@@ -24,6 +24,8 @@
class MetaResource(SyncAPIResource):
+ """数据源管理"""
+
@cached_property
def with_raw_response(self) -> MetaResourceWithRawResponse:
"""
@@ -47,23 +49,19 @@ def create(
self,
datasource_id: str,
*,
- async_process_meta: bool | NotGiven = NOT_GIVEN,
- value_index: bool | NotGiven = NOT_GIVEN,
- meta: Optional[meta_create_params.Meta] | NotGiven = NOT_GIVEN,
- selected_tables: Optional[Dict[str, List[str]]] | NotGiven = NOT_GIVEN,
+ async_process_meta: bool | Omit = omit,
+ value_index: bool | Omit = omit,
+ meta: Optional[meta_create_params.Meta] | Omit = omit,
+ selected_tables: Optional[Dict[str, SequenceNotStr[str]]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
- 创建数据源的 meta,如果已经存在,则删除旧的
-
- 如果上传了 meta,则使用用户上传的数据创建。
-
- 否则从数据源中自动获取。
+ 初始化数据源的 meta。不允许覆盖已成功初始化的 meta,需使用 PUT 更新。
Args:
extra_headers: Send extra headers
@@ -77,7 +75,7 @@ def create(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._post(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
body=maybe_transform(
{
"meta": meta,
@@ -110,7 +108,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Meta:
"""
从数据源中获取最新的元数据
@@ -127,7 +125,7 @@ def retrieve(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._get(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -138,15 +136,15 @@ def update(
self,
datasource_id: str,
*,
- async_process_meta: bool | NotGiven = NOT_GIVEN,
- meta: Optional[meta_update_params.Meta] | NotGiven = NOT_GIVEN,
- selected_tables: Optional[Dict[str, List[str]]] | NotGiven = NOT_GIVEN,
+ async_process_meta: bool | Omit = omit,
+ meta: Optional[meta_update_params.Meta] | Omit = omit,
+ selected_tables: Optional[Dict[str, SequenceNotStr[str]]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
用于更新 DB 类型的数据源的 Meta(增加新表或者删除老表)
@@ -163,7 +161,7 @@ def update(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._put(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
body=maybe_transform(
{
"meta": meta,
@@ -191,7 +189,7 @@ def annotate(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
修改数据 meta 的描述,用来修改表和字段的备注
@@ -208,7 +206,7 @@ def annotate(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return self._patch(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
body=maybe_transform({"schemas": schemas}, meta_annotate_params.MetaAnnotateParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
@@ -218,6 +216,8 @@ def annotate(
class AsyncMetaResource(AsyncAPIResource):
+ """数据源管理"""
+
@cached_property
def with_raw_response(self) -> AsyncMetaResourceWithRawResponse:
"""
@@ -241,23 +241,19 @@ async def create(
self,
datasource_id: str,
*,
- async_process_meta: bool | NotGiven = NOT_GIVEN,
- value_index: bool | NotGiven = NOT_GIVEN,
- meta: Optional[meta_create_params.Meta] | NotGiven = NOT_GIVEN,
- selected_tables: Optional[Dict[str, List[str]]] | NotGiven = NOT_GIVEN,
+ async_process_meta: bool | Omit = omit,
+ value_index: bool | Omit = omit,
+ meta: Optional[meta_create_params.Meta] | Omit = omit,
+ selected_tables: Optional[Dict[str, SequenceNotStr[str]]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
- 创建数据源的 meta,如果已经存在,则删除旧的
-
- 如果上传了 meta,则使用用户上传的数据创建。
-
- 否则从数据源中自动获取。
+ 初始化数据源的 meta。不允许覆盖已成功初始化的 meta,需使用 PUT 更新。
Args:
extra_headers: Send extra headers
@@ -271,7 +267,7 @@ async def create(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._post(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
body=await async_maybe_transform(
{
"meta": meta,
@@ -304,7 +300,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Meta:
"""
从数据源中获取最新的元数据
@@ -321,7 +317,7 @@ async def retrieve(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._get(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -332,15 +328,15 @@ async def update(
self,
datasource_id: str,
*,
- async_process_meta: bool | NotGiven = NOT_GIVEN,
- meta: Optional[meta_update_params.Meta] | NotGiven = NOT_GIVEN,
- selected_tables: Optional[Dict[str, List[str]]] | NotGiven = NOT_GIVEN,
+ async_process_meta: bool | Omit = omit,
+ meta: Optional[meta_update_params.Meta] | Omit = omit,
+ selected_tables: Optional[Dict[str, SequenceNotStr[str]]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
用于更新 DB 类型的数据源的 Meta(增加新表或者删除老表)
@@ -357,7 +353,7 @@ async def update(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._put(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
body=await async_maybe_transform(
{
"meta": meta,
@@ -387,7 +383,7 @@ async def annotate(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
修改数据 meta 的描述,用来修改表和字段的备注
@@ -404,7 +400,7 @@ async def annotate(
if not datasource_id:
raise ValueError(f"Expected a non-empty value for `datasource_id` but received {datasource_id!r}")
return await self._patch(
- f"/v1/datasources/{datasource_id}/meta",
+ path_template("/v1/datasources/{datasource_id}/meta", datasource_id=datasource_id),
body=await async_maybe_transform({"schemas": schemas}, meta_annotate_params.MetaAnnotateParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
diff --git a/src/asktable/resources/datasources/upload_params.py b/src/asktable/resources/datasources/upload_params.py
index 01578571..7cea2f29 100644
--- a/src/asktable/resources/datasources/upload_params.py
+++ b/src/asktable/resources/datasources/upload_params.py
@@ -6,7 +6,7 @@
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -18,11 +18,14 @@
)
from ..._base_client import make_request_options
from ...types.datasources import upload_param_create_params
+from ...types.datasources.upload_param_create_response import UploadParamCreateResponse
__all__ = ["UploadParamsResource", "AsyncUploadParamsResource"]
class UploadParamsResource(SyncAPIResource):
+ """数据源管理"""
+
@cached_property
def with_raw_response(self) -> UploadParamsResourceWithRawResponse:
"""
@@ -45,15 +48,15 @@ def with_streaming_response(self) -> UploadParamsResourceWithStreamingResponse:
def create(
self,
*,
- expiration: Optional[int] | NotGiven = NOT_GIVEN,
- file_max_size: Optional[int] | NotGiven = NOT_GIVEN,
+ expiration: Optional[int] | Omit = omit,
+ file_max_size: Optional[int] | 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> UploadParamCreateResponse:
"""
获取 OSS 签名参数
@@ -82,11 +85,13 @@ def create(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=UploadParamCreateResponse,
)
class AsyncUploadParamsResource(AsyncAPIResource):
+ """数据源管理"""
+
@cached_property
def with_raw_response(self) -> AsyncUploadParamsResourceWithRawResponse:
"""
@@ -109,15 +114,15 @@ def with_streaming_response(self) -> AsyncUploadParamsResourceWithStreamingRespo
async def create(
self,
*,
- expiration: Optional[int] | NotGiven = NOT_GIVEN,
- file_max_size: Optional[int] | NotGiven = NOT_GIVEN,
+ expiration: Optional[int] | Omit = omit,
+ file_max_size: Optional[int] | 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> UploadParamCreateResponse:
"""
获取 OSS 签名参数
@@ -146,7 +151,7 @@ async def create(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=UploadParamCreateResponse,
)
diff --git a/src/asktable/resources/files.py b/src/asktable/resources/files.py
index 6673a7bf..9c2262d6 100644
--- a/src/asktable/resources/files.py
+++ b/src/asktable/resources/files.py
@@ -4,7 +4,8 @@
import httpx
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+from .._types import Body, Query, Headers, NotGiven, not_given
+from .._utils import path_template
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -19,6 +20,8 @@
class FilesResource(SyncAPIResource):
+ """数据源管理"""
+
@cached_property
def with_raw_response(self) -> FilesResourceWithRawResponse:
"""
@@ -47,10 +50,10 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
- 获取文件
+ 下载文件
Args:
extra_headers: Send extra headers
@@ -64,7 +67,7 @@ def retrieve(
if not file_id:
raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
return self._get(
- f"/v1/files/{file_id}",
+ path_template("/v1/files/{file_id}", file_id=file_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -73,6 +76,8 @@ def retrieve(
class AsyncFilesResource(AsyncAPIResource):
+ """数据源管理"""
+
@cached_property
def with_raw_response(self) -> AsyncFilesResourceWithRawResponse:
"""
@@ -101,10 +106,10 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
- 获取文件
+ 下载文件
Args:
extra_headers: Send extra headers
@@ -118,7 +123,7 @@ async def retrieve(
if not file_id:
raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
return await self._get(
- f"/v1/files/{file_id}",
+ path_template("/v1/files/{file_id}", file_id=file_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
diff --git a/src/asktable/resources/integration.py b/src/asktable/resources/integration.py
index e82d2672..46354ff3 100644
--- a/src/asktable/resources/integration.py
+++ b/src/asktable/resources/integration.py
@@ -7,7 +7,7 @@
import httpx
from ..types import integration_excel_csv_ask_params, integration_create_excel_ds_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -25,6 +25,8 @@
class IntegrationResource(SyncAPIResource):
+ """与第三方平台集成"""
+
@cached_property
def with_raw_response(self) -> IntegrationResourceWithRawResponse:
"""
@@ -48,13 +50,13 @@ def create_excel_ds(
self,
*,
file_url: str,
- value_index: bool | NotGiven = NOT_GIVEN,
+ value_index: 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Datasource:
"""
通过 Excel/CSV 文件 URL 创建数据源
@@ -91,13 +93,13 @@ def excel_csv_ask(
*,
file_url: str,
question: str,
- with_json: Optional[bool] | NotGiven = NOT_GIVEN,
+ with_json: Optional[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> FileAskResponse:
"""
通过 Excel/CSV 文件 URL 添加数据并提问
@@ -135,6 +137,8 @@ def excel_csv_ask(
class AsyncIntegrationResource(AsyncAPIResource):
+ """与第三方平台集成"""
+
@cached_property
def with_raw_response(self) -> AsyncIntegrationResourceWithRawResponse:
"""
@@ -158,13 +162,13 @@ async def create_excel_ds(
self,
*,
file_url: str,
- value_index: bool | NotGiven = NOT_GIVEN,
+ value_index: 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Datasource:
"""
通过 Excel/CSV 文件 URL 创建数据源
@@ -201,13 +205,13 @@ async def excel_csv_ask(
*,
file_url: str,
question: str,
- with_json: Optional[bool] | NotGiven = NOT_GIVEN,
+ with_json: Optional[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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> FileAskResponse:
"""
通过 Excel/CSV 文件 URL 添加数据并提问
diff --git a/src/asktable/resources/policies.py b/src/asktable/resources/policies.py
index fc27f2c4..04ffce4f 100644
--- a/src/asktable/resources/policies.py
+++ b/src/asktable/resources/policies.py
@@ -2,14 +2,14 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import Literal
import httpx
from ..types import policy_list_params, policy_create_params, policy_update_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven
-from .._utils import maybe_transform, async_maybe_transform
+from .._types import Body, Omit, Query, Headers, NoneType, NotGiven, SequenceNotStr, omit, not_given
+from .._utils import path_template, maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -26,6 +26,8 @@
class PoliciesResource(SyncAPIResource):
+ """策略管理"""
+
@cached_property
def with_raw_response(self) -> PoliciesResourceWithRawResponse:
"""
@@ -56,7 +58,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Policy:
"""
定义一个新的策略
@@ -101,7 +103,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Policy:
"""
获取某个策略
@@ -118,7 +120,7 @@ def retrieve(
if not policy_id:
raise ValueError(f"Expected a non-empty value for `policy_id` but received {policy_id!r}")
return self._get(
- f"/v1/policies/{policy_id}",
+ path_template("/v1/policies/{policy_id}", policy_id=policy_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -129,15 +131,15 @@ def update(
self,
policy_id: str,
*,
- dataset_config: Optional[policy_update_params.DatasetConfig] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- permission: Optional[Literal["allow", "deny"]] | NotGiven = NOT_GIVEN,
+ dataset_config: Optional[policy_update_params.DatasetConfig] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ permission: Optional[Literal["allow", "deny"]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Policy:
"""
更新某个策略
@@ -160,7 +162,7 @@ def update(
if not policy_id:
raise ValueError(f"Expected a non-empty value for `policy_id` but received {policy_id!r}")
return self._patch(
- f"/v1/policies/{policy_id}",
+ path_template("/v1/policies/{policy_id}", policy_id=policy_id),
body=maybe_transform(
{
"dataset_config": dataset_config,
@@ -178,16 +180,16 @@ def update(
def list(
self,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- policy_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ policy_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[Policy]:
"""
查询所有策略
@@ -239,7 +241,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
删除某个策略
@@ -257,7 +259,7 @@ def delete(
raise ValueError(f"Expected a non-empty value for `policy_id` but received {policy_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return self._delete(
- f"/v1/policies/{policy_id}",
+ path_template("/v1/policies/{policy_id}", policy_id=policy_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -266,6 +268,8 @@ def delete(
class AsyncPoliciesResource(AsyncAPIResource):
+ """策略管理"""
+
@cached_property
def with_raw_response(self) -> AsyncPoliciesResourceWithRawResponse:
"""
@@ -296,7 +300,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Policy:
"""
定义一个新的策略
@@ -341,7 +345,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Policy:
"""
获取某个策略
@@ -358,7 +362,7 @@ async def retrieve(
if not policy_id:
raise ValueError(f"Expected a non-empty value for `policy_id` but received {policy_id!r}")
return await self._get(
- f"/v1/policies/{policy_id}",
+ path_template("/v1/policies/{policy_id}", policy_id=policy_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -369,15 +373,15 @@ async def update(
self,
policy_id: str,
*,
- dataset_config: Optional[policy_update_params.DatasetConfig] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- permission: Optional[Literal["allow", "deny"]] | NotGiven = NOT_GIVEN,
+ dataset_config: Optional[policy_update_params.DatasetConfig] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ permission: Optional[Literal["allow", "deny"]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Policy:
"""
更新某个策略
@@ -400,7 +404,7 @@ async def update(
if not policy_id:
raise ValueError(f"Expected a non-empty value for `policy_id` but received {policy_id!r}")
return await self._patch(
- f"/v1/policies/{policy_id}",
+ path_template("/v1/policies/{policy_id}", policy_id=policy_id),
body=await async_maybe_transform(
{
"dataset_config": dataset_config,
@@ -418,16 +422,16 @@ async def update(
def list(
self,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- policy_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ policy_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Policy, AsyncPage[Policy]]:
"""
查询所有策略
@@ -479,7 +483,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
删除某个策略
@@ -497,7 +501,7 @@ async def delete(
raise ValueError(f"Expected a non-empty value for `policy_id` but received {policy_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return await self._delete(
- f"/v1/policies/{policy_id}",
+ path_template("/v1/policies/{policy_id}", policy_id=policy_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
diff --git a/src/asktable/resources/polish.py b/src/asktable/resources/polish.py
index 23df7f15..5a51a4c6 100644
--- a/src/asktable/resources/polish.py
+++ b/src/asktable/resources/polish.py
@@ -7,7 +7,7 @@
import httpx
from ..types import polish_create_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -24,6 +24,8 @@
class PolishResource(SyncAPIResource):
+ """润色"""
+
@cached_property
def with_raw_response(self) -> PolishResourceWithRawResponse:
"""
@@ -48,13 +50,13 @@ def create(
*,
max_word_count: int,
user_desc: str,
- polish_mode: Literal[0] | NotGiven = NOT_GIVEN,
+ polish_mode: Literal[0] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PolishCreateResponse:
"""
Polish Table Desc
@@ -92,6 +94,8 @@ def create(
class AsyncPolishResource(AsyncAPIResource):
+ """润色"""
+
@cached_property
def with_raw_response(self) -> AsyncPolishResourceWithRawResponse:
"""
@@ -116,13 +120,13 @@ async def create(
*,
max_word_count: int,
user_desc: str,
- polish_mode: Literal[0] | NotGiven = NOT_GIVEN,
+ polish_mode: Literal[0] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PolishCreateResponse:
"""
Polish Table Desc
diff --git a/src/asktable/resources/preferences.py b/src/asktable/resources/preferences.py
index a96452be..6543b65c 100644
--- a/src/asktable/resources/preferences.py
+++ b/src/asktable/resources/preferences.py
@@ -7,7 +7,7 @@
import httpx
from ..types import preference_create_params, preference_update_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -26,6 +26,8 @@
class PreferencesResource(SyncAPIResource):
+ """偏好设置"""
+
@cached_property
def with_raw_response(self) -> PreferencesResourceWithRawResponse:
"""
@@ -49,13 +51,13 @@ def create(
self,
*,
general_preference: str,
- sql_preference: Optional[str] | NotGiven = NOT_GIVEN,
+ sql_preference: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PreferenceCreateResponse:
"""
创建偏好设置
@@ -96,7 +98,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PreferenceRetrieveResponse:
"""获取偏好设置"""
return self._get(
@@ -110,14 +112,14 @@ def retrieve(
def update(
self,
*,
- general_preference: Optional[str] | NotGiven = NOT_GIVEN,
- sql_preference: Optional[str] | NotGiven = NOT_GIVEN,
+ general_preference: Optional[str] | Omit = omit,
+ sql_preference: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PreferenceUpdateResponse:
"""
更新偏好设置
@@ -158,7 +160,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""删除偏好设置"""
return self._delete(
@@ -171,6 +173,8 @@ def delete(
class AsyncPreferencesResource(AsyncAPIResource):
+ """偏好设置"""
+
@cached_property
def with_raw_response(self) -> AsyncPreferencesResourceWithRawResponse:
"""
@@ -194,13 +198,13 @@ async def create(
self,
*,
general_preference: str,
- sql_preference: Optional[str] | NotGiven = NOT_GIVEN,
+ sql_preference: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PreferenceCreateResponse:
"""
创建偏好设置
@@ -241,7 +245,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PreferenceRetrieveResponse:
"""获取偏好设置"""
return await self._get(
@@ -255,14 +259,14 @@ async def retrieve(
async def update(
self,
*,
- general_preference: Optional[str] | NotGiven = NOT_GIVEN,
- sql_preference: Optional[str] | NotGiven = NOT_GIVEN,
+ general_preference: Optional[str] | Omit = omit,
+ sql_preference: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> PreferenceUpdateResponse:
"""
更新偏好设置
@@ -303,7 +307,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""删除偏好设置"""
return await self._delete(
diff --git a/src/asktable/resources/project.py b/src/asktable/resources/project.py
index 5624ab32..920f2d1c 100644
--- a/src/asktable/resources/project.py
+++ b/src/asktable/resources/project.py
@@ -7,7 +7,7 @@
import httpx
from ..types import project_update_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -25,6 +25,8 @@
class ProjectResource(SyncAPIResource):
+ """我的项目"""
+
@cached_property
def with_raw_response(self) -> ProjectResourceWithRawResponse:
"""
@@ -52,7 +54,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""Get My Project"""
return self._get(
@@ -66,14 +68,14 @@ def retrieve(
def update(
self,
*,
- llm_model_group: Optional[str] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ llm_model_group: Optional[str] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Update My Project
@@ -114,7 +116,7 @@ def list_model_groups(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ProjectListModelGroupsResponse:
"""Get Llm Model Groups"""
return self._get(
@@ -127,6 +129,8 @@ def list_model_groups(
class AsyncProjectResource(AsyncAPIResource):
+ """我的项目"""
+
@cached_property
def with_raw_response(self) -> AsyncProjectResourceWithRawResponse:
"""
@@ -154,7 +158,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""Get My Project"""
return await self._get(
@@ -168,14 +172,14 @@ async def retrieve(
async def update(
self,
*,
- llm_model_group: Optional[str] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ llm_model_group: Optional[str] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Update My Project
@@ -216,7 +220,7 @@ async def list_model_groups(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ProjectListModelGroupsResponse:
"""Get Llm Model Groups"""
return await self._get(
diff --git a/src/asktable/resources/roles.py b/src/asktable/resources/roles.py
index c05f9a91..fa4754bc 100644
--- a/src/asktable/resources/roles.py
+++ b/src/asktable/resources/roles.py
@@ -2,13 +2,13 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
import httpx
from ..types import role_list_params, role_create_params, role_update_params, role_get_variables_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from .._utils import maybe_transform, async_maybe_transform
+from .._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from .._utils import path_template, maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -21,11 +21,14 @@
from ..types.role import Role
from .._base_client import AsyncPaginator, make_request_options
from ..types.role_get_polices_response import RoleGetPolicesResponse
+from ..types.role_get_variables_response import RoleGetVariablesResponse
__all__ = ["RolesResource", "AsyncRolesResource"]
class RolesResource(SyncAPIResource):
+ """角色管理"""
+
@cached_property
def with_raw_response(self) -> RolesResourceWithRawResponse:
"""
@@ -49,13 +52,13 @@ def create(
self,
*,
name: str,
- policy_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
+ policy_ids: Optional[SequenceNotStr[str]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Role:
"""
创建一个新的角色
@@ -97,7 +100,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Role:
"""
获取某个角色
@@ -114,7 +117,7 @@ def retrieve(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return self._get(
- f"/v1/roles/{role_id}",
+ path_template("/v1/roles/{role_id}", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -125,14 +128,14 @@ def update(
self,
role_id: str,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- policy_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ policy_ids: Optional[SequenceNotStr[str]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Role:
"""
更新某个角色
@@ -153,7 +156,7 @@ def update(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return self._patch(
- f"/v1/roles/{role_id}",
+ path_template("/v1/roles/{role_id}", role_id=role_id),
body=maybe_transform(
{
"name": name,
@@ -170,16 +173,16 @@ def update(
def list(
self,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- role_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ role_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[Role]:
"""
查询所有的角色
@@ -231,7 +234,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除某个角色
@@ -248,7 +251,7 @@ def delete(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return self._delete(
- f"/v1/roles/{role_id}",
+ path_template("/v1/roles/{role_id}", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -264,7 +267,7 @@ def get_polices(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> RoleGetPolicesResponse:
"""
查询某个角色的所有策略
@@ -281,7 +284,7 @@ def get_polices(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return self._get(
- f"/v1/roles/{role_id}/policies",
+ path_template("/v1/roles/{role_id}/policies", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -292,15 +295,15 @@ def get_variables(
self,
role_id: str,
*,
- bot_id: Optional[str] | NotGiven = NOT_GIVEN,
- datasource_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
+ bot_id: Optional[str] | Omit = omit,
+ datasource_ids: Optional[SequenceNotStr[str]] | 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> RoleGetVariablesResponse:
"""
查询某个角色的所有变量
@@ -320,7 +323,7 @@ def get_variables(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return self._get(
- f"/v1/roles/{role_id}/variables",
+ path_template("/v1/roles/{role_id}/variables", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -334,11 +337,13 @@ def get_variables(
role_get_variables_params.RoleGetVariablesParams,
),
),
- cast_to=object,
+ cast_to=RoleGetVariablesResponse,
)
class AsyncRolesResource(AsyncAPIResource):
+ """角色管理"""
+
@cached_property
def with_raw_response(self) -> AsyncRolesResourceWithRawResponse:
"""
@@ -362,13 +367,13 @@ async def create(
self,
*,
name: str,
- policy_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
+ policy_ids: Optional[SequenceNotStr[str]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Role:
"""
创建一个新的角色
@@ -410,7 +415,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Role:
"""
获取某个角色
@@ -427,7 +432,7 @@ async def retrieve(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return await self._get(
- f"/v1/roles/{role_id}",
+ path_template("/v1/roles/{role_id}", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -438,14 +443,14 @@ async def update(
self,
role_id: str,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- policy_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ policy_ids: Optional[SequenceNotStr[str]] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Role:
"""
更新某个角色
@@ -466,7 +471,7 @@ async def update(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return await self._patch(
- f"/v1/roles/{role_id}",
+ path_template("/v1/roles/{role_id}", role_id=role_id),
body=await async_maybe_transform(
{
"name": name,
@@ -483,16 +488,16 @@ async def update(
def list(
self,
*,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- role_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ name: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ role_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Role, AsyncPage[Role]]:
"""
查询所有的角色
@@ -544,7 +549,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
删除某个角色
@@ -561,7 +566,7 @@ async def delete(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return await self._delete(
- f"/v1/roles/{role_id}",
+ path_template("/v1/roles/{role_id}", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -577,7 +582,7 @@ async def get_polices(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> RoleGetPolicesResponse:
"""
查询某个角色的所有策略
@@ -594,7 +599,7 @@ async def get_polices(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return await self._get(
- f"/v1/roles/{role_id}/policies",
+ path_template("/v1/roles/{role_id}/policies", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -605,15 +610,15 @@ async def get_variables(
self,
role_id: str,
*,
- bot_id: Optional[str] | NotGiven = NOT_GIVEN,
- datasource_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
+ bot_id: Optional[str] | Omit = omit,
+ datasource_ids: Optional[SequenceNotStr[str]] | 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> RoleGetVariablesResponse:
"""
查询某个角色的所有变量
@@ -633,7 +638,7 @@ async def get_variables(
if not role_id:
raise ValueError(f"Expected a non-empty value for `role_id` but received {role_id!r}")
return await self._get(
- f"/v1/roles/{role_id}/variables",
+ path_template("/v1/roles/{role_id}/variables", role_id=role_id),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
@@ -647,7 +652,7 @@ async def get_variables(
role_get_variables_params.RoleGetVariablesParams,
),
),
- cast_to=object,
+ cast_to=RoleGetVariablesResponse,
)
diff --git a/src/asktable/resources/scores.py b/src/asktable/resources/scores.py
index 343a17e8..8c62c017 100644
--- a/src/asktable/resources/scores.py
+++ b/src/asktable/resources/scores.py
@@ -5,7 +5,7 @@
import httpx
from ..types import score_create_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -22,6 +22,8 @@
class ScoresResource(SyncAPIResource):
+ """评分"""
+
@cached_property
def with_raw_response(self) -> ScoresResourceWithRawResponse:
"""
@@ -52,7 +54,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ScoreCreateResponse:
"""
Score
@@ -93,6 +95,8 @@ def create(
class AsyncScoresResource(AsyncAPIResource):
+ """评分"""
+
@cached_property
def with_raw_response(self) -> AsyncScoresResourceWithRawResponse:
"""
@@ -123,7 +127,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ScoreCreateResponse:
"""
Score
diff --git a/src/asktable/resources/securetunnels.py b/src/asktable/resources/securetunnels.py
index 13476a28..42ecaf08 100644
--- a/src/asktable/resources/securetunnels.py
+++ b/src/asktable/resources/securetunnels.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
import httpx
@@ -12,8 +12,8 @@
securetunnel_update_params,
securetunnel_list_links_params,
)
-from .._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven
-from .._utils import maybe_transform, async_maybe_transform
+from .._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given
+from .._utils import path_template, maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
@@ -31,6 +31,8 @@
class SecuretunnelsResource(SyncAPIResource):
+ """安全隧道"""
+
@cached_property
def with_raw_response(self) -> SecuretunnelsResourceWithRawResponse:
"""
@@ -59,7 +61,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SecureTunnel:
"""
创建安全隧道
@@ -93,7 +95,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SecureTunnel:
"""
获取某个 ATST
@@ -110,7 +112,7 @@ def retrieve(
if not securetunnel_id:
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
return self._get(
- f"/v1/securetunnels/{securetunnel_id}",
+ path_template("/v1/securetunnels/{securetunnel_id}", securetunnel_id=securetunnel_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -121,15 +123,15 @@ def update(
self,
securetunnel_id: str,
*,
- client_info: Optional[object] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- unique_key: Optional[str] | NotGiven = NOT_GIVEN,
+ client_info: Optional[Dict[str, object]] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ unique_key: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SecureTunnel:
"""
更新某个 ATST
@@ -152,7 +154,7 @@ def update(
if not securetunnel_id:
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
return self._patch(
- f"/v1/securetunnels/{securetunnel_id}",
+ path_template("/v1/securetunnels/{securetunnel_id}", securetunnel_id=securetunnel_id),
body=maybe_transform(
{
"client_info": client_info,
@@ -170,14 +172,14 @@ def update(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[SecureTunnel]:
"""
查询安全隧道列表
@@ -223,7 +225,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
删除某个 ATST
@@ -241,7 +243,7 @@ def delete(
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return self._delete(
- f"/v1/securetunnels/{securetunnel_id}",
+ path_template("/v1/securetunnels/{securetunnel_id}", securetunnel_id=securetunnel_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -252,14 +254,14 @@ def list_links(
self,
securetunnel_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[SecuretunnelListLinksResponse]:
"""
查询安全隧道的所有 Link
@@ -280,7 +282,7 @@ def list_links(
if not securetunnel_id:
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
return self._get_api_list(
- f"/v1/securetunnels/{securetunnel_id}/links",
+ path_template("/v1/securetunnels/{securetunnel_id}/links", securetunnel_id=securetunnel_id),
page=SyncPage[SecuretunnelListLinksResponse],
options=make_request_options(
extra_headers=extra_headers,
@@ -300,6 +302,8 @@ def list_links(
class AsyncSecuretunnelsResource(AsyncAPIResource):
+ """安全隧道"""
+
@cached_property
def with_raw_response(self) -> AsyncSecuretunnelsResourceWithRawResponse:
"""
@@ -328,7 +332,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SecureTunnel:
"""
创建安全隧道
@@ -362,7 +366,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SecureTunnel:
"""
获取某个 ATST
@@ -379,7 +383,7 @@ async def retrieve(
if not securetunnel_id:
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
return await self._get(
- f"/v1/securetunnels/{securetunnel_id}",
+ path_template("/v1/securetunnels/{securetunnel_id}", securetunnel_id=securetunnel_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -390,15 +394,15 @@ async def update(
self,
securetunnel_id: str,
*,
- client_info: Optional[object] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
- unique_key: Optional[str] | NotGiven = NOT_GIVEN,
+ client_info: Optional[Dict[str, object]] | Omit = omit,
+ name: Optional[str] | Omit = omit,
+ unique_key: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SecureTunnel:
"""
更新某个 ATST
@@ -421,7 +425,7 @@ async def update(
if not securetunnel_id:
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
return await self._patch(
- f"/v1/securetunnels/{securetunnel_id}",
+ path_template("/v1/securetunnels/{securetunnel_id}", securetunnel_id=securetunnel_id),
body=await async_maybe_transform(
{
"client_info": client_info,
@@ -439,14 +443,14 @@ async def update(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[SecureTunnel, AsyncPage[SecureTunnel]]:
"""
查询安全隧道列表
@@ -492,7 +496,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
删除某个 ATST
@@ -510,7 +514,7 @@ async def delete(
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return await self._delete(
- f"/v1/securetunnels/{securetunnel_id}",
+ path_template("/v1/securetunnels/{securetunnel_id}", securetunnel_id=securetunnel_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -521,14 +525,14 @@ def list_links(
self,
securetunnel_id: str,
*,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[SecuretunnelListLinksResponse, AsyncPage[SecuretunnelListLinksResponse]]:
"""
查询安全隧道的所有 Link
@@ -549,7 +553,7 @@ def list_links(
if not securetunnel_id:
raise ValueError(f"Expected a non-empty value for `securetunnel_id` but received {securetunnel_id!r}")
return self._get_api_list(
- f"/v1/securetunnels/{securetunnel_id}/links",
+ path_template("/v1/securetunnels/{securetunnel_id}/links", securetunnel_id=securetunnel_id),
page=AsyncPage[SecuretunnelListLinksResponse],
options=make_request_options(
extra_headers=extra_headers,
diff --git a/src/asktable/resources/sqls.py b/src/asktable/resources/sqls.py
index fc871c84..502e47d2 100644
--- a/src/asktable/resources/sqls.py
+++ b/src/asktable/resources/sqls.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
import httpx
from ..types import sql_list_params, sql_create_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -25,6 +25,8 @@
class SqlsResource(SyncAPIResource):
+ """单轮对话"""
+
@cached_property
def with_raw_response(self) -> SqlsResourceWithRawResponse:
"""
@@ -49,15 +51,15 @@ def create(
*,
datasource_id: str,
question: str,
- parameterize: bool | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
+ parameterize: bool | Omit = omit,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> QueryResponse:
"""
发起生成 sql 的请求
@@ -103,15 +105,15 @@ def create(
def list(
self,
*,
- datasource_id: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ datasource_id: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[QueryResponse]:
"""
获取所有的 Q2S 记录
@@ -153,6 +155,8 @@ def list(
class AsyncSqlsResource(AsyncAPIResource):
+ """单轮对话"""
+
@cached_property
def with_raw_response(self) -> AsyncSqlsResourceWithRawResponse:
"""
@@ -177,15 +181,15 @@ async def create(
*,
datasource_id: str,
question: str,
- parameterize: bool | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- role_variables: Optional[object] | NotGiven = NOT_GIVEN,
+ parameterize: bool | Omit = omit,
+ role_id: Optional[str] | Omit = omit,
+ role_variables: Optional[Dict[str, 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> QueryResponse:
"""
发起生成 sql 的请求
@@ -231,15 +235,15 @@ async def create(
def list(
self,
*,
- datasource_id: Optional[str] | NotGiven = NOT_GIVEN,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ datasource_id: Optional[str] | Omit = omit,
+ page: int | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[QueryResponse, AsyncPage[QueryResponse]]:
"""
获取所有的 Q2S 记录
diff --git a/src/asktable/resources/sys/projects/api_keys.py b/src/asktable/resources/sys/projects/api_keys.py
index 4b17a377..f0f75750 100644
--- a/src/asktable/resources/sys/projects/api_keys.py
+++ b/src/asktable/resources/sys/projects/api_keys.py
@@ -2,13 +2,13 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Literal
import httpx
-from ...._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven
-from ...._utils import maybe_transform, async_maybe_transform
+from ...._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given
+from ...._utils import path_template, maybe_transform, async_maybe_transform
from ...._compat import cached_property
from ...._resource import SyncAPIResource, AsyncAPIResource
from ...._response import (
@@ -21,11 +21,14 @@
from ....types.sys.projects import api_key_create_params, api_key_create_token_params
from ....types.sys.projects.api_key_list_response import APIKeyListResponse
from ....types.sys.projects.api_key_create_response import APIKeyCreateResponse
+from ....types.sys.projects.api_key_create_token_response import APIKeyCreateTokenResponse
__all__ = ["APIKeysResource", "AsyncAPIKeysResource"]
class APIKeysResource(SyncAPIResource):
+ """系统管理"""
+
@cached_property
def with_raw_response(self) -> APIKeysResourceWithRawResponse:
"""
@@ -55,7 +58,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> APIKeyCreateResponse:
"""
创建 API Key
@@ -74,7 +77,7 @@ def create(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._post(
- f"/v1/sys/projects/{project_id}/api-keys",
+ path_template("/v1/sys/projects/{project_id}/api-keys", project_id=project_id),
body=maybe_transform({"ak_role": ak_role}, api_key_create_params.APIKeyCreateParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
@@ -91,7 +94,7 @@ def list(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> APIKeyListResponse:
"""
List Api Keys
@@ -108,7 +111,7 @@ def list(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._get(
- f"/v1/sys/projects/{project_id}/api-keys",
+ path_template("/v1/sys/projects/{project_id}/api-keys", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -125,7 +128,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
Delete Api Key View
@@ -145,7 +148,7 @@ def delete(
raise ValueError(f"Expected a non-empty value for `key_id` but received {key_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return self._delete(
- f"/v1/sys/projects/{project_id}/api-keys/{key_id}",
+ path_template("/v1/sys/projects/{project_id}/api-keys/{key_id}", project_id=project_id, key_id=key_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -156,17 +159,17 @@ def create_token(
self,
project_id: str,
*,
- ak_role: Literal["sys", "admin", "asker", "visitor"] | NotGiven = NOT_GIVEN,
- chat_role: Optional[api_key_create_token_params.ChatRole] | NotGiven = NOT_GIVEN,
- token_ttl: int | NotGiven = NOT_GIVEN,
- user_profile: Optional[object] | NotGiven = NOT_GIVEN,
+ ak_role: Literal["sys", "admin", "asker", "visitor"] | Omit = omit,
+ chat_role: Optional[api_key_create_token_params.ChatRole] | Omit = omit,
+ token_ttl: int | Omit = omit,
+ user_profile: Optional[Dict[str, 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> APIKeyCreateTokenResponse:
"""
Create Token
@@ -190,7 +193,7 @@ def create_token(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._post(
- f"/v1/sys/projects/{project_id}/tokens",
+ path_template("/v1/sys/projects/{project_id}/tokens", project_id=project_id),
body=maybe_transform(
{
"ak_role": ak_role,
@@ -203,11 +206,13 @@ def create_token(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=APIKeyCreateTokenResponse,
)
class AsyncAPIKeysResource(AsyncAPIResource):
+ """系统管理"""
+
@cached_property
def with_raw_response(self) -> AsyncAPIKeysResourceWithRawResponse:
"""
@@ -237,7 +242,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> APIKeyCreateResponse:
"""
创建 API Key
@@ -256,7 +261,7 @@ async def create(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._post(
- f"/v1/sys/projects/{project_id}/api-keys",
+ path_template("/v1/sys/projects/{project_id}/api-keys", project_id=project_id),
body=await async_maybe_transform({"ak_role": ak_role}, api_key_create_params.APIKeyCreateParams),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
@@ -273,7 +278,7 @@ async def list(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> APIKeyListResponse:
"""
List Api Keys
@@ -290,7 +295,7 @@ async def list(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._get(
- f"/v1/sys/projects/{project_id}/api-keys",
+ path_template("/v1/sys/projects/{project_id}/api-keys", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -307,7 +312,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
Delete Api Key View
@@ -327,7 +332,7 @@ async def delete(
raise ValueError(f"Expected a non-empty value for `key_id` but received {key_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return await self._delete(
- f"/v1/sys/projects/{project_id}/api-keys/{key_id}",
+ path_template("/v1/sys/projects/{project_id}/api-keys/{key_id}", project_id=project_id, key_id=key_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -338,17 +343,17 @@ async def create_token(
self,
project_id: str,
*,
- ak_role: Literal["sys", "admin", "asker", "visitor"] | NotGiven = NOT_GIVEN,
- chat_role: Optional[api_key_create_token_params.ChatRole] | NotGiven = NOT_GIVEN,
- token_ttl: int | NotGiven = NOT_GIVEN,
- user_profile: Optional[object] | NotGiven = NOT_GIVEN,
+ ak_role: Literal["sys", "admin", "asker", "visitor"] | Omit = omit,
+ chat_role: Optional[api_key_create_token_params.ChatRole] | Omit = omit,
+ token_ttl: int | Omit = omit,
+ user_profile: Optional[Dict[str, 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,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> APIKeyCreateTokenResponse:
"""
Create Token
@@ -372,7 +377,7 @@ async def create_token(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._post(
- f"/v1/sys/projects/{project_id}/tokens",
+ path_template("/v1/sys/projects/{project_id}/tokens", project_id=project_id),
body=await async_maybe_transform(
{
"ak_role": ak_role,
@@ -385,7 +390,7 @@ async def create_token(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=APIKeyCreateTokenResponse,
)
diff --git a/src/asktable/resources/sys/projects/projects.py b/src/asktable/resources/sys/projects/projects.py
index 6c7c5f13..c948a0e3 100644
--- a/src/asktable/resources/sys/projects/projects.py
+++ b/src/asktable/resources/sys/projects/projects.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Dict, Optional
import httpx
@@ -14,8 +14,8 @@
APIKeysResourceWithStreamingResponse,
AsyncAPIKeysResourceWithStreamingResponse,
)
-from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-from ...._utils import maybe_transform, async_maybe_transform
+from ...._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
+from ...._utils import path_template, maybe_transform, async_maybe_transform
from ...._compat import cached_property
from ...._resource import SyncAPIResource, AsyncAPIResource
from ...._response import (
@@ -28,14 +28,19 @@
from ....pagination import SyncPage, AsyncPage
from ...._base_client import AsyncPaginator, make_request_options
from ....types.sys.project import Project
+from ....types.sys.project_export_response import ProjectExportResponse
+from ....types.sys.project_import_response import ProjectImportResponse
from ....types.sys.project_model_groups_response import ProjectModelGroupsResponse
__all__ = ["ProjectsResource", "AsyncProjectsResource"]
class ProjectsResource(SyncAPIResource):
+ """系统管理"""
+
@cached_property
def api_keys(self) -> APIKeysResource:
+ """系统管理"""
return APIKeysResource(self._client)
@cached_property
@@ -66,7 +71,7 @@ def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Create New Project
@@ -100,7 +105,7 @@ def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Get Project
@@ -117,7 +122,7 @@ def retrieve(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._get(
- f"/v1/sys/projects/{project_id}",
+ path_template("/v1/sys/projects/{project_id}", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -128,15 +133,15 @@ def update(
self,
project_id: str,
*,
- llm_model_group: Optional[str] | NotGiven = NOT_GIVEN,
- locked: Optional[bool] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ llm_model_group: Optional[str] | Omit = omit,
+ locked: Optional[bool] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Update Project
@@ -159,7 +164,7 @@ def update(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._patch(
- f"/v1/sys/projects/{project_id}",
+ path_template("/v1/sys/projects/{project_id}", project_id=project_id),
body=maybe_transform(
{
"llm_model_group": llm_model_group,
@@ -177,15 +182,15 @@ def update(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- project_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ project_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncPage[Project]:
"""
Get Projects
@@ -234,7 +239,7 @@ def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
Delete Project
@@ -251,7 +256,7 @@ def delete(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._delete(
- f"/v1/sys/projects/{project_id}",
+ path_template("/v1/sys/projects/{project_id}", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -267,8 +272,8 @@ def export(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ProjectExportResponse:
"""
Export Project
@@ -284,24 +289,24 @@ def export(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return self._post(
- f"/v1/sys/projects/{project_id}/export",
+ path_template("/v1/sys/projects/{project_id}/export", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=ProjectExportResponse,
)
def import_(
self,
*,
- body: object,
+ body: 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:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ProjectImportResponse:
"""
Import Project
@@ -320,7 +325,7 @@ def import_(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=ProjectImportResponse,
)
def model_groups(
@@ -331,9 +336,9 @@ def model_groups(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ProjectModelGroupsResponse:
- """Get Llm Model Groups"""
+ """Get Model Groups"""
return self._get(
"/v1/sys/projects/model-groups",
options=make_request_options(
@@ -344,8 +349,11 @@ def model_groups(
class AsyncProjectsResource(AsyncAPIResource):
+ """系统管理"""
+
@cached_property
def api_keys(self) -> AsyncAPIKeysResource:
+ """系统管理"""
return AsyncAPIKeysResource(self._client)
@cached_property
@@ -376,7 +384,7 @@ async def create(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Create New Project
@@ -410,7 +418,7 @@ async def retrieve(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Get Project
@@ -427,7 +435,7 @@ async def retrieve(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._get(
- f"/v1/sys/projects/{project_id}",
+ path_template("/v1/sys/projects/{project_id}", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -438,15 +446,15 @@ async def update(
self,
project_id: str,
*,
- llm_model_group: Optional[str] | NotGiven = NOT_GIVEN,
- locked: Optional[bool] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ llm_model_group: Optional[str] | Omit = omit,
+ locked: Optional[bool] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Update Project
@@ -469,7 +477,7 @@ async def update(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._patch(
- f"/v1/sys/projects/{project_id}",
+ path_template("/v1/sys/projects/{project_id}", project_id=project_id),
body=await async_maybe_transform(
{
"llm_model_group": llm_model_group,
@@ -487,15 +495,15 @@ async def update(
def list(
self,
*,
- page: int | NotGiven = NOT_GIVEN,
- project_ids: Optional[List[str]] | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
+ page: int | Omit = omit,
+ project_ids: Optional[SequenceNotStr[str]] | Omit = omit,
+ size: int | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Project, AsyncPage[Project]]:
"""
Get Projects
@@ -544,7 +552,7 @@ async def delete(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> object:
"""
Delete Project
@@ -561,7 +569,7 @@ async def delete(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._delete(
- f"/v1/sys/projects/{project_id}",
+ path_template("/v1/sys/projects/{project_id}", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
@@ -577,8 +585,8 @@ async def export(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
- ) -> object:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ProjectExportResponse:
"""
Export Project
@@ -594,24 +602,24 @@ async def export(
if not project_id:
raise ValueError(f"Expected a non-empty value for `project_id` but received {project_id!r}")
return await self._post(
- f"/v1/sys/projects/{project_id}/export",
+ path_template("/v1/sys/projects/{project_id}/export", project_id=project_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=ProjectExportResponse,
)
async def import_(
self,
*,
- body: object,
+ body: 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:
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
+ ) -> ProjectImportResponse:
"""
Import Project
@@ -630,7 +638,7 @@ async def import_(
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
- cast_to=object,
+ cast_to=ProjectImportResponse,
)
async def model_groups(
@@ -641,9 +649,9 @@ async def model_groups(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ProjectModelGroupsResponse:
- """Get Llm Model Groups"""
+ """Get Model Groups"""
return await self._get(
"/v1/sys/projects/model-groups",
options=make_request_options(
@@ -684,6 +692,7 @@ def __init__(self, projects: ProjectsResource) -> None:
@cached_property
def api_keys(self) -> APIKeysResourceWithRawResponse:
+ """系统管理"""
return APIKeysResourceWithRawResponse(self._projects.api_keys)
@@ -718,6 +727,7 @@ def __init__(self, projects: AsyncProjectsResource) -> None:
@cached_property
def api_keys(self) -> AsyncAPIKeysResourceWithRawResponse:
+ """系统管理"""
return AsyncAPIKeysResourceWithRawResponse(self._projects.api_keys)
@@ -752,6 +762,7 @@ def __init__(self, projects: ProjectsResource) -> None:
@cached_property
def api_keys(self) -> APIKeysResourceWithStreamingResponse:
+ """系统管理"""
return APIKeysResourceWithStreamingResponse(self._projects.api_keys)
@@ -786,4 +797,5 @@ def __init__(self, projects: AsyncProjectsResource) -> None:
@cached_property
def api_keys(self) -> AsyncAPIKeysResourceWithStreamingResponse:
+ """系统管理"""
return AsyncAPIKeysResourceWithStreamingResponse(self._projects.api_keys)
diff --git a/src/asktable/resources/sys/sys.py b/src/asktable/resources/sys/sys.py
index 3ab1213c..9352d837 100644
--- a/src/asktable/resources/sys/sys.py
+++ b/src/asktable/resources/sys/sys.py
@@ -2,22 +2,8 @@
from __future__ import annotations
-from typing import Optional
-
-import httpx
-
-from ...types import sy_update_config_params
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-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 .projects.projects import (
ProjectsResource,
AsyncProjectsResource,
@@ -26,7 +12,6 @@
ProjectsResourceWithStreamingResponse,
AsyncProjectsResourceWithStreamingResponse,
)
-from ...types.sy_update_config_response import SyUpdateConfigResponse
__all__ = ["SysResource", "AsyncSysResource"]
@@ -34,6 +19,7 @@
class SysResource(SyncAPIResource):
@cached_property
def projects(self) -> ProjectsResource:
+ """系统管理"""
return ProjectsResource(self._client)
@cached_property
@@ -55,46 +41,11 @@ def with_streaming_response(self) -> SysResourceWithStreamingResponse:
"""
return SysResourceWithStreamingResponse(self)
- def update_config(
- self,
- *,
- global_table_limit: Optional[int] | NotGiven = NOT_GIVEN,
- # 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,
- ) -> SyUpdateConfigResponse:
- """
- Update Config
-
- Args:
- global_table_limit: 表限制数量
-
- 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._patch(
- "/v1/sys/config",
- body=maybe_transform(
- {"global_table_limit": global_table_limit}, sy_update_config_params.SyUpdateConfigParams
- ),
- options=make_request_options(
- extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
- ),
- cast_to=SyUpdateConfigResponse,
- )
-
class AsyncSysResource(AsyncAPIResource):
@cached_property
def projects(self) -> AsyncProjectsResource:
+ """系统管理"""
return AsyncProjectsResource(self._client)
@cached_property
@@ -116,53 +67,14 @@ def with_streaming_response(self) -> AsyncSysResourceWithStreamingResponse:
"""
return AsyncSysResourceWithStreamingResponse(self)
- async def update_config(
- self,
- *,
- global_table_limit: Optional[int] | NotGiven = NOT_GIVEN,
- # 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,
- ) -> SyUpdateConfigResponse:
- """
- Update Config
-
- Args:
- global_table_limit: 表限制数量
-
- 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._patch(
- "/v1/sys/config",
- body=await async_maybe_transform(
- {"global_table_limit": global_table_limit}, sy_update_config_params.SyUpdateConfigParams
- ),
- options=make_request_options(
- extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
- ),
- cast_to=SyUpdateConfigResponse,
- )
-
class SysResourceWithRawResponse:
def __init__(self, sys: SysResource) -> None:
self._sys = sys
- self.update_config = to_raw_response_wrapper(
- sys.update_config,
- )
-
@cached_property
def projects(self) -> ProjectsResourceWithRawResponse:
+ """系统管理"""
return ProjectsResourceWithRawResponse(self._sys.projects)
@@ -170,12 +82,9 @@ class AsyncSysResourceWithRawResponse:
def __init__(self, sys: AsyncSysResource) -> None:
self._sys = sys
- self.update_config = async_to_raw_response_wrapper(
- sys.update_config,
- )
-
@cached_property
def projects(self) -> AsyncProjectsResourceWithRawResponse:
+ """系统管理"""
return AsyncProjectsResourceWithRawResponse(self._sys.projects)
@@ -183,12 +92,9 @@ class SysResourceWithStreamingResponse:
def __init__(self, sys: SysResource) -> None:
self._sys = sys
- self.update_config = to_streamed_response_wrapper(
- sys.update_config,
- )
-
@cached_property
def projects(self) -> ProjectsResourceWithStreamingResponse:
+ """系统管理"""
return ProjectsResourceWithStreamingResponse(self._sys.projects)
@@ -196,10 +102,7 @@ class AsyncSysResourceWithStreamingResponse:
def __init__(self, sys: AsyncSysResource) -> None:
self._sys = sys
- self.update_config = async_to_streamed_response_wrapper(
- sys.update_config,
- )
-
@cached_property
def projects(self) -> AsyncProjectsResourceWithStreamingResponse:
+ """系统管理"""
return AsyncProjectsResourceWithStreamingResponse(self._sys.projects)
diff --git a/src/asktable/resources/trainings.py b/src/asktable/resources/trainings.py
deleted file mode 100644
index 98882a5c..00000000
--- a/src/asktable/resources/trainings.py
+++ /dev/null
@@ -1,528 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing import Iterable, Optional
-
-import httpx
-
-from ..types import training_list_params, training_create_params, training_delete_params, training_update_params
-from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
-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 ..pagination import SyncPage, AsyncPage
-from .._base_client import AsyncPaginator, make_request_options
-from ..types.training_list_response import TrainingListResponse
-from ..types.training_create_response import TrainingCreateResponse
-from ..types.training_update_response import TrainingUpdateResponse
-
-__all__ = ["TrainingsResource", "AsyncTrainingsResource"]
-
-
-class TrainingsResource(SyncAPIResource):
- @cached_property
- def with_raw_response(self) -> TrainingsResourceWithRawResponse:
- """
- 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/DataMini/asktable-python#accessing-raw-response-data-eg-headers
- """
- return TrainingsResourceWithRawResponse(self)
-
- @cached_property
- def with_streaming_response(self) -> TrainingsResourceWithStreamingResponse:
- """
- An alternative to `.with_raw_response` that doesn't eagerly read the response body.
-
- For more information, see https://www.github.com/DataMini/asktable-python#with_streaming_response
- """
- return TrainingsResourceWithStreamingResponse(self)
-
- def create(
- self,
- *,
- datasource_id: str,
- body: Iterable[training_create_params.Body],
- # 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,
- ) -> TrainingCreateResponse:
- """
- Create Training Pair
-
- Args:
- datasource_id: 数据源 ID
-
- 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(
- "/v1/training",
- body=maybe_transform(body, Iterable[training_create_params.Body]),
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=maybe_transform({"datasource_id": datasource_id}, training_create_params.TrainingCreateParams),
- ),
- cast_to=TrainingCreateResponse,
- )
-
- def update(
- self,
- id: str,
- *,
- datasource_id: str,
- active: Optional[bool] | NotGiven = NOT_GIVEN,
- question: Optional[str] | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- sql: Optional[str] | NotGiven = NOT_GIVEN,
- # 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,
- ) -> TrainingUpdateResponse:
- """
- Update Training Pair
-
- Args:
- datasource_id: 数据源 ID
-
- active: 是否启用
-
- question: 用户问题
-
- role_id: 角色 ID
-
- sql: 用户问题对应的 SQL
-
- 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 id:
- raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
- return self._patch(
- f"/v1/training/{id}",
- body=maybe_transform(
- {
- "active": active,
- "question": question,
- "role_id": role_id,
- "sql": sql,
- },
- training_update_params.TrainingUpdateParams,
- ),
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=maybe_transform({"datasource_id": datasource_id}, training_update_params.TrainingUpdateParams),
- ),
- cast_to=TrainingUpdateResponse,
- )
-
- def list(
- self,
- *,
- datasource_id: str,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
- # 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,
- ) -> SyncPage[TrainingListResponse]:
- """
- Get Training Pairs
-
- Args:
- datasource_id: 数据源 ID
-
- page: Page number
-
- size: Page size
-
- 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_api_list(
- "/v1/training",
- page=SyncPage[TrainingListResponse],
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=maybe_transform(
- {
- "datasource_id": datasource_id,
- "page": page,
- "size": size,
- },
- training_list_params.TrainingListParams,
- ),
- ),
- model=TrainingListResponse,
- )
-
- def delete(
- self,
- id: str,
- *,
- datasource_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,
- ) -> object:
- """
- Delete Training Pair
-
- Args:
- datasource_id: 数据源 ID
-
- 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 id:
- raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
- return self._delete(
- f"/v1/training/{id}",
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=maybe_transform({"datasource_id": datasource_id}, training_delete_params.TrainingDeleteParams),
- ),
- cast_to=object,
- )
-
-
-class AsyncTrainingsResource(AsyncAPIResource):
- @cached_property
- def with_raw_response(self) -> AsyncTrainingsResourceWithRawResponse:
- """
- 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/DataMini/asktable-python#accessing-raw-response-data-eg-headers
- """
- return AsyncTrainingsResourceWithRawResponse(self)
-
- @cached_property
- def with_streaming_response(self) -> AsyncTrainingsResourceWithStreamingResponse:
- """
- An alternative to `.with_raw_response` that doesn't eagerly read the response body.
-
- For more information, see https://www.github.com/DataMini/asktable-python#with_streaming_response
- """
- return AsyncTrainingsResourceWithStreamingResponse(self)
-
- async def create(
- self,
- *,
- datasource_id: str,
- body: Iterable[training_create_params.Body],
- # 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,
- ) -> TrainingCreateResponse:
- """
- Create Training Pair
-
- Args:
- datasource_id: 数据源 ID
-
- 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(
- "/v1/training",
- body=await async_maybe_transform(body, Iterable[training_create_params.Body]),
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=await async_maybe_transform(
- {"datasource_id": datasource_id}, training_create_params.TrainingCreateParams
- ),
- ),
- cast_to=TrainingCreateResponse,
- )
-
- async def update(
- self,
- id: str,
- *,
- datasource_id: str,
- active: Optional[bool] | NotGiven = NOT_GIVEN,
- question: Optional[str] | NotGiven = NOT_GIVEN,
- role_id: Optional[str] | NotGiven = NOT_GIVEN,
- sql: Optional[str] | NotGiven = NOT_GIVEN,
- # 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,
- ) -> TrainingUpdateResponse:
- """
- Update Training Pair
-
- Args:
- datasource_id: 数据源 ID
-
- active: 是否启用
-
- question: 用户问题
-
- role_id: 角色 ID
-
- sql: 用户问题对应的 SQL
-
- 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 id:
- raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
- return await self._patch(
- f"/v1/training/{id}",
- body=await async_maybe_transform(
- {
- "active": active,
- "question": question,
- "role_id": role_id,
- "sql": sql,
- },
- training_update_params.TrainingUpdateParams,
- ),
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=await async_maybe_transform(
- {"datasource_id": datasource_id}, training_update_params.TrainingUpdateParams
- ),
- ),
- cast_to=TrainingUpdateResponse,
- )
-
- def list(
- self,
- *,
- datasource_id: str,
- page: int | NotGiven = NOT_GIVEN,
- size: int | NotGiven = NOT_GIVEN,
- # 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,
- ) -> AsyncPaginator[TrainingListResponse, AsyncPage[TrainingListResponse]]:
- """
- Get Training Pairs
-
- Args:
- datasource_id: 数据源 ID
-
- page: Page number
-
- size: Page size
-
- 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_api_list(
- "/v1/training",
- page=AsyncPage[TrainingListResponse],
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=maybe_transform(
- {
- "datasource_id": datasource_id,
- "page": page,
- "size": size,
- },
- training_list_params.TrainingListParams,
- ),
- ),
- model=TrainingListResponse,
- )
-
- async def delete(
- self,
- id: str,
- *,
- datasource_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,
- ) -> object:
- """
- Delete Training Pair
-
- Args:
- datasource_id: 数据源 ID
-
- 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 id:
- raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
- return await self._delete(
- f"/v1/training/{id}",
- options=make_request_options(
- extra_headers=extra_headers,
- extra_query=extra_query,
- extra_body=extra_body,
- timeout=timeout,
- query=await async_maybe_transform(
- {"datasource_id": datasource_id}, training_delete_params.TrainingDeleteParams
- ),
- ),
- cast_to=object,
- )
-
-
-class TrainingsResourceWithRawResponse:
- def __init__(self, trainings: TrainingsResource) -> None:
- self._trainings = trainings
-
- self.create = to_raw_response_wrapper(
- trainings.create,
- )
- self.update = to_raw_response_wrapper(
- trainings.update,
- )
- self.list = to_raw_response_wrapper(
- trainings.list,
- )
- self.delete = to_raw_response_wrapper(
- trainings.delete,
- )
-
-
-class AsyncTrainingsResourceWithRawResponse:
- def __init__(self, trainings: AsyncTrainingsResource) -> None:
- self._trainings = trainings
-
- self.create = async_to_raw_response_wrapper(
- trainings.create,
- )
- self.update = async_to_raw_response_wrapper(
- trainings.update,
- )
- self.list = async_to_raw_response_wrapper(
- trainings.list,
- )
- self.delete = async_to_raw_response_wrapper(
- trainings.delete,
- )
-
-
-class TrainingsResourceWithStreamingResponse:
- def __init__(self, trainings: TrainingsResource) -> None:
- self._trainings = trainings
-
- self.create = to_streamed_response_wrapper(
- trainings.create,
- )
- self.update = to_streamed_response_wrapper(
- trainings.update,
- )
- self.list = to_streamed_response_wrapper(
- trainings.list,
- )
- self.delete = to_streamed_response_wrapper(
- trainings.delete,
- )
-
-
-class AsyncTrainingsResourceWithStreamingResponse:
- def __init__(self, trainings: AsyncTrainingsResource) -> None:
- self._trainings = trainings
-
- self.create = async_to_streamed_response_wrapper(
- trainings.create,
- )
- self.update = async_to_streamed_response_wrapper(
- trainings.update,
- )
- self.list = async_to_streamed_response_wrapper(
- trainings.list,
- )
- self.delete = async_to_streamed_response_wrapper(
- trainings.delete,
- )
diff --git a/src/asktable/resources/user/projects.py b/src/asktable/resources/user/projects.py
index 27ba7426..324dd9ac 100644
--- a/src/asktable/resources/user/projects.py
+++ b/src/asktable/resources/user/projects.py
@@ -6,7 +6,7 @@
import httpx
-from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
+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
@@ -25,6 +25,8 @@
class ProjectsResource(SyncAPIResource):
+ """我的项目"""
+
@cached_property
def with_raw_response(self) -> ProjectsResourceWithRawResponse:
"""
@@ -52,7 +54,7 @@ def retrieve_model_groups(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ProjectRetrieveModelGroupsResponse:
"""Get Llm Model Groups"""
return self._get(
@@ -71,7 +73,7 @@ def retrieve_my_project(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""Get My Project"""
return self._get(
@@ -85,14 +87,14 @@ def retrieve_my_project(
def update_my_project(
self,
*,
- llm_model_group: Optional[str] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ llm_model_group: Optional[str] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Update My Project
@@ -127,6 +129,8 @@ def update_my_project(
class AsyncProjectsResource(AsyncAPIResource):
+ """我的项目"""
+
@cached_property
def with_raw_response(self) -> AsyncProjectsResourceWithRawResponse:
"""
@@ -154,7 +158,7 @@ async def retrieve_model_groups(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ProjectRetrieveModelGroupsResponse:
"""Get Llm Model Groups"""
return await self._get(
@@ -173,7 +177,7 @@ async def retrieve_my_project(
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
- timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""Get My Project"""
return await self._get(
@@ -187,14 +191,14 @@ async def retrieve_my_project(
async def update_my_project(
self,
*,
- llm_model_group: Optional[str] | NotGiven = NOT_GIVEN,
- name: Optional[str] | NotGiven = NOT_GIVEN,
+ llm_model_group: Optional[str] | Omit = omit,
+ name: Optional[str] | 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,
+ timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Project:
"""
Update My Project
diff --git a/src/asktable/resources/user/user.py b/src/asktable/resources/user/user.py
index 981d0969..970be13c 100644
--- a/src/asktable/resources/user/user.py
+++ b/src/asktable/resources/user/user.py
@@ -19,6 +19,7 @@
class UserResource(SyncAPIResource):
@cached_property
def projects(self) -> ProjectsResource:
+ """我的项目"""
return ProjectsResource(self._client)
@cached_property
@@ -44,6 +45,7 @@ def with_streaming_response(self) -> UserResourceWithStreamingResponse:
class AsyncUserResource(AsyncAPIResource):
@cached_property
def projects(self) -> AsyncProjectsResource:
+ """我的项目"""
return AsyncProjectsResource(self._client)
@cached_property
@@ -72,6 +74,7 @@ def __init__(self, user: UserResource) -> None:
@cached_property
def projects(self) -> ProjectsResourceWithRawResponse:
+ """我的项目"""
return ProjectsResourceWithRawResponse(self._user.projects)
@@ -81,6 +84,7 @@ def __init__(self, user: AsyncUserResource) -> None:
@cached_property
def projects(self) -> AsyncProjectsResourceWithRawResponse:
+ """我的项目"""
return AsyncProjectsResourceWithRawResponse(self._user.projects)
@@ -90,6 +94,7 @@ def __init__(self, user: UserResource) -> None:
@cached_property
def projects(self) -> ProjectsResourceWithStreamingResponse:
+ """我的项目"""
return ProjectsResourceWithStreamingResponse(self._user.projects)
@@ -99,4 +104,5 @@ def __init__(self, user: AsyncUserResource) -> None:
@cached_property
def projects(self) -> AsyncProjectsResourceWithStreamingResponse:
+ """我的项目"""
return AsyncProjectsResourceWithStreamingResponse(self._user.projects)
diff --git a/src/asktable/types/__init__.py b/src/asktable/types/__init__.py
index 640c9f4b..6b42fdbb 100644
--- a/src/asktable/types/__init__.py
+++ b/src/asktable/types/__init__.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-from .chat import Chat as Chat
from .meta import Meta as Meta
from .role import Role as Role
from .entry import Entry as Entry
@@ -33,17 +32,19 @@
from .sql_create_params import SqlCreateParams as SqlCreateParams
from .answer_list_params import AnswerListParams as AnswerListParams
from .chat_create_params import ChatCreateParams as ChatCreateParams
+from .chat_list_response import ChatListResponse as ChatListResponse
from .policy_list_params import PolicyListParams as PolicyListParams
from .role_create_params import RoleCreateParams as RoleCreateParams
from .role_update_params import RoleUpdateParams as RoleUpdateParams
from .ats_create_response import ATSCreateResponse as ATSCreateResponse
from .ats_update_response import ATSUpdateResponse as ATSUpdateResponse
+from .bot_invite_response import BotInviteResponse as BotInviteResponse
from .score_create_params import ScoreCreateParams as ScoreCreateParams
from .answer_create_params import AnswerCreateParams as AnswerCreateParams
+from .chat_create_response import ChatCreateResponse as ChatCreateResponse
from .policy_create_params import PolicyCreateParams as PolicyCreateParams
from .policy_update_params import PolicyUpdateParams as PolicyUpdateParams
from .polish_create_params import PolishCreateParams as PolishCreateParams
-from .training_list_params import TrainingListParams as TrainingListParams
from .ats_retrieve_response import ATSRetrieveResponse as ATSRetrieveResponse
from .entry_with_definition import EntryWithDefinition as EntryWithDefinition
from .project_update_params import ProjectUpdateParams as ProjectUpdateParams
@@ -51,28 +52,22 @@
from .chat_retrieve_response import ChatRetrieveResponse as ChatRetrieveResponse
from .datasource_list_params import DatasourceListParams as DatasourceListParams
from .polish_create_response import PolishCreateResponse as PolishCreateResponse
-from .training_create_params import TrainingCreateParams as TrainingCreateParams
-from .training_delete_params import TrainingDeleteParams as TrainingDeleteParams
-from .training_list_response import TrainingListResponse as TrainingListResponse
-from .training_update_params import TrainingUpdateParams as TrainingUpdateParams
-from .sy_update_config_params import SyUpdateConfigParams as SyUpdateConfigParams
from .auth_create_token_params import AuthCreateTokenParams as AuthCreateTokenParams
from .datasource_create_params import DatasourceCreateParams as DatasourceCreateParams
from .datasource_update_params import DatasourceUpdateParams as DatasourceUpdateParams
from .preference_create_params import PreferenceCreateParams as PreferenceCreateParams
from .preference_update_params import PreferenceUpdateParams as PreferenceUpdateParams
from .securetunnel_list_params import SecuretunnelListParams as SecuretunnelListParams
-from .training_create_response import TrainingCreateResponse as TrainingCreateResponse
-from .training_update_response import TrainingUpdateResponse as TrainingUpdateResponse
from .role_get_polices_response import RoleGetPolicesResponse as RoleGetPolicesResponse
from .role_get_variables_params import RoleGetVariablesParams as RoleGetVariablesParams
-from .sy_update_config_response import SyUpdateConfigResponse as SyUpdateConfigResponse
+from .auth_create_token_response import AuthCreateTokenResponse as AuthCreateTokenResponse
from .datasource_add_file_params import DatasourceAddFileParams as DatasourceAddFileParams
from .preference_create_response import PreferenceCreateResponse as PreferenceCreateResponse
from .preference_update_response import PreferenceUpdateResponse as PreferenceUpdateResponse
from .securetunnel_create_params import SecuretunnelCreateParams as SecuretunnelCreateParams
from .securetunnel_update_params import SecuretunnelUpdateParams as SecuretunnelUpdateParams
from .dataframe_retrieve_response import DataframeRetrieveResponse as DataframeRetrieveResponse
+from .role_get_variables_response import RoleGetVariablesResponse as RoleGetVariablesResponse
from .datasource_retrieve_response import DatasourceRetrieveResponse as DatasourceRetrieveResponse
from .preference_retrieve_response import PreferenceRetrieveResponse as PreferenceRetrieveResponse
from .business_glossary_list_params import BusinessGlossaryListParams as BusinessGlossaryListParams
diff --git a/src/asktable/types/ai_message.py b/src/asktable/types/ai_message.py
index 986e1827..11f0d3a7 100644
--- a/src/asktable/types/ai_message.py
+++ b/src/asktable/types/ai_message.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Optional
+from typing import Dict, List, Optional
from datetime import datetime
from typing_extensions import Literal
@@ -10,9 +10,9 @@
class ContentAttachment(BaseModel):
- info: object
+ info: Dict[str, object]
- type: str
+ type: Literal["data_json"]
"""The type of the attachment"""
@@ -48,7 +48,7 @@ class AIMessage(BaseModel):
end_turn: Optional[bool] = None
- metadata: Optional[object] = None
+ metadata: Optional[Dict[str, object]] = None
name: Optional[str] = None
diff --git a/src/asktable/types/answer_create_params.py b/src/asktable/types/answer_create_params.py
index b4fcd62f..c5adf1db 100644
--- a/src/asktable/types/answer_create_params.py
+++ b/src/asktable/types/answer_create_params.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Required, TypedDict
__all__ = ["AnswerCreateParams"]
@@ -24,7 +24,7 @@ class AnswerCreateParams(TypedDict, total=False):
数据
"""
- role_variables: Optional[object]
+ role_variables: Optional[Dict[str, object]]
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
with_json: Optional[bool]
diff --git a/src/asktable/types/answer_response.py b/src/asktable/types/answer_response.py
index 04112480..2aa376c1 100644
--- a/src/asktable/types/answer_response.py
+++ b/src/asktable/types/answer_response.py
@@ -1,17 +1,18 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Optional
+from typing import Dict, List, Optional
from datetime import datetime
+from typing_extensions import Literal
from .._models import BaseModel
-__all__ = ["AnswerResponse", "Answer", "AnswerAttachment", "Request", "Timing"]
+__all__ = ["AnswerResponse", "Answer", "AnswerAttachment", "Request"]
class AnswerAttachment(BaseModel):
- info: object
+ info: Dict[str, object]
- type: str
+ type: Literal["data_json"]
"""The type of the attachment"""
@@ -37,21 +38,13 @@ class Request(BaseModel):
数据
"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
with_json: Optional[bool] = None
"""是否同时将数据,作为 json 格式的附件一起返回"""
-class Timing(BaseModel):
- accessor_duration: Optional[float] = None
-
- llm_duration: Optional[float] = None
-
- total_duration: Optional[float] = None
-
-
class AnswerResponse(BaseModel):
id: str
@@ -71,6 +64,4 @@ class AnswerResponse(BaseModel):
err_msg: Optional[str] = None
- timing: Optional[Timing] = None
-
trace_id: Optional[str] = None
diff --git a/src/asktable/types/ats/task_get_case_tasks_response.py b/src/asktable/types/ats/task_get_case_tasks_response.py
index 0592193e..6f81b7f9 100644
--- a/src/asktable/types/ats/task_get_case_tasks_response.py
+++ b/src/asktable/types/ats/task_get_case_tasks_response.py
@@ -1,20 +1,26 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Union, Optional
+from typing import Dict, List, Union, Optional
from datetime import datetime
+from typing_extensions import Literal
from ..._models import BaseModel
-__all__ = ["TaskGetCaseTasksResponse", "Item"]
+__all__ = ["TaskGetCaseTasksResponse", "Item", "ItemCompareLog"]
+
+
+class ItemCompareLog(BaseModel):
+ check: str
+
+ level: Literal["ERROR", "WARNING", "INFO"]
+
+ message: str
class Item(BaseModel):
id: str
"""测试用例运行记录 ID"""
- ats_task_id: str
- """对应的测试任务 ID"""
-
created_at: datetime
"""创建时间"""
@@ -27,22 +33,28 @@ class Item(BaseModel):
question: str
"""提问内容"""
+ run_id: str
+ """对应的测试任务 ID"""
+
status: str
"""测试状态"""
- atc_id: Optional[str] = None
+ case_id: Optional[str] = None
"""对应的测试用例 ID"""
+ compare_logs: Optional[List[ItemCompareLog]] = None
+ """测试样本生成 sql 和预期 sql 的对比日志"""
+
duration: Optional[float] = None
"""测试用例执行时间,单位为秒"""
- expected_query_result: Union[List[object], object, None] = None
+ expected_query_result: Union[Dict[str, object], List[Dict[str, object]], None] = None
"""预期查询出来的数据"""
generated_sql: Optional[str] = None
"""生成的 sql"""
- generated_sql_query_result: Union[List[object], object, None] = None
+ generated_sql_query_result: Union[Dict[str, object], List[Dict[str, object]], None] = None
"""测试样本生成的 sql 查询结果"""
last_run: Optional[datetime] = None
@@ -51,7 +63,7 @@ class Item(BaseModel):
role_id: Optional[str] = None
"""角色 ID"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""扮演角色需要传递的值"""
status_message: Optional[str] = None
@@ -60,14 +72,17 @@ class Item(BaseModel):
task_id: Optional[str] = None
"""测试调用接口对应任务的 id"""
+ trace_id: Optional[str] = None
+ """测试样本运行时对应的 trace_id"""
+
class TaskGetCaseTasksResponse(BaseModel):
items: List[Item]
- page: Optional[int] = None
+ page: int
- size: Optional[int] = None
+ pages: int
- total: Optional[int] = None
+ size: int
- pages: Optional[int] = None
+ total: int
diff --git a/src/asktable/types/ats/task_list_response.py b/src/asktable/types/ats/task_list_response.py
index a3591ca0..e3428566 100644
--- a/src/asktable/types/ats/task_list_response.py
+++ b/src/asktable/types/ats/task_list_response.py
@@ -1,8 +1,10 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
+from pydantic import Field as FieldInfo
+
from ..._models import BaseModel
__all__ = ["TaskListResponse"]
@@ -15,9 +17,6 @@ class TaskListResponse(BaseModel):
accuracy: float
"""测试正确率"""
- ats_id: str
- """测试集 ID"""
-
completed_case_count: int
"""已完成测试用例数"""
@@ -36,6 +35,9 @@ class TaskListResponse(BaseModel):
status: str
"""测试状态"""
+ suite_id: str
+ """测试集 ID"""
+
total_case_count: int
"""测试用例总数"""
@@ -45,5 +47,8 @@ class TaskListResponse(BaseModel):
last_run: Optional[datetime] = None
"""上次测试运行时间"""
+ api_model_group: Optional[Dict[str, object]] = FieldInfo(alias="model_group", default=None)
+ """运行使用的模型组"""
+
status_message: Optional[str] = None
"""测试日志"""
diff --git a/src/asktable/types/ats/task_retrieve_response.py b/src/asktable/types/ats/task_retrieve_response.py
index bc81d5bc..0d1101a8 100644
--- a/src/asktable/types/ats/task_retrieve_response.py
+++ b/src/asktable/types/ats/task_retrieve_response.py
@@ -1,8 +1,10 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
+from pydantic import Field as FieldInfo
+
from ..._models import BaseModel
__all__ = ["TaskRetrieveResponse"]
@@ -15,9 +17,6 @@ class TaskRetrieveResponse(BaseModel):
accuracy: float
"""测试正确率"""
- ats_id: str
- """测试集 ID"""
-
completed_case_count: int
"""已完成测试用例数"""
@@ -36,6 +35,9 @@ class TaskRetrieveResponse(BaseModel):
status: str
"""测试状态"""
+ suite_id: str
+ """测试集 ID"""
+
total_case_count: int
"""测试用例总数"""
@@ -45,5 +47,8 @@ class TaskRetrieveResponse(BaseModel):
last_run: Optional[datetime] = None
"""上次测试运行时间"""
+ api_model_group: Optional[Dict[str, object]] = FieldInfo(alias="model_group", default=None)
+ """运行使用的模型组"""
+
status_message: Optional[str] = None
"""测试日志"""
diff --git a/src/asktable/types/ats/task_run_params.py b/src/asktable/types/ats/task_run_params.py
index b86b4193..a397edcb 100644
--- a/src/asktable/types/ats/task_run_params.py
+++ b/src/asktable/types/ats/task_run_params.py
@@ -2,9 +2,10 @@
from __future__ import annotations
-from typing import List
from typing_extensions import Required, TypedDict
+from ..._types import SequenceNotStr
+
__all__ = ["TaskRunParams"]
@@ -12,5 +13,5 @@ class TaskRunParams(TypedDict, total=False):
datasource_id: Required[str]
"""数据源 ID"""
- specific_case_ids: Required[List[str]]
+ specific_case_ids: Required[SequenceNotStr[str]]
"""测试用例 ID 列表"""
diff --git a/src/asktable/types/ats/task_run_response.py b/src/asktable/types/ats/task_run_response.py
index fbc3533c..e74587a6 100644
--- a/src/asktable/types/ats/task_run_response.py
+++ b/src/asktable/types/ats/task_run_response.py
@@ -1,8 +1,10 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
+from pydantic import Field as FieldInfo
+
from ..._models import BaseModel
__all__ = ["TaskRunResponse"]
@@ -15,9 +17,6 @@ class TaskRunResponse(BaseModel):
accuracy: float
"""测试正确率"""
- ats_id: str
- """测试集 ID"""
-
completed_case_count: int
"""已完成测试用例数"""
@@ -36,6 +35,9 @@ class TaskRunResponse(BaseModel):
status: str
"""测试状态"""
+ suite_id: str
+ """测试集 ID"""
+
total_case_count: int
"""测试用例总数"""
@@ -45,5 +47,8 @@ class TaskRunResponse(BaseModel):
last_run: Optional[datetime] = None
"""上次测试运行时间"""
+ api_model_group: Optional[Dict[str, object]] = FieldInfo(alias="model_group", default=None)
+ """运行使用的模型组"""
+
status_message: Optional[str] = None
"""测试日志"""
diff --git a/src/asktable/types/ats/test_case_create_params.py b/src/asktable/types/ats/test_case_create_params.py
index 229132b2..02ecaca0 100644
--- a/src/asktable/types/ats/test_case_create_params.py
+++ b/src/asktable/types/ats/test_case_create_params.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Required, TypedDict
__all__ = ["TestCaseCreateParams"]
@@ -18,5 +18,5 @@ class TestCaseCreateParams(TypedDict, total=False):
role_id: Optional[str]
"""角色 ID"""
- role_variables: Optional[object]
+ role_variables: Optional[Dict[str, object]]
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/ats/test_case_create_response.py b/src/asktable/types/ats/test_case_create_response.py
index 0faa6a83..79862611 100644
--- a/src/asktable/types/ats/test_case_create_response.py
+++ b/src/asktable/types/ats/test_case_create_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
from ..._models import BaseModel
@@ -13,9 +13,6 @@ class TestCaseCreateResponse(BaseModel):
id: str
"""测试样例 ID"""
- ats_id: str
- """所属的测试集 ID"""
-
created_at: datetime
"""创建时间"""
@@ -28,8 +25,11 @@ class TestCaseCreateResponse(BaseModel):
question: str
"""用户提问"""
+ suite_id: str
+ """所属的测试集 ID"""
+
role_id: Optional[str] = None
"""角色 ID"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/ats/test_case_list_response.py b/src/asktable/types/ats/test_case_list_response.py
index 4216c794..b6318136 100644
--- a/src/asktable/types/ats/test_case_list_response.py
+++ b/src/asktable/types/ats/test_case_list_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
from ..._models import BaseModel
@@ -13,9 +13,6 @@ class TestCaseListResponse(BaseModel):
id: str
"""测试样例 ID"""
- ats_id: str
- """所属的测试集 ID"""
-
created_at: datetime
"""创建时间"""
@@ -28,8 +25,11 @@ class TestCaseListResponse(BaseModel):
question: str
"""用户提问"""
+ suite_id: str
+ """所属的测试集 ID"""
+
role_id: Optional[str] = None
"""角色 ID"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/ats/test_case_retrieve_response.py b/src/asktable/types/ats/test_case_retrieve_response.py
index 951aee1d..e0b2328a 100644
--- a/src/asktable/types/ats/test_case_retrieve_response.py
+++ b/src/asktable/types/ats/test_case_retrieve_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
from ..._models import BaseModel
@@ -13,9 +13,6 @@ class TestCaseRetrieveResponse(BaseModel):
id: str
"""测试样例 ID"""
- ats_id: str
- """所属的测试集 ID"""
-
created_at: datetime
"""创建时间"""
@@ -28,8 +25,11 @@ class TestCaseRetrieveResponse(BaseModel):
question: str
"""用户提问"""
+ suite_id: str
+ """所属的测试集 ID"""
+
role_id: Optional[str] = None
"""角色 ID"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/ats/test_case_update_params.py b/src/asktable/types/ats/test_case_update_params.py
index 020118e0..1b5124a7 100644
--- a/src/asktable/types/ats/test_case_update_params.py
+++ b/src/asktable/types/ats/test_case_update_params.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Required, TypedDict
__all__ = ["TestCaseUpdateParams"]
@@ -20,5 +20,5 @@ class TestCaseUpdateParams(TypedDict, total=False):
role_id: Optional[str]
"""角色 ID"""
- role_variables: Optional[object]
+ role_variables: Optional[Dict[str, object]]
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/ats/test_case_update_response.py b/src/asktable/types/ats/test_case_update_response.py
index 089d55e8..17577368 100644
--- a/src/asktable/types/ats/test_case_update_response.py
+++ b/src/asktable/types/ats/test_case_update_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
from ..._models import BaseModel
@@ -13,9 +13,6 @@ class TestCaseUpdateResponse(BaseModel):
id: str
"""测试样例 ID"""
- ats_id: str
- """所属的测试集 ID"""
-
created_at: datetime
"""创建时间"""
@@ -28,8 +25,11 @@ class TestCaseUpdateResponse(BaseModel):
question: str
"""用户提问"""
+ suite_id: str
+ """所属的测试集 ID"""
+
role_id: Optional[str] = None
"""角色 ID"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/ats_create_response.py b/src/asktable/types/ats_create_response.py
index 4ed69a97..f8e41ec9 100644
--- a/src/asktable/types/ats_create_response.py
+++ b/src/asktable/types/ats_create_response.py
@@ -1,5 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+from typing import Optional
from datetime import datetime
from .._models import BaseModel
@@ -25,3 +26,9 @@ class ATSCreateResponse(BaseModel):
project_id: str
"""项目 ID"""
+
+ case_count: Optional[int] = None
+ """测试用例数量"""
+
+ datasource_name: Optional[str] = None
+ """数据源名称"""
diff --git a/src/asktable/types/ats_list_params.py b/src/asktable/types/ats_list_params.py
index 09110362..7373b365 100644
--- a/src/asktable/types/ats_list_params.py
+++ b/src/asktable/types/ats_list_params.py
@@ -2,14 +2,15 @@
from __future__ import annotations
-from typing_extensions import Required, TypedDict
+from typing import Optional
+from typing_extensions import TypedDict
__all__ = ["ATSListParams"]
class ATSListParams(TypedDict, total=False):
- datasource_id: Required[str]
- """数据源 ID"""
+ datasource_id: Optional[str]
+ """数据源 ID,可选过滤条件"""
page: int
"""Page number"""
diff --git a/src/asktable/types/ats_list_response.py b/src/asktable/types/ats_list_response.py
index 04206289..c3afd735 100644
--- a/src/asktable/types/ats_list_response.py
+++ b/src/asktable/types/ats_list_response.py
@@ -1,5 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+from typing import Optional
from datetime import datetime
from .._models import BaseModel
@@ -25,3 +26,9 @@ class ATSListResponse(BaseModel):
project_id: str
"""项目 ID"""
+
+ case_count: Optional[int] = None
+ """测试用例数量"""
+
+ datasource_name: Optional[str] = None
+ """数据源名称"""
diff --git a/src/asktable/types/ats_retrieve_response.py b/src/asktable/types/ats_retrieve_response.py
index 0195c97c..fe010a8c 100644
--- a/src/asktable/types/ats_retrieve_response.py
+++ b/src/asktable/types/ats_retrieve_response.py
@@ -1,5 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+from typing import Optional
from datetime import datetime
from .._models import BaseModel
@@ -25,3 +26,9 @@ class ATSRetrieveResponse(BaseModel):
project_id: str
"""项目 ID"""
+
+ case_count: Optional[int] = None
+ """测试用例数量"""
+
+ datasource_name: Optional[str] = None
+ """数据源名称"""
diff --git a/src/asktable/types/ats_update_response.py b/src/asktable/types/ats_update_response.py
index 374dfe87..0a27ed2e 100644
--- a/src/asktable/types/ats_update_response.py
+++ b/src/asktable/types/ats_update_response.py
@@ -1,5 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+from typing import Optional
from datetime import datetime
from .._models import BaseModel
@@ -25,3 +26,9 @@ class ATSUpdateResponse(BaseModel):
project_id: str
"""项目 ID"""
+
+ case_count: Optional[int] = None
+ """测试用例数量"""
+
+ datasource_name: Optional[str] = None
+ """数据源名称"""
diff --git a/src/asktable/types/auth_create_token_params.py b/src/asktable/types/auth_create_token_params.py
index 7764745b..2b245f32 100644
--- a/src/asktable/types/auth_create_token_params.py
+++ b/src/asktable/types/auth_create_token_params.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Literal, TypedDict
__all__ = ["AuthCreateTokenParams", "ChatRole"]
@@ -18,13 +18,15 @@ class AuthCreateTokenParams(TypedDict, total=False):
token_ttl: int
"""The time-to-live for the token in seconds"""
- user_profile: Optional[object]
+ user_profile: Optional[Dict[str, object]]
"""Optional user profile data"""
class ChatRole(TypedDict, total=False):
+ """The chat role"""
+
role_id: Optional[str]
"""The chat role ID"""
- role_variables: Optional[object]
+ role_variables: Optional[Dict[str, object]]
"""The chat role variables"""
diff --git a/src/asktable/types/auth_create_token_response.py b/src/asktable/types/auth_create_token_response.py
new file mode 100644
index 00000000..0ff7ae33
--- /dev/null
+++ b/src/asktable/types/auth_create_token_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["AuthCreateTokenResponse"]
+
+AuthCreateTokenResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/auth_me_response.py b/src/asktable/types/auth_me_response.py
index 0db427fa..94307134 100644
--- a/src/asktable/types/auth_me_response.py
+++ b/src/asktable/types/auth_me_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Literal
from .._models import BaseModel
@@ -15,10 +15,10 @@ class AuthMeResponse(BaseModel):
ak_id: Optional[str] = None
- chat_role: Optional[object] = None
+ chat_role: Optional[Dict[str, object]] = None
exp: Optional[int] = None
locked: Optional[bool] = None
- user_profile: Optional[object] = None
+ user_profile: Optional[Dict[str, object]] = None
diff --git a/src/asktable/types/bot_create_params.py b/src/asktable/types/bot_create_params.py
index e2a2f550..8b323b30 100644
--- a/src/asktable/types/bot_create_params.py
+++ b/src/asktable/types/bot_create_params.py
@@ -2,14 +2,16 @@
from __future__ import annotations
-from typing import List, Iterable, Optional
+from typing import Iterable, Optional
from typing_extensions import Literal, Required, TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["BotCreateParams", "InteractionRule"]
class BotCreateParams(TypedDict, total=False):
- datasource_ids: Required[List[str]]
+ datasource_ids: Required[SequenceNotStr[str]]
"""数据源 ID,目前只支持 1 个数据源。"""
name: Required[str]
@@ -21,11 +23,8 @@ class BotCreateParams(TypedDict, total=False):
debug: bool
"""调试模式"""
- extapi_ids: List[str]
- """扩展 API ID 列表,扩展 API ID 的逗号分隔列表。"""
-
interaction_rules: Iterable[InteractionRule]
- """交互规则列表,用于定义 bot 的行为规则"""
+ """交互规则列表,用于定义 AI 数据助手的行为规则"""
magic_input: Optional[str]
"""魔法提示词"""
@@ -37,12 +36,12 @@ class BotCreateParams(TypedDict, total=False):
"""是否公开"""
query_balance: Optional[int]
- """bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数"""
+ """AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数"""
- sample_questions: Optional[List[str]]
+ sample_questions: Optional[SequenceNotStr[str]]
"""示例问题列表"""
- webhooks: List[str]
+ webhooks: SequenceNotStr[str]
"""Webhook URL 列表"""
welcome_message: Optional[str]
@@ -58,4 +57,4 @@ class InteractionRule(TypedDict, total=False):
version: Required[Literal["1.0.0"]]
- words: Required[List[str]]
+ words: Required[SequenceNotStr[str]]
diff --git a/src/asktable/types/bot_invite_response.py b/src/asktable/types/bot_invite_response.py
new file mode 100644
index 00000000..25c02623
--- /dev/null
+++ b/src/asktable/types/bot_invite_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["BotInviteResponse"]
+
+BotInviteResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/bot_list_params.py b/src/asktable/types/bot_list_params.py
index 2463c813..063a000f 100644
--- a/src/asktable/types/bot_list_params.py
+++ b/src/asktable/types/bot_list_params.py
@@ -2,14 +2,16 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["BotListParams"]
class BotListParams(TypedDict, total=False):
- bot_ids: Optional[List[str]]
+ bot_ids: Optional[SequenceNotStr[str]]
"""Bot ID"""
name: Optional[str]
diff --git a/src/asktable/types/bot_update_params.py b/src/asktable/types/bot_update_params.py
index e08d5a37..34731704 100644
--- a/src/asktable/types/bot_update_params.py
+++ b/src/asktable/types/bot_update_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Iterable, Optional
+from typing import Iterable, Optional
from typing_extensions import Literal, Required, TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["BotUpdateParams", "InteractionRule"]
@@ -15,17 +17,14 @@ class BotUpdateParams(TypedDict, total=False):
color_theme: Optional[str]
"""颜色主题"""
- datasource_ids: Optional[List[str]]
+ datasource_ids: Optional[SequenceNotStr[str]]
"""数据源 ID,目前只支持 1 个数据源。"""
debug: Optional[bool]
"""调试模式"""
- extapi_ids: Optional[List[str]]
- """扩展 API ID 列表,扩展 API ID 的逗号分隔列表。"""
-
interaction_rules: Optional[Iterable[InteractionRule]]
- """交互规则列表,用于定义 bot 的行为规则"""
+ """交互规则列表,用于定义 AI 数据助手的行为规则"""
magic_input: Optional[str]
"""魔法提示词"""
@@ -40,12 +39,12 @@ class BotUpdateParams(TypedDict, total=False):
"""是否公开"""
query_balance: Optional[int]
- """bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数"""
+ """AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 0 的整数"""
- sample_questions: Optional[List[str]]
+ sample_questions: Optional[SequenceNotStr[str]]
"""示例问题列表"""
- webhooks: Optional[List[str]]
+ webhooks: Optional[SequenceNotStr[str]]
"""Webhook URL 列表"""
welcome_message: Optional[str]
@@ -61,4 +60,4 @@ class InteractionRule(TypedDict, total=False):
version: Required[Literal["1.0.0"]]
- words: Required[List[str]]
+ words: Required[SequenceNotStr[str]]
diff --git a/src/asktable/types/business_glossary_create_params.py b/src/asktable/types/business_glossary_create_params.py
index e9f3d42d..c3ba76dc 100644
--- a/src/asktable/types/business_glossary_create_params.py
+++ b/src/asktable/types/business_glossary_create_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Iterable, Optional
+from typing import Dict, Iterable, Optional
from typing_extensions import Required, TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["BusinessGlossaryCreateParams", "Body"]
@@ -13,6 +15,8 @@ class BusinessGlossaryCreateParams(TypedDict, total=False):
class Body(TypedDict, total=False):
+ """Schema for creating a new document"""
+
definition: Required[str]
"""业务术语定义"""
@@ -22,8 +26,8 @@ class Body(TypedDict, total=False):
active: bool
"""业务术语是否生效"""
- aliases: Optional[List[str]]
+ aliases: Optional[SequenceNotStr[str]]
"""业务术语同义词"""
- payload: Optional[object]
+ payload: Optional[Dict[str, object]]
"""业务术语元数据"""
diff --git a/src/asktable/types/business_glossary_update_params.py b/src/asktable/types/business_glossary_update_params.py
index 89bad224..8b65f387 100644
--- a/src/asktable/types/business_glossary_update_params.py
+++ b/src/asktable/types/business_glossary_update_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Dict, Optional
from typing_extensions import TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["BusinessGlossaryUpdateParams"]
@@ -12,13 +14,13 @@ class BusinessGlossaryUpdateParams(TypedDict, total=False):
active: Optional[bool]
"""业务术语是否生效"""
- aliases: Optional[List[str]]
+ aliases: Optional[SequenceNotStr[str]]
"""业务术语同义词"""
definition: Optional[str]
"""业务术语定义"""
- payload: Optional[object]
+ payload: Optional[Dict[str, object]]
"""业务术语元数据"""
term: Optional[str]
diff --git a/src/asktable/types/chat_create_params.py b/src/asktable/types/chat_create_params.py
index ca697335..7d42c04b 100644
--- a/src/asktable/types/chat_create_params.py
+++ b/src/asktable/types/chat_create_params.py
@@ -11,8 +11,8 @@
class ChatCreateParams(TypedDict, total=False):
bot_id: Optional[str]
"""
- 机器人 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在机器人中你可以定义
- 可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
+ AI 数据助手 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在 AI 数据助手中
+ 你可以定义可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
"""
name: Optional[str]
diff --git a/src/asktable/types/chat_create_response.py b/src/asktable/types/chat_create_response.py
new file mode 100644
index 00000000..0e31823f
--- /dev/null
+++ b/src/asktable/types/chat_create_response.py
@@ -0,0 +1,50 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict, Union, Optional
+from datetime import datetime
+from typing_extensions import Literal
+
+from .._models import BaseModel
+
+__all__ = ["ChatCreateResponse"]
+
+
+class ChatCreateResponse(BaseModel):
+ id: str
+ """对话 ID"""
+
+ created_at: datetime
+ """创建时间"""
+
+ modified_at: datetime
+ """修改时间"""
+
+ project_id: str
+
+ status: Literal["active", "pending", "warning", "error"]
+
+ bot_id: Optional[str] = None
+ """
+ AI 数据助手 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在 AI 数据助手中
+ 你可以定义可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
+ """
+
+ error_detail: Optional[Dict[str, object]] = None
+
+ name: Optional[str] = None
+ """New name for the chat"""
+
+ role_id: Optional[str] = None
+ """
+ 角色 ID,将扮演这个角色来执行对话,用于权限控制。若无,则跳过鉴权,即可查询所有
+ 数据
+ """
+
+ role_name: Optional[str] = None
+ """角色名称"""
+
+ role_variables: Optional[Dict[str, Union[str, int, bool]]] = None
+ """在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
+
+ user_profile: Optional[Dict[str, Union[str, int, bool]]] = None
+ """用户信息,用于在对话中传递用户的信息,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/chat.py b/src/asktable/types/chat_list_response.py
similarity index 68%
rename from src/asktable/types/chat.py
rename to src/asktable/types/chat_list_response.py
index ff282d79..e2b1c503 100644
--- a/src/asktable/types/chat.py
+++ b/src/asktable/types/chat_list_response.py
@@ -6,10 +6,10 @@
from .._models import BaseModel
-__all__ = ["Chat"]
+__all__ = ["ChatListResponse"]
-class Chat(BaseModel):
+class ChatListResponse(BaseModel):
id: str
"""对话 ID"""
@@ -21,16 +21,16 @@ class Chat(BaseModel):
project_id: str
- status: Literal["active", "pending", "error", "fatal"]
-
- status_message: Optional[str] = None
+ status: Literal["active", "pending", "warning", "error"]
bot_id: Optional[str] = None
"""
- 机器人 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在机器人中你可以定义
- 可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
+ AI 数据助手 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在 AI 数据助手中
+ 你可以定义可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
"""
+ error_detail: Optional[Dict[str, object]] = None
+
name: Optional[str] = None
"""New name for the chat"""
@@ -40,6 +40,9 @@ class Chat(BaseModel):
数据
"""
+ role_name: Optional[str] = None
+ """角色名称"""
+
role_variables: Optional[Dict[str, Union[str, int, bool]]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/chat_retrieve_response.py b/src/asktable/types/chat_retrieve_response.py
index 3868c1a8..91c241f2 100644
--- a/src/asktable/types/chat_retrieve_response.py
+++ b/src/asktable/types/chat_retrieve_response.py
@@ -21,18 +21,18 @@ class ChatRetrieveResponse(BaseModel):
project_id: str
- status: Literal["active", "pending", "error", "fatal"]
-
- status_message: Optional[str] = None
+ status: Literal["active", "pending", "warning", "error"]
bot_id: Optional[str] = None
"""
- 机器人 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在机器人中你可以定义
- 可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
+ AI 数据助手 ID,如果需要使用高级功能,请使用 bot_id 来创建对话。在 AI 数据助手中
+ 你可以定义可以访问的数据、可以执行的任务以及是否开启调试模式等设置。
"""
datasource_ids: Optional[List[str]] = None
+ error_detail: Optional[Dict[str, object]] = None
+
name: Optional[str] = None
"""New name for the chat"""
@@ -42,6 +42,9 @@ class ChatRetrieveResponse(BaseModel):
数据
"""
+ role_name: Optional[str] = None
+ """角色名称"""
+
role_variables: Optional[Dict[str, Union[str, int, bool]]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/chatbot.py b/src/asktable/types/chatbot.py
index 2c37b41b..c48283c6 100644
--- a/src/asktable/types/chatbot.py
+++ b/src/asktable/types/chatbot.py
@@ -27,7 +27,6 @@ class Chatbot(BaseModel):
created_at: datetime
datasource_ids: List[str]
- """数据源 ID,目前只支持 1 个数据源。"""
modified_at: datetime
@@ -42,14 +41,14 @@ class Chatbot(BaseModel):
color_theme: Optional[str] = None
"""颜色主题"""
+ datasource_name: Optional[str] = None
+ """数据源名称"""
+
debug: Optional[bool] = None
"""调试模式"""
- extapi_ids: Optional[List[str]] = None
- """扩展 API ID 列表,扩展 API ID 的逗号分隔列表。"""
-
interaction_rules: Optional[List[InteractionRule]] = None
- """交互规则列表,用于定义 bot 的行为规则"""
+ """交互规则列表,用于定义 AI 数据助手的行为规则"""
magic_input: Optional[str] = None
"""魔法提示词"""
@@ -61,7 +60,7 @@ class Chatbot(BaseModel):
"""是否公开"""
query_balance: Optional[int] = None
- """bot 的查询次数,默认是 None,表示无限次查询,入参为大于等于 1 的整数"""
+ """AI 数据助手的查询次数,默认是 None,表示无限次查询,入参为大于等于 1 的整数"""
sample_questions: Optional[List[str]] = None
"""示例问题列表"""
diff --git a/src/asktable/types/chats/message_create_params.py b/src/asktable/types/chats/message_create_params.py
index 64600d94..5f29fbec 100644
--- a/src/asktable/types/chats/message_create_params.py
+++ b/src/asktable/types/chats/message_create_params.py
@@ -2,10 +2,16 @@
from __future__ import annotations
-from typing_extensions import Required, TypedDict
+from typing import Optional
+from typing_extensions import Annotated, TypedDict
+
+from ..._utils import PropertyInfo
__all__ = ["MessageCreateParams"]
class MessageCreateParams(TypedDict, total=False):
- question: Required[str]
+ query_question: Annotated[Optional[str], PropertyInfo(alias="question")]
+
+ body_question: Annotated[Optional[str], PropertyInfo(alias="question")]
+ """用户问题"""
diff --git a/src/asktable/types/dataframe_retrieve_response.py b/src/asktable/types/dataframe_retrieve_response.py
index 75cdbde6..56619d43 100644
--- a/src/asktable/types/dataframe_retrieve_response.py
+++ b/src/asktable/types/dataframe_retrieve_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List
+from typing import Dict, List, Optional
from datetime import datetime
from .._models import BaseModel
@@ -12,24 +12,18 @@ class DataframeRetrieveResponse(BaseModel):
id: str
"""ID"""
- chart_options: object
+ chart_options: Dict[str, object]
"""图表选项"""
- content: List[object]
- """内容"""
-
created_at: datetime
"""创建时间"""
- header: List[object]
+ header: List[Dict[str, object]]
"""表头"""
modified_at: datetime
"""更新时间"""
- msg_id: str
- """消息 ID"""
-
project_id: str
"""项目 ID"""
@@ -41,3 +35,12 @@ class DataframeRetrieveResponse(BaseModel):
title: str
"""标题"""
+
+ chart_config: Optional[Dict[str, object]] = None
+ """ChartSpec 图表配置"""
+
+ content: Optional[List[Dict[str, object]]] = None
+ """内容"""
+
+ msg_id: Optional[str] = None
+ """消息 ID"""
diff --git a/src/asktable/types/datasource.py b/src/asktable/types/datasource.py
index 70a1ae18..403b9b37 100644
--- a/src/asktable/types/datasource.py
+++ b/src/asktable/types/datasource.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, List, Optional
from datetime import datetime
from typing_extensions import Literal
@@ -38,11 +38,23 @@ class Datasource(BaseModel):
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
]
"""数据源引擎"""
- meta_status: Literal["processing", "failed", "success", "unprocessed"]
- """元数据处理状态"""
+ meta_status: Literal["unavailable", "available"]
+ """数据源可用性"""
modified_at: datetime
"""修改时间"""
@@ -50,23 +62,29 @@ class Datasource(BaseModel):
project_id: str
"""项目 ID"""
+ sync_status: Literal["processing", "success", "failed", "warning"]
+ """同步状态"""
+
desc: Optional[str] = None
"""数据源描述"""
field_count: Optional[int] = None
"""字段数量"""
- meta_error: Optional[str] = None
- """元数据处理错误"""
-
name: Optional[str] = None
"""数据源的名称"""
- sample_questions: Optional[str] = None
+ sample_questions: Optional[List[str]] = None
"""示例问题"""
schema_count: Optional[int] = None
"""库数量"""
+ sync_error: Optional[Dict[str, object]] = None
+ """同步错误信息"""
+
+ synced_at: Optional[datetime] = None
+ """上次同步完成时间"""
+
table_count: Optional[int] = None
"""表数量"""
diff --git a/src/asktable/types/datasource_add_file_params.py b/src/asktable/types/datasource_add_file_params.py
index fa03fb7a..39418d4a 100644
--- a/src/asktable/types/datasource_add_file_params.py
+++ b/src/asktable/types/datasource_add_file_params.py
@@ -4,10 +4,8 @@
from typing_extensions import Required, TypedDict
-from .._types import FileTypes
-
__all__ = ["DatasourceAddFileParams"]
class DatasourceAddFileParams(TypedDict, total=False):
- file: Required[FileTypes]
+ file: Required[str]
diff --git a/src/asktable/types/datasource_create_params.py b/src/asktable/types/datasource_create_params.py
index afd362b0..eb6d87b7 100644
--- a/src/asktable/types/datasource_create_params.py
+++ b/src/asktable/types/datasource_create_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Union, Optional
+from typing import Dict, Union, Optional
from typing_extensions import Literal, Required, TypeAlias, TypedDict
+from .._types import SequenceNotStr
+
__all__ = [
"DatasourceCreateParams",
"AccessConfig",
@@ -37,6 +39,18 @@ class DatasourceCreateParams(TypedDict, total=False):
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
]
]
"""数据源引擎"""
@@ -58,7 +72,7 @@ class AccessConfigAccessConfigConnectionCreate(TypedDict, total=False):
db_version: Optional[str]
"""数据库版本"""
- extra_config: Optional[object]
+ extra_config: Optional[Dict[str, object]]
"""额外配置"""
password: Optional[str]
@@ -75,7 +89,7 @@ class AccessConfigAccessConfigConnectionCreate(TypedDict, total=False):
class AccessConfigAccessConfigFileCreate(TypedDict, total=False):
- files: Required[List[str]]
+ files: Required[SequenceNotStr[str]]
"""数据源文件 URL 列表, 创建时可以传入 URL"""
diff --git a/src/asktable/types/datasource_retrieve_response.py b/src/asktable/types/datasource_retrieve_response.py
index d244225c..27cca6a5 100644
--- a/src/asktable/types/datasource_retrieve_response.py
+++ b/src/asktable/types/datasource_retrieve_response.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Union, Optional
+from typing import Dict, List, Union, Optional
from datetime import datetime
from typing_extensions import Literal, TypeAlias
@@ -28,7 +28,7 @@ class AccessConfigAccessConfigConnectionResponse(BaseModel):
db_version: Optional[str] = None
"""数据库版本"""
- extra_config: Optional[object] = None
+ extra_config: Optional[Dict[str, object]] = None
"""额外配置"""
port: Optional[int] = None
@@ -52,7 +52,7 @@ class AccessConfigAccessConfigFileResponseFile(BaseModel):
filename: str
- custom_config: Optional[object] = None
+ custom_config: Optional[Dict[str, object]] = None
"""文件自定义配置"""
@@ -93,11 +93,23 @@ class DatasourceRetrieveResponse(BaseModel):
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
]
"""数据源引擎"""
- meta_status: Literal["processing", "failed", "success", "unprocessed"]
- """元数据处理状态"""
+ meta_status: Literal["unavailable", "available"]
+ """数据源可用性"""
modified_at: datetime
"""修改时间"""
@@ -105,6 +117,9 @@ class DatasourceRetrieveResponse(BaseModel):
project_id: str
"""项目 ID"""
+ sync_status: Literal["processing", "success", "failed", "warning"]
+ """同步状态"""
+
access_config: Optional[AccessConfig] = None
"""访问数据源的配置信息"""
@@ -114,17 +129,20 @@ class DatasourceRetrieveResponse(BaseModel):
field_count: Optional[int] = None
"""字段数量"""
- meta_error: Optional[str] = None
- """元数据处理错误"""
-
name: Optional[str] = None
"""数据源的名称"""
- sample_questions: Optional[str] = None
+ sample_questions: Optional[List[str]] = None
"""示例问题"""
schema_count: Optional[int] = None
"""库数量"""
+ sync_error: Optional[Dict[str, object]] = None
+ """同步错误信息"""
+
+ synced_at: Optional[datetime] = None
+ """上次同步完成时间"""
+
table_count: Optional[int] = None
"""表数量"""
diff --git a/src/asktable/types/datasource_update_params.py b/src/asktable/types/datasource_update_params.py
index ff22daff..d6b75aa8 100644
--- a/src/asktable/types/datasource_update_params.py
+++ b/src/asktable/types/datasource_update_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import Union, Iterable, Optional
+from typing import Dict, Union, Iterable, Optional
from typing_extensions import Literal, Required, TypeAlias, TypedDict
+from .._types import SequenceNotStr
+
__all__ = [
"DatasourceUpdateParams",
"AccessConfig",
@@ -44,6 +46,18 @@ class DatasourceUpdateParams(TypedDict, total=False):
"databend",
"sqlserver",
"mogdb",
+ "hologres",
+ "maxcompute",
+ "gaussdb",
+ "tdsqlmysql",
+ "tdsqlpg",
+ "kingbasees",
+ "gbase8c",
+ "yashandb",
+ "gbase8a",
+ "gaussdbdws",
+ "bitable",
+ "dap",
]
]
"""数据源引擎"""
@@ -51,21 +65,24 @@ class DatasourceUpdateParams(TypedDict, total=False):
field_count: Optional[int]
"""字段数量"""
- meta_error: Optional[str]
- """元数据处理错误"""
-
- meta_status: Optional[Literal["processing", "failed", "success", "unprocessed"]]
- """元数据处理状态"""
+ meta_status: Optional[Literal["unavailable", "available"]]
+ """数据源可用性"""
name: Optional[str]
"""数据源的名称"""
- sample_questions: Optional[str]
+ sample_questions: Optional[SequenceNotStr[str]]
"""示例问题"""
schema_count: Optional[int]
"""库数量"""
+ sync_error: Optional[Dict[str, object]]
+ """同步错误信息"""
+
+ sync_status: Optional[Literal["processing", "success", "failed", "warning"]]
+ """同步状态"""
+
table_count: Optional[int]
"""表数量"""
@@ -77,7 +94,7 @@ class AccessConfigAccessConfigConnectionUpdate(TypedDict, total=False):
db_version: Optional[str]
"""数据库版本"""
- extra_config: Optional[object]
+ extra_config: Optional[Dict[str, object]]
"""额外配置"""
host: Optional[str]
@@ -101,7 +118,7 @@ class AccessConfigAccessConfigFileUpdateFile(TypedDict, total=False):
filename: Required[str]
- custom_config: Optional[object]
+ custom_config: Optional[Dict[str, object]]
"""文件自定义配置"""
diff --git a/src/asktable/types/datasources/__init__.py b/src/asktable/types/datasources/__init__.py
index b015a299..a36de7e7 100644
--- a/src/asktable/types/datasources/__init__.py
+++ b/src/asktable/types/datasources/__init__.py
@@ -8,3 +8,4 @@
from .index_create_params import IndexCreateParams as IndexCreateParams
from .meta_annotate_params import MetaAnnotateParams as MetaAnnotateParams
from .upload_param_create_params import UploadParamCreateParams as UploadParamCreateParams
+from .upload_param_create_response import UploadParamCreateResponse as UploadParamCreateResponse
diff --git a/src/asktable/types/datasources/meta_create_params.py b/src/asktable/types/datasources/meta_create_params.py
index 86783588..10f3ac13 100644
--- a/src/asktable/types/datasources/meta_create_params.py
+++ b/src/asktable/types/datasources/meta_create_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import Dict, List, Optional
+from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
+from ..._types import SequenceNotStr
+
__all__ = ["MetaCreateParams", "Meta", "MetaSchemas", "MetaSchemasTables", "MetaSchemasTablesFields"]
@@ -15,7 +17,7 @@ class MetaCreateParams(TypedDict, total=False):
meta: Optional[Meta]
- selected_tables: Optional[Dict[str, List[str]]]
+ selected_tables: Optional[Dict[str, SequenceNotStr[str]]]
class MetaSchemasTablesFields(TypedDict, total=False):
@@ -58,7 +60,7 @@ class MetaSchemas(TypedDict, total=False):
origin_desc: Required[str]
"""schema description from database"""
- custom_configs: Optional[object]
+ custom_configs: Optional[Dict[str, object]]
"""custom configs"""
tables: Dict[str, MetaSchemasTables]
diff --git a/src/asktable/types/datasources/meta_update_params.py b/src/asktable/types/datasources/meta_update_params.py
index 2a14b685..dc0d45fa 100644
--- a/src/asktable/types/datasources/meta_update_params.py
+++ b/src/asktable/types/datasources/meta_update_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import Dict, List, Optional
+from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
+from ..._types import SequenceNotStr
+
__all__ = ["MetaUpdateParams", "Meta", "MetaSchemas", "MetaSchemasTables", "MetaSchemasTablesFields"]
@@ -13,7 +15,7 @@ class MetaUpdateParams(TypedDict, total=False):
meta: Optional[Meta]
- selected_tables: Optional[Dict[str, List[str]]]
+ selected_tables: Optional[Dict[str, SequenceNotStr[str]]]
class MetaSchemasTablesFields(TypedDict, total=False):
@@ -56,7 +58,7 @@ class MetaSchemas(TypedDict, total=False):
origin_desc: Required[str]
"""schema description from database"""
- custom_configs: Optional[object]
+ custom_configs: Optional[Dict[str, object]]
"""custom configs"""
tables: Dict[str, MetaSchemasTables]
diff --git a/src/asktable/types/datasources/upload_param_create_response.py b/src/asktable/types/datasources/upload_param_create_response.py
new file mode 100644
index 00000000..eec09f23
--- /dev/null
+++ b/src/asktable/types/datasources/upload_param_create_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["UploadParamCreateResponse"]
+
+UploadParamCreateResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/entry.py b/src/asktable/types/entry.py
index a4140a5d..70775b84 100644
--- a/src/asktable/types/entry.py
+++ b/src/asktable/types/entry.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Optional
+from typing import Dict, List, Optional
from datetime import datetime
from .._models import BaseModel
@@ -9,6 +9,8 @@
class Entry(BaseModel):
+ """Schema for document response"""
+
id: str
"""业务术语 ID"""
@@ -30,5 +32,5 @@ class Entry(BaseModel):
aliases: Optional[List[str]] = None
"""业务术语同义词"""
- payload: Optional[object] = None
+ payload: Optional[Dict[str, object]] = None
"""业务术语元数据"""
diff --git a/src/asktable/types/entry_with_definition.py b/src/asktable/types/entry_with_definition.py
index 9b76baff..74ac03d7 100644
--- a/src/asktable/types/entry_with_definition.py
+++ b/src/asktable/types/entry_with_definition.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Optional
+from typing import Dict, List, Optional
from datetime import datetime
from .._models import BaseModel
@@ -33,5 +33,5 @@ class EntryWithDefinition(BaseModel):
aliases: Optional[List[str]] = None
"""业务术语同义词"""
- payload: Optional[object] = None
+ payload: Optional[Dict[str, object]] = None
"""业务术语元数据"""
diff --git a/src/asktable/types/index.py b/src/asktable/types/index.py
index a558c037..ea46e49f 100644
--- a/src/asktable/types/index.py
+++ b/src/asktable/types/index.py
@@ -9,6 +9,8 @@
class Index(BaseModel):
+ """索引响应模型"""
+
id: str
"""索引 ID"""
diff --git a/src/asktable/types/meta.py b/src/asktable/types/meta.py
index f94d2037..b3442c15 100644
--- a/src/asktable/types/meta.py
+++ b/src/asktable/types/meta.py
@@ -6,7 +6,26 @@
from .._models import BaseModel
-__all__ = ["Meta", "Schemas", "SchemasTables", "SchemasTablesFields"]
+__all__ = ["Meta", "Schemas", "SchemasTables", "SchemasTablesFields", "SchemasTablesFieldsIndex"]
+
+
+class SchemasTablesFieldsIndex(BaseModel):
+ """索引信息"""
+
+ id: str
+ """索引 ID"""
+
+ distinct_count: Optional[int] = None
+ """不同值数量"""
+
+ index_value_count: Optional[int] = None
+ """索引值总数"""
+
+ status_msg: Optional[str] = None
+ """状态信息,为空表示成功"""
+
+ value_count: Optional[int] = None
+ """值总数"""
class SchemasTablesFields(BaseModel):
@@ -39,6 +58,9 @@ class SchemasTablesFields(BaseModel):
] = None
"""identifiable type"""
+ index: Optional[SchemasTablesFieldsIndex] = None
+ """索引信息"""
+
sample_data: Optional[str] = None
"""field sample data"""
@@ -83,7 +105,7 @@ class Schemas(BaseModel):
tables: Dict[str, SchemasTables]
- custom_configs: Optional[object] = None
+ custom_configs: Optional[Dict[str, object]] = None
"""custom configs"""
diff --git a/src/asktable/types/policy_create_params.py b/src/asktable/types/policy_create_params.py
index 9630207c..64ca1c7b 100644
--- a/src/asktable/types/policy_create_params.py
+++ b/src/asktable/types/policy_create_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import Dict, List, Optional
+from typing import Dict, Optional
from typing_extensions import Literal, Required, TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["PolicyCreateParams", "DatasetConfig", "DatasetConfigRegexPatterns"]
@@ -20,6 +22,12 @@ class PolicyCreateParams(TypedDict, total=False):
class DatasetConfigRegexPatterns(TypedDict, total=False):
+ """
+ 正则表达式。
+ - 描述:用于匹配指定数据源中Schema(DB)、Table和Field名称的三个正则表达式,即同时满足这三个正则表达式的DB、Table和Field才被允许访问。
+ - 注意:此字段为可选项。如果未提供,则默认包含指定数据源的所有数据。
+ """
+
fields_regex_pattern: Optional[str]
"""Field 正则表达式,空值默认全选"""
@@ -31,7 +39,9 @@ class DatasetConfigRegexPatterns(TypedDict, total=False):
class DatasetConfig(TypedDict, total=False):
- datasource_ids: Required[List[str]]
+ """数据集配置"""
+
+ datasource_ids: Required[SequenceNotStr[str]]
"""
数据源 ID 列表,必填。 - 描述:用于指定策略适用的数据源。可以使用通配符 _ 表示所
有数据源。 - 示例:["ds_id_1","ds_id_2"],["_"]。
@@ -44,7 +54,7 @@ class DatasetConfig(TypedDict, total=False):
注意:此字段为可选项。如果未提供,则默认包含指定数据源的所有数据。
"""
- rows_filters: Optional[Dict[str, List[str]]]
+ rows_filters: Optional[Dict[str, SequenceNotStr[str]]]
"""行级别过滤器。
- 描述:指定行级别的过滤器,满足条件的行才可访问。 用户在查询数据的时候会自动对
diff --git a/src/asktable/types/policy_list_params.py b/src/asktable/types/policy_list_params.py
index 5a9e7ea6..a8e91ab3 100644
--- a/src/asktable/types/policy_list_params.py
+++ b/src/asktable/types/policy_list_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["PolicyListParams"]
@@ -15,7 +17,7 @@ class PolicyListParams(TypedDict, total=False):
page: int
"""Page number"""
- policy_ids: Optional[List[str]]
+ policy_ids: Optional[SequenceNotStr[str]]
"""策略 ID 列表"""
size: int
diff --git a/src/asktable/types/policy_update_params.py b/src/asktable/types/policy_update_params.py
index dc1675b2..3aae252d 100644
--- a/src/asktable/types/policy_update_params.py
+++ b/src/asktable/types/policy_update_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import Dict, List, Iterable, Optional
+from typing import Dict, Iterable, Optional
from typing_extensions import Literal, Required, TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["PolicyUpdateParams", "DatasetConfig", "DatasetConfigRegexPatterns", "DatasetConfigRowsFilter"]
@@ -20,6 +22,12 @@ class PolicyUpdateParams(TypedDict, total=False):
class DatasetConfigRegexPatterns(TypedDict, total=False):
+ """
+ 正则表达式。
+ - 描述:用于匹配指定数据源中Schema(DB)、Table和Field名称的三个正则表达式,即同时满足这三个正则表达式的DB、Table和Field才被允许访问。
+ - 注意:此字段为可选项。如果未提供,则默认包含指定数据源的所有数据。
+ """
+
fields_regex_pattern: Optional[str]
"""Field 正则表达式,空值默认全选"""
@@ -46,12 +54,14 @@ class DatasetConfigRowsFilter(TypedDict, total=False):
table_regex: Required[str]
"""Table regex pattern"""
- variables: List[str]
+ variables: SequenceNotStr[str]
"""Jinja2 variables in the condition"""
class DatasetConfig(TypedDict, total=False):
- datasource_ids: Required[List[str]]
+ """数据集配置"""
+
+ datasource_ids: Required[SequenceNotStr[str]]
"""
数据源 ID 列表,必填。 - 描述:用于指定策略适用的数据源。可以使用通配符 _ 表示所
有数据源。 - 示例:["ds_id_1","ds_id_2"],["_"]。
diff --git a/src/asktable/types/preference_create_response.py b/src/asktable/types/preference_create_response.py
index 9016f33f..07844536 100644
--- a/src/asktable/types/preference_create_response.py
+++ b/src/asktable/types/preference_create_response.py
@@ -8,6 +8,8 @@
class PreferenceCreateResponse(BaseModel):
+ """Schema for preference response"""
+
id: str
"""偏好设置 ID"""
diff --git a/src/asktable/types/preference_retrieve_response.py b/src/asktable/types/preference_retrieve_response.py
index 36afa791..587c5d14 100644
--- a/src/asktable/types/preference_retrieve_response.py
+++ b/src/asktable/types/preference_retrieve_response.py
@@ -8,6 +8,8 @@
class PreferenceRetrieveResponse(BaseModel):
+ """Schema for preference response"""
+
id: str
"""偏好设置 ID"""
diff --git a/src/asktable/types/preference_update_response.py b/src/asktable/types/preference_update_response.py
index a317deae..e5b309bd 100644
--- a/src/asktable/types/preference_update_response.py
+++ b/src/asktable/types/preference_update_response.py
@@ -8,6 +8,8 @@
class PreferenceUpdateResponse(BaseModel):
+ """Schema for preference response"""
+
id: str
"""偏好设置 ID"""
diff --git a/src/asktable/types/project_list_model_groups_response.py b/src/asktable/types/project_list_model_groups_response.py
index 21df8bd4..a0edd01b 100644
--- a/src/asktable/types/project_list_model_groups_response.py
+++ b/src/asktable/types/project_list_model_groups_response.py
@@ -1,10 +1,94 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List
-from typing_extensions import TypeAlias
+from typing import Dict, List, Optional
+from datetime import datetime
+from typing_extensions import Literal, TypeAlias
-from .sys.model_group import ModelGroup
+from pydantic import Field as FieldInfo
-__all__ = ["ProjectListModelGroupsResponse"]
+from .._models import BaseModel
-ProjectListModelGroupsResponse: TypeAlias = List[ModelGroup]
+__all__ = [
+ "ProjectListModelGroupsResponse",
+ "ProjectListModelGroupsResponseItem",
+ "ProjectListModelGroupsResponseItemModels",
+ "ProjectListModelGroupsResponseItemModelConfigs",
+]
+
+
+class ProjectListModelGroupsResponseItemModels(BaseModel):
+ """角色→模型映射"""
+
+ agent: Optional[str] = None
+
+ canvas: Optional[str] = None
+
+ fast: Optional[str] = None
+
+ image: Optional[str] = None
+
+ omni: Optional[str] = None
+
+ report: Optional[str] = None
+
+ sql: Optional[str] = None
+
+
+class ProjectListModelGroupsResponseItemModelConfigs(BaseModel):
+ """Per-model 配置,key 为 model ID"""
+
+ capabilities: Optional[Dict[str, object]] = None
+
+ context_window: Optional[int] = None
+
+ display_name: Optional[str] = None
+
+ enabled: Optional[bool] = None
+
+ provider_options: Optional[Dict[str, object]] = None
+
+
+class ProjectListModelGroupsResponseItem(BaseModel):
+ id: str
+ """模型组 ID"""
+
+ api_key: str
+ """API 密钥"""
+
+ available_models: List[str]
+ """可用模型列表"""
+
+ base_url: str
+ """OpenAI 兼容 API 端点"""
+
+ created_at: datetime
+ """创建时间"""
+
+ extra_headers: Dict[str, str]
+ """额外请求头"""
+
+ models: ProjectListModelGroupsResponseItemModels
+ """角色 → 模型映射"""
+
+ modified_at: datetime
+ """修改时间"""
+
+ name: str
+ """模型组名称"""
+
+ api_format: Optional[Literal["openai_chat", "anthropic"]] = None
+ """API 协议格式"""
+
+ display_name: Optional[str] = None
+ """展示名称"""
+
+ is_default: Optional[bool] = None
+ """是否为默认组"""
+
+ api_model_configs: Optional[Dict[str, ProjectListModelGroupsResponseItemModelConfigs]] = FieldInfo(
+ alias="model_configs", default=None
+ )
+ """Per-model 配置"""
+
+
+ProjectListModelGroupsResponse: TypeAlias = List[ProjectListModelGroupsResponseItem]
diff --git a/src/asktable/types/query_response.py b/src/asktable/types/query_response.py
index f57289fb..089357bc 100644
--- a/src/asktable/types/query_response.py
+++ b/src/asktable/types/query_response.py
@@ -1,11 +1,11 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
from .._models import BaseModel
-__all__ = ["QueryResponse", "Query", "Request", "Timing"]
+__all__ = ["QueryResponse", "Query", "Request"]
class Query(BaseModel):
@@ -15,7 +15,7 @@ class Query(BaseModel):
parameterized_sql: Optional[str] = None
"""参数化后的 SQL 语句"""
- params: Optional[object] = None
+ params: Optional[Dict[str, object]] = None
"""参数"""
@@ -35,16 +35,10 @@ class Request(BaseModel):
数据
"""
- role_variables: Optional[object] = None
+ role_variables: Optional[Dict[str, object]] = None
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
-class Timing(BaseModel):
- llm_duration: Optional[float] = None
-
- total_duration: Optional[float] = None
-
-
class QueryResponse(BaseModel):
id: str
@@ -64,6 +58,4 @@ class QueryResponse(BaseModel):
err_msg: Optional[str] = None
- timing: Optional[Timing] = None
-
trace_id: Optional[str] = None
diff --git a/src/asktable/types/role_create_params.py b/src/asktable/types/role_create_params.py
index 4750a3e0..4e0679c7 100644
--- a/src/asktable/types/role_create_params.py
+++ b/src/asktable/types/role_create_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import Required, TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["RoleCreateParams"]
@@ -12,5 +14,5 @@ class RoleCreateParams(TypedDict, total=False):
name: Required[str]
"""名称"""
- policy_ids: Optional[List[str]]
+ policy_ids: Optional[SequenceNotStr[str]]
"""策略列表。注意:如果为空或者不传则不绑定策略"""
diff --git a/src/asktable/types/role_get_variables_params.py b/src/asktable/types/role_get_variables_params.py
index cebb567c..35a79f86 100644
--- a/src/asktable/types/role_get_variables_params.py
+++ b/src/asktable/types/role_get_variables_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["RoleGetVariablesParams"]
@@ -12,5 +14,5 @@ class RoleGetVariablesParams(TypedDict, total=False):
bot_id: Optional[str]
"""Bot ID"""
- datasource_ids: Optional[List[str]]
+ datasource_ids: Optional[SequenceNotStr[str]]
"""数据源 ID 列表"""
diff --git a/src/asktable/types/role_get_variables_response.py b/src/asktable/types/role_get_variables_response.py
new file mode 100644
index 00000000..54b74d57
--- /dev/null
+++ b/src/asktable/types/role_get_variables_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["RoleGetVariablesResponse"]
+
+RoleGetVariablesResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/role_list_params.py b/src/asktable/types/role_list_params.py
index 851c0904..a5e6e489 100644
--- a/src/asktable/types/role_list_params.py
+++ b/src/asktable/types/role_list_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["RoleListParams"]
@@ -15,7 +17,7 @@ class RoleListParams(TypedDict, total=False):
page: int
"""Page number"""
- role_ids: Optional[List[str]]
+ role_ids: Optional[SequenceNotStr[str]]
"""角色 ID 列表"""
size: int
diff --git a/src/asktable/types/role_update_params.py b/src/asktable/types/role_update_params.py
index 6cb3bb99..2cb20bea 100644
--- a/src/asktable/types/role_update_params.py
+++ b/src/asktable/types/role_update_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import TypedDict
+from .._types import SequenceNotStr
+
__all__ = ["RoleUpdateParams"]
@@ -12,5 +14,5 @@ class RoleUpdateParams(TypedDict, total=False):
name: Optional[str]
"""名称"""
- policy_ids: Optional[List[str]]
+ policy_ids: Optional[SequenceNotStr[str]]
"""策略列表。注意:如果为空或者不传则不绑定策略"""
diff --git a/src/asktable/types/secure_tunnel.py b/src/asktable/types/secure_tunnel.py
index c6223b4e..6a9cb647 100644
--- a/src/asktable/types/secure_tunnel.py
+++ b/src/asktable/types/secure_tunnel.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import Optional
+from typing import Dict, Optional
from datetime import datetime
from .._models import BaseModel
@@ -26,7 +26,7 @@ class SecureTunnel(BaseModel):
atst_server_port: Optional[int] = None
- info: Optional[object] = None
+ info: Optional[Dict[str, object]] = None
links_count: Optional[int] = None
diff --git a/src/asktable/types/securetunnel_update_params.py b/src/asktable/types/securetunnel_update_params.py
index 6322936a..d558a6c3 100644
--- a/src/asktable/types/securetunnel_update_params.py
+++ b/src/asktable/types/securetunnel_update_params.py
@@ -2,14 +2,14 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import TypedDict
__all__ = ["SecuretunnelUpdateParams"]
class SecuretunnelUpdateParams(TypedDict, total=False):
- client_info: Optional[object]
+ client_info: Optional[Dict[str, object]]
"""客户端信息"""
name: Optional[str]
diff --git a/src/asktable/types/shared/policy.py b/src/asktable/types/shared/policy.py
index 0fd1b6db..ac3aef11 100644
--- a/src/asktable/types/shared/policy.py
+++ b/src/asktable/types/shared/policy.py
@@ -10,6 +10,12 @@
class DatasetConfigRegexPatterns(BaseModel):
+ """
+ 正则表达式。
+ - 描述:用于匹配指定数据源中Schema(DB)、Table和Field名称的三个正则表达式,即同时满足这三个正则表达式的DB、Table和Field才被允许访问。
+ - 注意:此字段为可选项。如果未提供,则默认包含指定数据源的所有数据。
+ """
+
fields_regex_pattern: Optional[str] = None
"""Field 正则表达式,空值默认全选"""
diff --git a/src/asktable/types/sql_create_params.py b/src/asktable/types/sql_create_params.py
index 515dbd47..8ddf89f7 100644
--- a/src/asktable/types/sql_create_params.py
+++ b/src/asktable/types/sql_create_params.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Required, TypedDict
__all__ = ["SqlCreateParams"]
@@ -24,5 +24,5 @@ class SqlCreateParams(TypedDict, total=False):
数据
"""
- role_variables: Optional[object]
+ role_variables: Optional[Dict[str, object]]
"""在扮演这个角色时需要传递的变量值,用 Key-Value 形式传递"""
diff --git a/src/asktable/types/sy_update_config_params.py b/src/asktable/types/sy_update_config_params.py
deleted file mode 100644
index fd7c7246..00000000
--- a/src/asktable/types/sy_update_config_params.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing import Optional
-from typing_extensions import TypedDict
-
-__all__ = ["SyUpdateConfigParams"]
-
-
-class SyUpdateConfigParams(TypedDict, total=False):
- global_table_limit: Optional[int]
- """表限制数量"""
diff --git a/src/asktable/types/sy_update_config_response.py b/src/asktable/types/sy_update_config_response.py
deleted file mode 100644
index 9d77316d..00000000
--- a/src/asktable/types/sy_update_config_response.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from typing import Optional
-
-from .._models import BaseModel
-
-__all__ = ["SyUpdateConfigResponse"]
-
-
-class SyUpdateConfigResponse(BaseModel):
- global_table_limit: Optional[int] = None
- """表限制数量"""
diff --git a/src/asktable/types/sys/__init__.py b/src/asktable/types/sys/__init__.py
index 603cf14d..088f68ea 100644
--- a/src/asktable/types/sys/__init__.py
+++ b/src/asktable/types/sys/__init__.py
@@ -4,9 +4,10 @@
from .api_key import APIKey as APIKey
from .project import Project as Project
-from .model_group import ModelGroup as ModelGroup
from .project_list_params import ProjectListParams as ProjectListParams
from .project_create_params import ProjectCreateParams as ProjectCreateParams
from .project_import_params import ProjectImportParams as ProjectImportParams
from .project_update_params import ProjectUpdateParams as ProjectUpdateParams
+from .project_export_response import ProjectExportResponse as ProjectExportResponse
+from .project_import_response import ProjectImportResponse as ProjectImportResponse
from .project_model_groups_response import ProjectModelGroupsResponse as ProjectModelGroupsResponse
diff --git a/src/asktable/types/sys/model_group.py b/src/asktable/types/sys/model_group.py
deleted file mode 100644
index d37d6270..00000000
--- a/src/asktable/types/sys/model_group.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from ..._models import BaseModel
-
-__all__ = ["ModelGroup"]
-
-
-class ModelGroup(BaseModel):
- id: str
- """模型组 ID"""
-
- agent: str
- """Agent 模型"""
-
- fast: str
- """快速模型"""
-
- image: str
- """图片模型"""
-
- name: str
- """模型组名称"""
-
- omni: str
- """通用模型"""
-
- sql: str
- """SQL 模型"""
diff --git a/src/asktable/types/sys/project_export_response.py b/src/asktable/types/sys/project_export_response.py
new file mode 100644
index 00000000..30135eed
--- /dev/null
+++ b/src/asktable/types/sys/project_export_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["ProjectExportResponse"]
+
+ProjectExportResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/sys/project_import_params.py b/src/asktable/types/sys/project_import_params.py
index d244232a..52b5fdb6 100644
--- a/src/asktable/types/sys/project_import_params.py
+++ b/src/asktable/types/sys/project_import_params.py
@@ -2,10 +2,11 @@
from __future__ import annotations
+from typing import Dict
from typing_extensions import Required, TypedDict
__all__ = ["ProjectImportParams"]
class ProjectImportParams(TypedDict, total=False):
- body: Required[object]
+ body: Required[Dict[str, object]]
diff --git a/src/asktable/types/sys/project_import_response.py b/src/asktable/types/sys/project_import_response.py
new file mode 100644
index 00000000..e98dcd60
--- /dev/null
+++ b/src/asktable/types/sys/project_import_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["ProjectImportResponse"]
+
+ProjectImportResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/sys/project_list_params.py b/src/asktable/types/sys/project_list_params.py
index f0b103dc..661b42ad 100644
--- a/src/asktable/types/sys/project_list_params.py
+++ b/src/asktable/types/sys/project_list_params.py
@@ -2,9 +2,11 @@
from __future__ import annotations
-from typing import List, Optional
+from typing import Optional
from typing_extensions import TypedDict
+from ..._types import SequenceNotStr
+
__all__ = ["ProjectListParams"]
@@ -12,7 +14,7 @@ class ProjectListParams(TypedDict, total=False):
page: int
"""Page number"""
- project_ids: Optional[List[str]]
+ project_ids: Optional[SequenceNotStr[str]]
"""项目 ID 列表"""
size: int
diff --git a/src/asktable/types/sys/project_model_groups_response.py b/src/asktable/types/sys/project_model_groups_response.py
index 5a4939f3..b9a3c55a 100644
--- a/src/asktable/types/sys/project_model_groups_response.py
+++ b/src/asktable/types/sys/project_model_groups_response.py
@@ -1,10 +1,94 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List
-from typing_extensions import TypeAlias
+from typing import Dict, List, Optional
+from datetime import datetime
+from typing_extensions import Literal, TypeAlias
-from .model_group import ModelGroup
+from pydantic import Field as FieldInfo
-__all__ = ["ProjectModelGroupsResponse"]
+from ..._models import BaseModel
-ProjectModelGroupsResponse: TypeAlias = List[ModelGroup]
+__all__ = [
+ "ProjectModelGroupsResponse",
+ "ProjectModelGroupsResponseItem",
+ "ProjectModelGroupsResponseItemModels",
+ "ProjectModelGroupsResponseItemModelConfigs",
+]
+
+
+class ProjectModelGroupsResponseItemModels(BaseModel):
+ """角色→模型映射"""
+
+ agent: Optional[str] = None
+
+ canvas: Optional[str] = None
+
+ fast: Optional[str] = None
+
+ image: Optional[str] = None
+
+ omni: Optional[str] = None
+
+ report: Optional[str] = None
+
+ sql: Optional[str] = None
+
+
+class ProjectModelGroupsResponseItemModelConfigs(BaseModel):
+ """Per-model 配置,key 为 model ID"""
+
+ capabilities: Optional[Dict[str, object]] = None
+
+ context_window: Optional[int] = None
+
+ display_name: Optional[str] = None
+
+ enabled: Optional[bool] = None
+
+ provider_options: Optional[Dict[str, object]] = None
+
+
+class ProjectModelGroupsResponseItem(BaseModel):
+ id: str
+ """模型组 ID"""
+
+ api_key: str
+ """API 密钥"""
+
+ available_models: List[str]
+ """可用模型列表"""
+
+ base_url: str
+ """OpenAI 兼容 API 端点"""
+
+ created_at: datetime
+ """创建时间"""
+
+ extra_headers: Dict[str, str]
+ """额外请求头"""
+
+ models: ProjectModelGroupsResponseItemModels
+ """角色 → 模型映射"""
+
+ modified_at: datetime
+ """修改时间"""
+
+ name: str
+ """模型组名称"""
+
+ api_format: Optional[Literal["openai_chat", "anthropic"]] = None
+ """API 协议格式"""
+
+ display_name: Optional[str] = None
+ """展示名称"""
+
+ is_default: Optional[bool] = None
+ """是否为默认组"""
+
+ api_model_configs: Optional[Dict[str, ProjectModelGroupsResponseItemModelConfigs]] = FieldInfo(
+ alias="model_configs", default=None
+ )
+ """Per-model 配置"""
+
+
+ProjectModelGroupsResponse: TypeAlias = List[ProjectModelGroupsResponseItem]
diff --git a/src/asktable/types/sys/projects/__init__.py b/src/asktable/types/sys/projects/__init__.py
index 6fd494c1..baa4c7fc 100644
--- a/src/asktable/types/sys/projects/__init__.py
+++ b/src/asktable/types/sys/projects/__init__.py
@@ -6,3 +6,4 @@
from .api_key_list_response import APIKeyListResponse as APIKeyListResponse
from .api_key_create_response import APIKeyCreateResponse as APIKeyCreateResponse
from .api_key_create_token_params import APIKeyCreateTokenParams as APIKeyCreateTokenParams
+from .api_key_create_token_response import APIKeyCreateTokenResponse as APIKeyCreateTokenResponse
diff --git a/src/asktable/types/sys/projects/api_key_create_token_params.py b/src/asktable/types/sys/projects/api_key_create_token_params.py
index 212976c8..a98751a9 100644
--- a/src/asktable/types/sys/projects/api_key_create_token_params.py
+++ b/src/asktable/types/sys/projects/api_key_create_token_params.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Optional
+from typing import Dict, Optional
from typing_extensions import Literal, TypedDict
__all__ = ["APIKeyCreateTokenParams", "ChatRole"]
@@ -18,13 +18,15 @@ class APIKeyCreateTokenParams(TypedDict, total=False):
token_ttl: int
"""The time-to-live for the token in seconds"""
- user_profile: Optional[object]
+ user_profile: Optional[Dict[str, object]]
"""Optional user profile data"""
class ChatRole(TypedDict, total=False):
+ """The chat role"""
+
role_id: Optional[str]
"""The chat role ID"""
- role_variables: Optional[object]
+ role_variables: Optional[Dict[str, object]]
"""The chat role variables"""
diff --git a/src/asktable/types/sys/projects/api_key_create_token_response.py b/src/asktable/types/sys/projects/api_key_create_token_response.py
new file mode 100644
index 00000000..106eedb6
--- /dev/null
+++ b/src/asktable/types/sys/projects/api_key_create_token_response.py
@@ -0,0 +1,8 @@
+# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
+
+from typing import Dict
+from typing_extensions import TypeAlias
+
+__all__ = ["APIKeyCreateTokenResponse"]
+
+APIKeyCreateTokenResponse: TypeAlias = Dict[str, object]
diff --git a/src/asktable/types/tool_message.py b/src/asktable/types/tool_message.py
index bbbea211..ea939080 100644
--- a/src/asktable/types/tool_message.py
+++ b/src/asktable/types/tool_message.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Optional
+from typing import Dict, List, Optional
from datetime import datetime
from typing_extensions import Literal
@@ -10,9 +10,9 @@
class ContentAttachment(BaseModel):
- info: object
+ info: Dict[str, object]
- type: str
+ type: Literal["data_json"]
"""The type of the attachment"""
diff --git a/src/asktable/types/training_create_params.py b/src/asktable/types/training_create_params.py
deleted file mode 100644
index f8dec4df..00000000
--- a/src/asktable/types/training_create_params.py
+++ /dev/null
@@ -1,35 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing import Iterable, Optional
-from typing_extensions import Required, TypedDict
-
-__all__ = ["TrainingCreateParams", "Body"]
-
-
-class TrainingCreateParams(TypedDict, total=False):
- datasource_id: Required[str]
- """数据源 ID"""
-
- body: Required[Iterable[Body]]
-
-
-class Body(TypedDict, total=False):
- question: Required[str]
- """用户问题"""
-
- sql: Required[str]
- """用户问题对应的 SQL"""
-
- active: bool
- """是否启用"""
-
- chat_id: Optional[str]
- """聊天 ID"""
-
- msg_id: Optional[str]
- """消息 ID"""
-
- role_id: Optional[str]
- """角色 ID"""
diff --git a/src/asktable/types/training_create_response.py b/src/asktable/types/training_create_response.py
deleted file mode 100644
index 278021f5..00000000
--- a/src/asktable/types/training_create_response.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from typing import List, Optional
-from datetime import datetime
-from typing_extensions import Literal, TypeAlias
-
-from .._models import BaseModel
-
-__all__ = ["TrainingCreateResponse", "TrainingCreateResponseItem"]
-
-
-class TrainingCreateResponseItem(BaseModel):
- id: str
- """训练数据 ID"""
-
- created_at: datetime
- """创建时间"""
-
- datasource_id: str
- """数据源 ID"""
-
- modified_at: datetime
- """更新时间"""
-
- project_id: str
- """项目 ID"""
-
- question: str
- """用户问题"""
-
- source: Literal["import", "auto"]
- """训练数据来源"""
-
- sql: str
- """用户问题对应的 SQL"""
-
- active: Optional[bool] = None
- """是否启用"""
-
- chat_id: Optional[str] = None
- """聊天 ID"""
-
- msg_id: Optional[str] = None
- """消息 ID"""
-
- role_id: Optional[str] = None
- """角色 ID"""
-
-
-TrainingCreateResponse: TypeAlias = List[TrainingCreateResponseItem]
diff --git a/src/asktable/types/training_delete_params.py b/src/asktable/types/training_delete_params.py
deleted file mode 100644
index e7325e7f..00000000
--- a/src/asktable/types/training_delete_params.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing_extensions import Required, TypedDict
-
-__all__ = ["TrainingDeleteParams"]
-
-
-class TrainingDeleteParams(TypedDict, total=False):
- datasource_id: Required[str]
- """数据源 ID"""
diff --git a/src/asktable/types/training_list_params.py b/src/asktable/types/training_list_params.py
deleted file mode 100644
index bdf03a57..00000000
--- a/src/asktable/types/training_list_params.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing_extensions import Required, TypedDict
-
-__all__ = ["TrainingListParams"]
-
-
-class TrainingListParams(TypedDict, total=False):
- datasource_id: Required[str]
- """数据源 ID"""
-
- page: int
- """Page number"""
-
- size: int
- """Page size"""
diff --git a/src/asktable/types/training_list_response.py b/src/asktable/types/training_list_response.py
deleted file mode 100644
index bc22d53a..00000000
--- a/src/asktable/types/training_list_response.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from typing import Optional
-from datetime import datetime
-from typing_extensions import Literal
-
-from .._models import BaseModel
-
-__all__ = ["TrainingListResponse"]
-
-
-class TrainingListResponse(BaseModel):
- id: str
- """训练数据 ID"""
-
- created_at: datetime
- """创建时间"""
-
- datasource_id: str
- """数据源 ID"""
-
- modified_at: datetime
- """更新时间"""
-
- project_id: str
- """项目 ID"""
-
- question: str
- """用户问题"""
-
- source: Literal["import", "auto"]
- """训练数据来源"""
-
- sql: str
- """用户问题对应的 SQL"""
-
- active: Optional[bool] = None
- """是否启用"""
-
- chat_id: Optional[str] = None
- """聊天 ID"""
-
- msg_id: Optional[str] = None
- """消息 ID"""
-
- role_id: Optional[str] = None
- """角色 ID"""
diff --git a/src/asktable/types/training_update_params.py b/src/asktable/types/training_update_params.py
deleted file mode 100644
index 82d56a3f..00000000
--- a/src/asktable/types/training_update_params.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-from typing import Optional
-from typing_extensions import Required, TypedDict
-
-__all__ = ["TrainingUpdateParams"]
-
-
-class TrainingUpdateParams(TypedDict, total=False):
- datasource_id: Required[str]
- """数据源 ID"""
-
- active: Optional[bool]
- """是否启用"""
-
- question: Optional[str]
- """用户问题"""
-
- role_id: Optional[str]
- """角色 ID"""
-
- sql: Optional[str]
- """用户问题对应的 SQL"""
diff --git a/src/asktable/types/training_update_response.py b/src/asktable/types/training_update_response.py
deleted file mode 100644
index 3817394d..00000000
--- a/src/asktable/types/training_update_response.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from typing import Optional
-from datetime import datetime
-from typing_extensions import Literal
-
-from .._models import BaseModel
-
-__all__ = ["TrainingUpdateResponse"]
-
-
-class TrainingUpdateResponse(BaseModel):
- id: str
- """训练数据 ID"""
-
- created_at: datetime
- """创建时间"""
-
- datasource_id: str
- """数据源 ID"""
-
- modified_at: datetime
- """更新时间"""
-
- project_id: str
- """项目 ID"""
-
- question: str
- """用户问题"""
-
- source: Literal["import", "auto"]
- """训练数据来源"""
-
- sql: str
- """用户问题对应的 SQL"""
-
- active: Optional[bool] = None
- """是否启用"""
-
- chat_id: Optional[str] = None
- """聊天 ID"""
-
- msg_id: Optional[str] = None
- """消息 ID"""
-
- role_id: Optional[str] = None
- """角色 ID"""
diff --git a/src/asktable/types/user/project_retrieve_model_groups_response.py b/src/asktable/types/user/project_retrieve_model_groups_response.py
index d2f36279..2f32a335 100644
--- a/src/asktable/types/user/project_retrieve_model_groups_response.py
+++ b/src/asktable/types/user/project_retrieve_model_groups_response.py
@@ -1,10 +1,94 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List
-from typing_extensions import TypeAlias
+from typing import Dict, List, Optional
+from datetime import datetime
+from typing_extensions import Literal, TypeAlias
-from ..sys.model_group import ModelGroup
+from pydantic import Field as FieldInfo
-__all__ = ["ProjectRetrieveModelGroupsResponse"]
+from ..._models import BaseModel
-ProjectRetrieveModelGroupsResponse: TypeAlias = List[ModelGroup]
+__all__ = [
+ "ProjectRetrieveModelGroupsResponse",
+ "ProjectRetrieveModelGroupsResponseItem",
+ "ProjectRetrieveModelGroupsResponseItemModels",
+ "ProjectRetrieveModelGroupsResponseItemModelConfigs",
+]
+
+
+class ProjectRetrieveModelGroupsResponseItemModels(BaseModel):
+ """角色→模型映射"""
+
+ agent: Optional[str] = None
+
+ canvas: Optional[str] = None
+
+ fast: Optional[str] = None
+
+ image: Optional[str] = None
+
+ omni: Optional[str] = None
+
+ report: Optional[str] = None
+
+ sql: Optional[str] = None
+
+
+class ProjectRetrieveModelGroupsResponseItemModelConfigs(BaseModel):
+ """Per-model 配置,key 为 model ID"""
+
+ capabilities: Optional[Dict[str, object]] = None
+
+ context_window: Optional[int] = None
+
+ display_name: Optional[str] = None
+
+ enabled: Optional[bool] = None
+
+ provider_options: Optional[Dict[str, object]] = None
+
+
+class ProjectRetrieveModelGroupsResponseItem(BaseModel):
+ id: str
+ """模型组 ID"""
+
+ api_key: str
+ """API 密钥"""
+
+ available_models: List[str]
+ """可用模型列表"""
+
+ base_url: str
+ """OpenAI 兼容 API 端点"""
+
+ created_at: datetime
+ """创建时间"""
+
+ extra_headers: Dict[str, str]
+ """额外请求头"""
+
+ models: ProjectRetrieveModelGroupsResponseItemModels
+ """角色 → 模型映射"""
+
+ modified_at: datetime
+ """修改时间"""
+
+ name: str
+ """模型组名称"""
+
+ api_format: Optional[Literal["openai_chat", "anthropic"]] = None
+ """API 协议格式"""
+
+ display_name: Optional[str] = None
+ """展示名称"""
+
+ is_default: Optional[bool] = None
+ """是否为默认组"""
+
+ api_model_configs: Optional[Dict[str, ProjectRetrieveModelGroupsResponseItemModelConfigs]] = FieldInfo(
+ alias="model_configs", default=None
+ )
+ """Per-model 配置"""
+
+
+ProjectRetrieveModelGroupsResponse: TypeAlias = List[ProjectRetrieveModelGroupsResponseItem]
diff --git a/src/asktable/types/user_message.py b/src/asktable/types/user_message.py
index c7ea626b..5660431a 100644
--- a/src/asktable/types/user_message.py
+++ b/src/asktable/types/user_message.py
@@ -1,6 +1,6 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-from typing import List, Optional
+from typing import Dict, List, Optional
from datetime import datetime
from typing_extensions import Literal
@@ -10,9 +10,9 @@
class ContentAttachment(BaseModel):
- info: object
+ info: Dict[str, object]
- type: str
+ type: Literal["data_json"]
"""The type of the attachment"""
diff --git a/tests/api_resources/ats/test_test_case.py b/tests/api_resources/ats/test_test_case.py
index 7a9a1281..fbb3d808 100644
--- a/tests/api_resources/ats/test_test_case.py
+++ b/tests/api_resources/ats/test_test_case.py
@@ -39,7 +39,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
expected_sql="expected_sql",
question="question",
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
)
assert_matches_type(TestCaseCreateResponse, test_case, path=["response"])
@@ -146,7 +146,7 @@ def test_method_update_with_all_params(self, client: Asktable) -> None:
expected_sql="expected_sql",
question="question",
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
)
assert_matches_type(TestCaseUpdateResponse, test_case, path=["response"])
@@ -315,7 +315,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
expected_sql="expected_sql",
question="question",
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
)
assert_matches_type(TestCaseCreateResponse, test_case, path=["response"])
@@ -422,7 +422,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncAsktable)
expected_sql="expected_sql",
question="question",
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
)
assert_matches_type(TestCaseUpdateResponse, test_case, path=["response"])
diff --git a/tests/api_resources/chats/test_messages.py b/tests/api_resources/chats/test_messages.py
index 93280c1b..8bae4adf 100644
--- a/tests/api_resources/chats/test_messages.py
+++ b/tests/api_resources/chats/test_messages.py
@@ -26,7 +26,15 @@ class TestMessages:
def test_method_create(self, client: Asktable) -> None:
message = client.chats.messages.create(
chat_id="chat_id",
- question="question",
+ )
+ assert_matches_type(MessageCreateResponse, message, path=["response"])
+
+ @parametrize
+ def test_method_create_with_all_params(self, client: Asktable) -> None:
+ message = client.chats.messages.create(
+ chat_id="chat_id",
+ query_question="question",
+ body_question="question",
)
assert_matches_type(MessageCreateResponse, message, path=["response"])
@@ -34,7 +42,6 @@ def test_method_create(self, client: Asktable) -> None:
def test_raw_response_create(self, client: Asktable) -> None:
response = client.chats.messages.with_raw_response.create(
chat_id="chat_id",
- question="question",
)
assert response.is_closed is True
@@ -46,7 +53,6 @@ def test_raw_response_create(self, client: Asktable) -> None:
def test_streaming_response_create(self, client: Asktable) -> None:
with client.chats.messages.with_streaming_response.create(
chat_id="chat_id",
- question="question",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -61,7 +67,6 @@ def test_path_params_create(self, client: Asktable) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `chat_id` but received ''"):
client.chats.messages.with_raw_response.create(
chat_id="",
- question="question",
)
@parametrize
@@ -169,7 +174,15 @@ class TestAsyncMessages:
async def test_method_create(self, async_client: AsyncAsktable) -> None:
message = await async_client.chats.messages.create(
chat_id="chat_id",
- question="question",
+ )
+ assert_matches_type(MessageCreateResponse, message, path=["response"])
+
+ @parametrize
+ async def test_method_create_with_all_params(self, async_client: AsyncAsktable) -> None:
+ message = await async_client.chats.messages.create(
+ chat_id="chat_id",
+ query_question="question",
+ body_question="question",
)
assert_matches_type(MessageCreateResponse, message, path=["response"])
@@ -177,7 +190,6 @@ async def test_method_create(self, async_client: AsyncAsktable) -> None:
async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
response = await async_client.chats.messages.with_raw_response.create(
chat_id="chat_id",
- question="question",
)
assert response.is_closed is True
@@ -189,7 +201,6 @@ async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
async def test_streaming_response_create(self, async_client: AsyncAsktable) -> None:
async with async_client.chats.messages.with_streaming_response.create(
chat_id="chat_id",
- question="question",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -204,7 +215,6 @@ async def test_path_params_create(self, async_client: AsyncAsktable) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `chat_id` but received ''"):
await async_client.chats.messages.with_raw_response.create(
chat_id="",
- question="question",
)
@parametrize
diff --git a/tests/api_resources/datasources/test_meta.py b/tests/api_resources/datasources/test_meta.py
index ae7a8f6e..2dc54671 100644
--- a/tests/api_resources/datasources/test_meta.py
+++ b/tests/api_resources/datasources/test_meta.py
@@ -35,7 +35,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
"foo": {
"name": "name",
"origin_desc": "origin_desc",
- "custom_configs": {},
+ "custom_configs": {"foo": "bar"},
"tables": {
"foo": {
"name": "name",
@@ -146,7 +146,7 @@ def test_method_update_with_all_params(self, client: Asktable) -> None:
"foo": {
"name": "name",
"origin_desc": "origin_desc",
- "custom_configs": {},
+ "custom_configs": {"foo": "bar"},
"tables": {
"foo": {
"name": "name",
@@ -268,7 +268,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
"foo": {
"name": "name",
"origin_desc": "origin_desc",
- "custom_configs": {},
+ "custom_configs": {"foo": "bar"},
"tables": {
"foo": {
"name": "name",
@@ -379,7 +379,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncAsktable)
"foo": {
"name": "name",
"origin_desc": "origin_desc",
- "custom_configs": {},
+ "custom_configs": {"foo": "bar"},
"tables": {
"foo": {
"name": "name",
diff --git a/tests/api_resources/datasources/test_upload_params.py b/tests/api_resources/datasources/test_upload_params.py
index cb22379f..6b3dad48 100644
--- a/tests/api_resources/datasources/test_upload_params.py
+++ b/tests/api_resources/datasources/test_upload_params.py
@@ -9,6 +9,7 @@
from asktable import Asktable, AsyncAsktable
from tests.utils import assert_matches_type
+from asktable.types.datasources import UploadParamCreateResponse
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@@ -19,7 +20,7 @@ class TestUploadParams:
@parametrize
def test_method_create(self, client: Asktable) -> None:
upload_param = client.datasources.upload_params.create()
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
@parametrize
def test_method_create_with_all_params(self, client: Asktable) -> None:
@@ -27,7 +28,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
expiration=60,
file_max_size=524288000,
)
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
@parametrize
def test_raw_response_create(self, client: Asktable) -> None:
@@ -36,7 +37,7 @@ def test_raw_response_create(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
upload_param = response.parse()
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
@parametrize
def test_streaming_response_create(self, client: Asktable) -> None:
@@ -45,7 +46,7 @@ def test_streaming_response_create(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
upload_param = response.parse()
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -58,7 +59,7 @@ class TestAsyncUploadParams:
@parametrize
async def test_method_create(self, async_client: AsyncAsktable) -> None:
upload_param = await async_client.datasources.upload_params.create()
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
@parametrize
async def test_method_create_with_all_params(self, async_client: AsyncAsktable) -> None:
@@ -66,7 +67,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
expiration=60,
file_max_size=524288000,
)
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
@parametrize
async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
@@ -75,7 +76,7 @@ async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
upload_param = await response.parse()
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
@parametrize
async def test_streaming_response_create(self, async_client: AsyncAsktable) -> None:
@@ -84,6 +85,6 @@ async def test_streaming_response_create(self, async_client: AsyncAsktable) -> N
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
upload_param = await response.parse()
- assert_matches_type(object, upload_param, path=["response"])
+ assert_matches_type(UploadParamCreateResponse, upload_param, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/sys/projects/test_api_keys.py b/tests/api_resources/sys/projects/test_api_keys.py
index 51966f80..79be98a6 100644
--- a/tests/api_resources/sys/projects/test_api_keys.py
+++ b/tests/api_resources/sys/projects/test_api_keys.py
@@ -12,6 +12,7 @@
from asktable.types.sys.projects import (
APIKeyListResponse,
APIKeyCreateResponse,
+ APIKeyCreateTokenResponse,
)
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@@ -153,7 +154,7 @@ def test_method_create_token(self, client: Asktable) -> None:
api_key = client.sys.projects.api_keys.create_token(
project_id="project_id",
)
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
@parametrize
def test_method_create_token_with_all_params(self, client: Asktable) -> None:
@@ -162,12 +163,12 @@ def test_method_create_token_with_all_params(self, client: Asktable) -> None:
ak_role="asker",
chat_role={
"role_id": "1",
- "role_variables": {"id": "42"},
+ "role_variables": {"id": "bar"},
},
token_ttl=900,
- user_profile={"name": "张三"},
+ user_profile={"name": "bar"},
)
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
@parametrize
def test_raw_response_create_token(self, client: Asktable) -> None:
@@ -178,7 +179,7 @@ def test_raw_response_create_token(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
api_key = response.parse()
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
@parametrize
def test_streaming_response_create_token(self, client: Asktable) -> None:
@@ -189,7 +190,7 @@ def test_streaming_response_create_token(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
api_key = response.parse()
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -339,7 +340,7 @@ async def test_method_create_token(self, async_client: AsyncAsktable) -> None:
api_key = await async_client.sys.projects.api_keys.create_token(
project_id="project_id",
)
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
@parametrize
async def test_method_create_token_with_all_params(self, async_client: AsyncAsktable) -> None:
@@ -348,12 +349,12 @@ async def test_method_create_token_with_all_params(self, async_client: AsyncAskt
ak_role="asker",
chat_role={
"role_id": "1",
- "role_variables": {"id": "42"},
+ "role_variables": {"id": "bar"},
},
token_ttl=900,
- user_profile={"name": "张三"},
+ user_profile={"name": "bar"},
)
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
@parametrize
async def test_raw_response_create_token(self, async_client: AsyncAsktable) -> None:
@@ -364,7 +365,7 @@ async def test_raw_response_create_token(self, async_client: AsyncAsktable) -> N
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
api_key = await response.parse()
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
@parametrize
async def test_streaming_response_create_token(self, async_client: AsyncAsktable) -> None:
@@ -375,7 +376,7 @@ async def test_streaming_response_create_token(self, async_client: AsyncAsktable
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
api_key = await response.parse()
- assert_matches_type(object, api_key, path=["response"])
+ assert_matches_type(APIKeyCreateTokenResponse, api_key, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/sys/test_projects.py b/tests/api_resources/sys/test_projects.py
index 8b8d87c3..26007a3a 100644
--- a/tests/api_resources/sys/test_projects.py
+++ b/tests/api_resources/sys/test_projects.py
@@ -11,6 +11,8 @@
from tests.utils import assert_matches_type
from asktable.types.sys import (
Project,
+ ProjectExportResponse,
+ ProjectImportResponse,
ProjectModelGroupsResponse,
)
from asktable.pagination import SyncPage, AsyncPage
@@ -215,7 +217,7 @@ def test_method_export(self, client: Asktable) -> None:
project = client.sys.projects.export(
"project_id",
)
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectExportResponse, project, path=["response"])
@parametrize
def test_raw_response_export(self, client: Asktable) -> None:
@@ -226,7 +228,7 @@ def test_raw_response_export(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectExportResponse, project, path=["response"])
@parametrize
def test_streaming_response_export(self, client: Asktable) -> None:
@@ -237,7 +239,7 @@ def test_streaming_response_export(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectExportResponse, project, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -251,31 +253,31 @@ def test_path_params_export(self, client: Asktable) -> None:
@parametrize
def test_method_import(self, client: Asktable) -> None:
project = client.sys.projects.import_(
- body={},
+ body={"foo": "bar"},
)
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectImportResponse, project, path=["response"])
@parametrize
def test_raw_response_import(self, client: Asktable) -> None:
response = client.sys.projects.with_raw_response.import_(
- body={},
+ body={"foo": "bar"},
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectImportResponse, project, path=["response"])
@parametrize
def test_streaming_response_import(self, client: Asktable) -> None:
with client.sys.projects.with_streaming_response.import_(
- body={},
+ body={"foo": "bar"},
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectImportResponse, project, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -504,7 +506,7 @@ async def test_method_export(self, async_client: AsyncAsktable) -> None:
project = await async_client.sys.projects.export(
"project_id",
)
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectExportResponse, project, path=["response"])
@parametrize
async def test_raw_response_export(self, async_client: AsyncAsktable) -> None:
@@ -515,7 +517,7 @@ async def test_raw_response_export(self, async_client: AsyncAsktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = await response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectExportResponse, project, path=["response"])
@parametrize
async def test_streaming_response_export(self, async_client: AsyncAsktable) -> None:
@@ -526,7 +528,7 @@ async def test_streaming_response_export(self, async_client: AsyncAsktable) -> N
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = await response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectExportResponse, project, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -540,31 +542,31 @@ async def test_path_params_export(self, async_client: AsyncAsktable) -> None:
@parametrize
async def test_method_import(self, async_client: AsyncAsktable) -> None:
project = await async_client.sys.projects.import_(
- body={},
+ body={"foo": "bar"},
)
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectImportResponse, project, path=["response"])
@parametrize
async def test_raw_response_import(self, async_client: AsyncAsktable) -> None:
response = await async_client.sys.projects.with_raw_response.import_(
- body={},
+ body={"foo": "bar"},
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = await response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectImportResponse, project, path=["response"])
@parametrize
async def test_streaming_response_import(self, async_client: AsyncAsktable) -> None:
async with async_client.sys.projects.with_streaming_response.import_(
- body={},
+ body={"foo": "bar"},
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
project = await response.parse()
- assert_matches_type(object, project, path=["response"])
+ assert_matches_type(ProjectImportResponse, project, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/test_answers.py b/tests/api_resources/test_answers.py
index dc2260f5..cb0f6de6 100644
--- a/tests/api_resources/test_answers.py
+++ b/tests/api_resources/test_answers.py
@@ -33,7 +33,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
question="question",
max_rows=0,
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
with_json=True,
)
assert_matches_type(AnswerResponse, answer, path=["response"])
@@ -119,7 +119,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
question="question",
max_rows=0,
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
with_json=True,
)
assert_matches_type(AnswerResponse, answer, path=["response"])
diff --git a/tests/api_resources/test_ats.py b/tests/api_resources/test_ats.py
index 7dc37e89..f87e088b 100644
--- a/tests/api_resources/test_ats.py
+++ b/tests/api_resources/test_ats.py
@@ -139,9 +139,7 @@ def test_path_params_update(self, client: Asktable) -> None:
@parametrize
def test_method_list(self, client: Asktable) -> None:
- ats = client.ats.list(
- datasource_id="datasource_id",
- )
+ ats = client.ats.list()
assert_matches_type(SyncPage[ATSListResponse], ats, path=["response"])
@parametrize
@@ -155,9 +153,7 @@ def test_method_list_with_all_params(self, client: Asktable) -> None:
@parametrize
def test_raw_response_list(self, client: Asktable) -> None:
- response = client.ats.with_raw_response.list(
- datasource_id="datasource_id",
- )
+ response = client.ats.with_raw_response.list()
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -166,9 +162,7 @@ def test_raw_response_list(self, client: Asktable) -> None:
@parametrize
def test_streaming_response_list(self, client: Asktable) -> None:
- with client.ats.with_streaming_response.list(
- datasource_id="datasource_id",
- ) as response:
+ with client.ats.with_streaming_response.list() as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -341,9 +335,7 @@ async def test_path_params_update(self, async_client: AsyncAsktable) -> None:
@parametrize
async def test_method_list(self, async_client: AsyncAsktable) -> None:
- ats = await async_client.ats.list(
- datasource_id="datasource_id",
- )
+ ats = await async_client.ats.list()
assert_matches_type(AsyncPage[ATSListResponse], ats, path=["response"])
@parametrize
@@ -357,9 +349,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncAsktable) ->
@parametrize
async def test_raw_response_list(self, async_client: AsyncAsktable) -> None:
- response = await async_client.ats.with_raw_response.list(
- datasource_id="datasource_id",
- )
+ response = await async_client.ats.with_raw_response.list()
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -368,9 +358,7 @@ async def test_raw_response_list(self, async_client: AsyncAsktable) -> None:
@parametrize
async def test_streaming_response_list(self, async_client: AsyncAsktable) -> None:
- async with async_client.ats.with_streaming_response.list(
- datasource_id="datasource_id",
- ) as response:
+ async with async_client.ats.with_streaming_response.list() as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
diff --git a/tests/api_resources/test_auth.py b/tests/api_resources/test_auth.py
index e08b155e..0b637b87 100644
--- a/tests/api_resources/test_auth.py
+++ b/tests/api_resources/test_auth.py
@@ -9,7 +9,7 @@
from asktable import Asktable, AsyncAsktable
from tests.utils import assert_matches_type
-from asktable.types import AuthMeResponse
+from asktable.types import AuthMeResponse, AuthCreateTokenResponse
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@@ -20,7 +20,7 @@ class TestAuth:
@parametrize
def test_method_create_token(self, client: Asktable) -> None:
auth = client.auth.create_token()
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
@parametrize
def test_method_create_token_with_all_params(self, client: Asktable) -> None:
@@ -28,12 +28,12 @@ def test_method_create_token_with_all_params(self, client: Asktable) -> None:
ak_role="asker",
chat_role={
"role_id": "1",
- "role_variables": {"id": "42"},
+ "role_variables": {"id": "bar"},
},
token_ttl=900,
- user_profile={"name": "张三"},
+ user_profile={"name": "bar"},
)
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
@parametrize
def test_raw_response_create_token(self, client: Asktable) -> None:
@@ -42,7 +42,7 @@ def test_raw_response_create_token(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
auth = response.parse()
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
@parametrize
def test_streaming_response_create_token(self, client: Asktable) -> None:
@@ -51,7 +51,7 @@ def test_streaming_response_create_token(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
auth = response.parse()
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -89,7 +89,7 @@ class TestAsyncAuth:
@parametrize
async def test_method_create_token(self, async_client: AsyncAsktable) -> None:
auth = await async_client.auth.create_token()
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
@parametrize
async def test_method_create_token_with_all_params(self, async_client: AsyncAsktable) -> None:
@@ -97,12 +97,12 @@ async def test_method_create_token_with_all_params(self, async_client: AsyncAskt
ak_role="asker",
chat_role={
"role_id": "1",
- "role_variables": {"id": "42"},
+ "role_variables": {"id": "bar"},
},
token_ttl=900,
- user_profile={"name": "张三"},
+ user_profile={"name": "bar"},
)
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
@parametrize
async def test_raw_response_create_token(self, async_client: AsyncAsktable) -> None:
@@ -111,7 +111,7 @@ async def test_raw_response_create_token(self, async_client: AsyncAsktable) -> N
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
auth = await response.parse()
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
@parametrize
async def test_streaming_response_create_token(self, async_client: AsyncAsktable) -> None:
@@ -120,7 +120,7 @@ async def test_streaming_response_create_token(self, async_client: AsyncAsktable
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
auth = await response.parse()
- assert_matches_type(object, auth, path=["response"])
+ assert_matches_type(AuthCreateTokenResponse, auth, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/test_bots.py b/tests/api_resources/test_bots.py
index 09b2a320..70627696 100644
--- a/tests/api_resources/test_bots.py
+++ b/tests/api_resources/test_bots.py
@@ -9,7 +9,10 @@
from asktable import Asktable, AsyncAsktable
from tests.utils import assert_matches_type
-from asktable.types import Chatbot
+from asktable.types import (
+ Chatbot,
+ BotInviteResponse,
+)
from asktable.pagination import SyncPage, AsyncPage
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@@ -33,7 +36,6 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
name="name",
color_theme="default",
debug=True,
- extapi_ids=["string"],
interaction_rules=[
{
"enabled": True,
@@ -132,7 +134,6 @@ def test_method_update_with_all_params(self, client: Asktable) -> None:
color_theme="default",
datasource_ids=["ds_sJAbnNOUzu3R4DdCCOwe"],
debug=True,
- extapi_ids=["string"],
interaction_rules=[
{
"enabled": True,
@@ -263,7 +264,7 @@ def test_method_invite(self, client: Asktable) -> None:
bot_id="bot_id",
project_id="project_id",
)
- assert_matches_type(object, bot, path=["response"])
+ assert_matches_type(BotInviteResponse, bot, path=["response"])
@parametrize
def test_raw_response_invite(self, client: Asktable) -> None:
@@ -275,7 +276,7 @@ def test_raw_response_invite(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
bot = response.parse()
- assert_matches_type(object, bot, path=["response"])
+ assert_matches_type(BotInviteResponse, bot, path=["response"])
@parametrize
def test_streaming_response_invite(self, client: Asktable) -> None:
@@ -287,7 +288,7 @@ def test_streaming_response_invite(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
bot = response.parse()
- assert_matches_type(object, bot, path=["response"])
+ assert_matches_type(BotInviteResponse, bot, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -320,7 +321,6 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
name="name",
color_theme="default",
debug=True,
- extapi_ids=["string"],
interaction_rules=[
{
"enabled": True,
@@ -419,7 +419,6 @@ async def test_method_update_with_all_params(self, async_client: AsyncAsktable)
color_theme="default",
datasource_ids=["ds_sJAbnNOUzu3R4DdCCOwe"],
debug=True,
- extapi_ids=["string"],
interaction_rules=[
{
"enabled": True,
@@ -550,7 +549,7 @@ async def test_method_invite(self, async_client: AsyncAsktable) -> None:
bot_id="bot_id",
project_id="project_id",
)
- assert_matches_type(object, bot, path=["response"])
+ assert_matches_type(BotInviteResponse, bot, path=["response"])
@parametrize
async def test_raw_response_invite(self, async_client: AsyncAsktable) -> None:
@@ -562,7 +561,7 @@ async def test_raw_response_invite(self, async_client: AsyncAsktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
bot = await response.parse()
- assert_matches_type(object, bot, path=["response"])
+ assert_matches_type(BotInviteResponse, bot, path=["response"])
@parametrize
async def test_streaming_response_invite(self, async_client: AsyncAsktable) -> None:
@@ -574,7 +573,7 @@ async def test_streaming_response_invite(self, async_client: AsyncAsktable) -> N
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
bot = await response.parse()
- assert_matches_type(object, bot, path=["response"])
+ assert_matches_type(BotInviteResponse, bot, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/test_business_glossary.py b/tests/api_resources/test_business_glossary.py
index 5016bd69..03172958 100644
--- a/tests/api_resources/test_business_glossary.py
+++ b/tests/api_resources/test_business_glossary.py
@@ -120,7 +120,7 @@ def test_method_update_with_all_params(self, client: Asktable) -> None:
active=True,
aliases=["string"],
definition="definition",
- payload={},
+ payload={"foo": "bar"},
term="term",
)
assert_matches_type(Entry, business_glossary, path=["response"])
@@ -332,7 +332,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncAsktable)
active=True,
aliases=["string"],
definition="definition",
- payload={},
+ payload={"foo": "bar"},
term="term",
)
assert_matches_type(Entry, business_glossary, path=["response"])
diff --git a/tests/api_resources/test_caches.py b/tests/api_resources/test_caches.py
deleted file mode 100644
index 637c192e..00000000
--- a/tests/api_resources/test_caches.py
+++ /dev/null
@@ -1,98 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-import os
-from typing import Any, cast
-
-import pytest
-
-from asktable import Asktable, AsyncAsktable
-
-base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
-
-
-class TestCaches:
- parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
-
- @parametrize
- def test_method_delete(self, client: Asktable) -> None:
- cach = client.caches.delete(
- "cache_id",
- )
- assert cach is None
-
- @parametrize
- def test_raw_response_delete(self, client: Asktable) -> None:
- response = client.caches.with_raw_response.delete(
- "cache_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- cach = response.parse()
- assert cach is None
-
- @parametrize
- def test_streaming_response_delete(self, client: Asktable) -> None:
- with client.caches.with_streaming_response.delete(
- "cache_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- cach = response.parse()
- assert cach is None
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- def test_path_params_delete(self, client: Asktable) -> None:
- with pytest.raises(ValueError, match=r"Expected a non-empty value for `cache_id` but received ''"):
- client.caches.with_raw_response.delete(
- "",
- )
-
-
-class TestAsyncCaches:
- parametrize = pytest.mark.parametrize(
- "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
- )
-
- @parametrize
- async def test_method_delete(self, async_client: AsyncAsktable) -> None:
- cach = await async_client.caches.delete(
- "cache_id",
- )
- assert cach is None
-
- @parametrize
- async def test_raw_response_delete(self, async_client: AsyncAsktable) -> None:
- response = await async_client.caches.with_raw_response.delete(
- "cache_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- cach = await response.parse()
- assert cach is None
-
- @parametrize
- async def test_streaming_response_delete(self, async_client: AsyncAsktable) -> None:
- async with async_client.caches.with_streaming_response.delete(
- "cache_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- cach = await response.parse()
- assert cach is None
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- async def test_path_params_delete(self, async_client: AsyncAsktable) -> None:
- with pytest.raises(ValueError, match=r"Expected a non-empty value for `cache_id` but received ''"):
- await async_client.caches.with_raw_response.delete(
- "",
- )
diff --git a/tests/api_resources/test_chats.py b/tests/api_resources/test_chats.py
index 9748cf24..de5d05cb 100644
--- a/tests/api_resources/test_chats.py
+++ b/tests/api_resources/test_chats.py
@@ -9,7 +9,11 @@
from asktable import Asktable, AsyncAsktable
from tests.utils import assert_matches_type
-from asktable.types import Chat, ChatRetrieveResponse
+from asktable.types import (
+ ChatListResponse,
+ ChatCreateResponse,
+ ChatRetrieveResponse,
+)
from asktable.pagination import SyncPage, AsyncPage
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
@@ -21,7 +25,7 @@ class TestChats:
@parametrize
def test_method_create(self, client: Asktable) -> None:
chat = client.chats.create()
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
@parametrize
def test_method_create_with_all_params(self, client: Asktable) -> None:
@@ -36,7 +40,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
"name": "张三",
},
)
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
@parametrize
def test_raw_response_create(self, client: Asktable) -> None:
@@ -45,7 +49,7 @@ def test_raw_response_create(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = response.parse()
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
@parametrize
def test_streaming_response_create(self, client: Asktable) -> None:
@@ -54,7 +58,7 @@ def test_streaming_response_create(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = response.parse()
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -99,7 +103,7 @@ def test_path_params_retrieve(self, client: Asktable) -> None:
@parametrize
def test_method_list(self, client: Asktable) -> None:
chat = client.chats.list()
- assert_matches_type(SyncPage[Chat], chat, path=["response"])
+ assert_matches_type(SyncPage[ChatListResponse], chat, path=["response"])
@parametrize
def test_method_list_with_all_params(self, client: Asktable) -> None:
@@ -107,7 +111,7 @@ def test_method_list_with_all_params(self, client: Asktable) -> None:
page=1,
size=1,
)
- assert_matches_type(SyncPage[Chat], chat, path=["response"])
+ assert_matches_type(SyncPage[ChatListResponse], chat, path=["response"])
@parametrize
def test_raw_response_list(self, client: Asktable) -> None:
@@ -116,7 +120,7 @@ def test_raw_response_list(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = response.parse()
- assert_matches_type(SyncPage[Chat], chat, path=["response"])
+ assert_matches_type(SyncPage[ChatListResponse], chat, path=["response"])
@parametrize
def test_streaming_response_list(self, client: Asktable) -> None:
@@ -125,7 +129,7 @@ def test_streaming_response_list(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = response.parse()
- assert_matches_type(SyncPage[Chat], chat, path=["response"])
+ assert_matches_type(SyncPage[ChatListResponse], chat, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -176,7 +180,7 @@ class TestAsyncChats:
@parametrize
async def test_method_create(self, async_client: AsyncAsktable) -> None:
chat = await async_client.chats.create()
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
@parametrize
async def test_method_create_with_all_params(self, async_client: AsyncAsktable) -> None:
@@ -191,7 +195,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
"name": "张三",
},
)
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
@parametrize
async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
@@ -200,7 +204,7 @@ async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = await response.parse()
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
@parametrize
async def test_streaming_response_create(self, async_client: AsyncAsktable) -> None:
@@ -209,7 +213,7 @@ async def test_streaming_response_create(self, async_client: AsyncAsktable) -> N
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = await response.parse()
- assert_matches_type(Chat, chat, path=["response"])
+ assert_matches_type(ChatCreateResponse, chat, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -254,7 +258,7 @@ async def test_path_params_retrieve(self, async_client: AsyncAsktable) -> None:
@parametrize
async def test_method_list(self, async_client: AsyncAsktable) -> None:
chat = await async_client.chats.list()
- assert_matches_type(AsyncPage[Chat], chat, path=["response"])
+ assert_matches_type(AsyncPage[ChatListResponse], chat, path=["response"])
@parametrize
async def test_method_list_with_all_params(self, async_client: AsyncAsktable) -> None:
@@ -262,7 +266,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncAsktable) ->
page=1,
size=1,
)
- assert_matches_type(AsyncPage[Chat], chat, path=["response"])
+ assert_matches_type(AsyncPage[ChatListResponse], chat, path=["response"])
@parametrize
async def test_raw_response_list(self, async_client: AsyncAsktable) -> None:
@@ -271,7 +275,7 @@ async def test_raw_response_list(self, async_client: AsyncAsktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = await response.parse()
- assert_matches_type(AsyncPage[Chat], chat, path=["response"])
+ assert_matches_type(AsyncPage[ChatListResponse], chat, path=["response"])
@parametrize
async def test_streaming_response_list(self, async_client: AsyncAsktable) -> None:
@@ -280,7 +284,7 @@ async def test_streaming_response_list(self, async_client: AsyncAsktable) -> Non
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
chat = await response.parse()
- assert_matches_type(AsyncPage[Chat], chat, path=["response"])
+ assert_matches_type(AsyncPage[ChatListResponse], chat, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/test_datasources.py b/tests/api_resources/test_datasources.py
index ba4d2ab1..2ab4c033 100644
--- a/tests/api_resources/test_datasources.py
+++ b/tests/api_resources/test_datasources.py
@@ -37,7 +37,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
"host": "192.168.0.10",
"db": "at_test",
"db_version": "5.7",
- "extra_config": {"ssl_mode": "require"},
+ "extra_config": {"ssl_mode": "bar"},
"password": "root",
"port": 3306,
"securetunnel_id": "atst_123456",
@@ -123,7 +123,7 @@ def test_method_update_with_all_params(self, client: Asktable) -> None:
access_config={
"db": "at_test",
"db_version": "5.7",
- "extra_config": {"ssl_mode": "require"},
+ "extra_config": {"ssl_mode": "bar"},
"host": "192.168.0.10",
"password": "root",
"port": 3306,
@@ -133,11 +133,12 @@ def test_method_update_with_all_params(self, client: Asktable) -> None:
desc="数据源描述",
engine="mysql",
field_count=1,
- meta_error="error message",
- meta_status="success",
+ meta_status="available",
name="用户库",
- sample_questions="示例问题",
+ sample_questions=["示例问题1", "示例问题2"],
schema_count=1,
+ sync_error={"message": "bar"},
+ sync_status="success",
table_count=1,
)
assert_matches_type(Datasource, datasource, path=["response"])
@@ -249,7 +250,7 @@ def test_path_params_delete(self, client: Asktable) -> None:
def test_method_add_file(self, client: Asktable) -> None:
datasource = client.datasources.add_file(
datasource_id="datasource_id",
- file=b"raw file contents",
+ file="file",
)
assert_matches_type(object, datasource, path=["response"])
@@ -257,7 +258,7 @@ def test_method_add_file(self, client: Asktable) -> None:
def test_raw_response_add_file(self, client: Asktable) -> None:
response = client.datasources.with_raw_response.add_file(
datasource_id="datasource_id",
- file=b"raw file contents",
+ file="file",
)
assert response.is_closed is True
@@ -269,7 +270,7 @@ def test_raw_response_add_file(self, client: Asktable) -> None:
def test_streaming_response_add_file(self, client: Asktable) -> None:
with client.datasources.with_streaming_response.add_file(
datasource_id="datasource_id",
- file=b"raw file contents",
+ file="file",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -284,7 +285,7 @@ def test_path_params_add_file(self, client: Asktable) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `datasource_id` but received ''"):
client.datasources.with_raw_response.add_file(
datasource_id="",
- file=b"raw file contents",
+ file="file",
)
@parametrize
@@ -456,7 +457,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
"host": "192.168.0.10",
"db": "at_test",
"db_version": "5.7",
- "extra_config": {"ssl_mode": "require"},
+ "extra_config": {"ssl_mode": "bar"},
"password": "root",
"port": 3306,
"securetunnel_id": "atst_123456",
@@ -542,7 +543,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncAsktable)
access_config={
"db": "at_test",
"db_version": "5.7",
- "extra_config": {"ssl_mode": "require"},
+ "extra_config": {"ssl_mode": "bar"},
"host": "192.168.0.10",
"password": "root",
"port": 3306,
@@ -552,11 +553,12 @@ async def test_method_update_with_all_params(self, async_client: AsyncAsktable)
desc="数据源描述",
engine="mysql",
field_count=1,
- meta_error="error message",
- meta_status="success",
+ meta_status="available",
name="用户库",
- sample_questions="示例问题",
+ sample_questions=["示例问题1", "示例问题2"],
schema_count=1,
+ sync_error={"message": "bar"},
+ sync_status="success",
table_count=1,
)
assert_matches_type(Datasource, datasource, path=["response"])
@@ -668,7 +670,7 @@ async def test_path_params_delete(self, async_client: AsyncAsktable) -> None:
async def test_method_add_file(self, async_client: AsyncAsktable) -> None:
datasource = await async_client.datasources.add_file(
datasource_id="datasource_id",
- file=b"raw file contents",
+ file="file",
)
assert_matches_type(object, datasource, path=["response"])
@@ -676,7 +678,7 @@ async def test_method_add_file(self, async_client: AsyncAsktable) -> None:
async def test_raw_response_add_file(self, async_client: AsyncAsktable) -> None:
response = await async_client.datasources.with_raw_response.add_file(
datasource_id="datasource_id",
- file=b"raw file contents",
+ file="file",
)
assert response.is_closed is True
@@ -688,7 +690,7 @@ async def test_raw_response_add_file(self, async_client: AsyncAsktable) -> None:
async def test_streaming_response_add_file(self, async_client: AsyncAsktable) -> None:
async with async_client.datasources.with_streaming_response.add_file(
datasource_id="datasource_id",
- file=b"raw file contents",
+ file="file",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
@@ -703,7 +705,7 @@ async def test_path_params_add_file(self, async_client: AsyncAsktable) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `datasource_id` but received ''"):
await async_client.datasources.with_raw_response.add_file(
datasource_id="",
- file=b"raw file contents",
+ file="file",
)
@parametrize
diff --git a/tests/api_resources/test_roles.py b/tests/api_resources/test_roles.py
index b14375ad..86aa2051 100644
--- a/tests/api_resources/test_roles.py
+++ b/tests/api_resources/test_roles.py
@@ -12,6 +12,7 @@
from asktable.types import (
Role,
RoleGetPolicesResponse,
+ RoleGetVariablesResponse,
)
from asktable.pagination import SyncPage, AsyncPage
@@ -261,7 +262,7 @@ def test_method_get_variables(self, client: Asktable) -> None:
role = client.roles.get_variables(
role_id="role_id",
)
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
@parametrize
def test_method_get_variables_with_all_params(self, client: Asktable) -> None:
@@ -270,7 +271,7 @@ def test_method_get_variables_with_all_params(self, client: Asktable) -> None:
bot_id="bot_id",
datasource_ids=["string", "string"],
)
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
@parametrize
def test_raw_response_get_variables(self, client: Asktable) -> None:
@@ -281,7 +282,7 @@ def test_raw_response_get_variables(self, client: Asktable) -> None:
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
role = response.parse()
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
@parametrize
def test_streaming_response_get_variables(self, client: Asktable) -> None:
@@ -292,7 +293,7 @@ def test_streaming_response_get_variables(self, client: Asktable) -> None:
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
role = response.parse()
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
assert cast(Any, response.is_closed) is True
@@ -549,7 +550,7 @@ async def test_method_get_variables(self, async_client: AsyncAsktable) -> None:
role = await async_client.roles.get_variables(
role_id="role_id",
)
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
@parametrize
async def test_method_get_variables_with_all_params(self, async_client: AsyncAsktable) -> None:
@@ -558,7 +559,7 @@ async def test_method_get_variables_with_all_params(self, async_client: AsyncAsk
bot_id="bot_id",
datasource_ids=["string", "string"],
)
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
@parametrize
async def test_raw_response_get_variables(self, async_client: AsyncAsktable) -> None:
@@ -569,7 +570,7 @@ async def test_raw_response_get_variables(self, async_client: AsyncAsktable) ->
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
role = await response.parse()
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
@parametrize
async def test_streaming_response_get_variables(self, async_client: AsyncAsktable) -> None:
@@ -580,7 +581,7 @@ async def test_streaming_response_get_variables(self, async_client: AsyncAsktabl
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
role = await response.parse()
- assert_matches_type(object, role, path=["response"])
+ assert_matches_type(RoleGetVariablesResponse, role, path=["response"])
assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/test_securetunnels.py b/tests/api_resources/test_securetunnels.py
index 8ab246ed..e2a8b25e 100644
--- a/tests/api_resources/test_securetunnels.py
+++ b/tests/api_resources/test_securetunnels.py
@@ -101,7 +101,7 @@ def test_method_update(self, client: Asktable) -> None:
def test_method_update_with_all_params(self, client: Asktable) -> None:
securetunnel = client.securetunnels.update(
securetunnel_id="securetunnel_id",
- client_info={},
+ client_info={"foo": "bar"},
name="我的测试机",
unique_key="unique_key",
)
@@ -342,7 +342,7 @@ async def test_method_update(self, async_client: AsyncAsktable) -> None:
async def test_method_update_with_all_params(self, async_client: AsyncAsktable) -> None:
securetunnel = await async_client.securetunnels.update(
securetunnel_id="securetunnel_id",
- client_info={},
+ client_info={"foo": "bar"},
name="我的测试机",
unique_key="unique_key",
)
diff --git a/tests/api_resources/test_sqls.py b/tests/api_resources/test_sqls.py
index b1f756dc..c7eaf50c 100644
--- a/tests/api_resources/test_sqls.py
+++ b/tests/api_resources/test_sqls.py
@@ -33,7 +33,7 @@ def test_method_create_with_all_params(self, client: Asktable) -> None:
question="question",
parameterize=True,
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
)
assert_matches_type(QueryResponse, sql, path=["response"])
@@ -118,7 +118,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncAsktable)
question="question",
parameterize=True,
role_id="role_id",
- role_variables={},
+ role_variables={"foo": "bar"},
)
assert_matches_type(QueryResponse, sql, path=["response"])
diff --git a/tests/api_resources/test_sys.py b/tests/api_resources/test_sys.py
deleted file mode 100644
index 67abf960..00000000
--- a/tests/api_resources/test_sys.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-import os
-from typing import Any, cast
-
-import pytest
-
-from asktable import Asktable, AsyncAsktable
-from tests.utils import assert_matches_type
-from asktable.types import SyUpdateConfigResponse
-
-base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
-
-
-class TestSys:
- parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
-
- @parametrize
- def test_method_update_config(self, client: Asktable) -> None:
- sy = client.sys.update_config()
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- @parametrize
- def test_method_update_config_with_all_params(self, client: Asktable) -> None:
- sy = client.sys.update_config(
- global_table_limit=0,
- )
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- @parametrize
- def test_raw_response_update_config(self, client: Asktable) -> None:
- response = client.sys.with_raw_response.update_config()
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- sy = response.parse()
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- @parametrize
- def test_streaming_response_update_config(self, client: Asktable) -> None:
- with client.sys.with_streaming_response.update_config() as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- sy = response.parse()
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
-
-class TestAsyncSys:
- parametrize = pytest.mark.parametrize(
- "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
- )
-
- @parametrize
- async def test_method_update_config(self, async_client: AsyncAsktable) -> None:
- sy = await async_client.sys.update_config()
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- @parametrize
- async def test_method_update_config_with_all_params(self, async_client: AsyncAsktable) -> None:
- sy = await async_client.sys.update_config(
- global_table_limit=0,
- )
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- @parametrize
- async def test_raw_response_update_config(self, async_client: AsyncAsktable) -> None:
- response = await async_client.sys.with_raw_response.update_config()
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- sy = await response.parse()
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- @parametrize
- async def test_streaming_response_update_config(self, async_client: AsyncAsktable) -> None:
- async with async_client.sys.with_streaming_response.update_config() as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- sy = await response.parse()
- assert_matches_type(SyUpdateConfigResponse, sy, path=["response"])
-
- assert cast(Any, response.is_closed) is True
diff --git a/tests/api_resources/test_trainings.py b/tests/api_resources/test_trainings.py
deleted file mode 100644
index 33452ed1..00000000
--- a/tests/api_resources/test_trainings.py
+++ /dev/null
@@ -1,399 +0,0 @@
-# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
-
-from __future__ import annotations
-
-import os
-from typing import Any, cast
-
-import pytest
-
-from asktable import Asktable, AsyncAsktable
-from tests.utils import assert_matches_type
-from asktable.types import (
- TrainingListResponse,
- TrainingCreateResponse,
- TrainingUpdateResponse,
-)
-from asktable.pagination import SyncPage, AsyncPage
-
-base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
-
-
-class TestTrainings:
- parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
-
- @parametrize
- def test_method_create(self, client: Asktable) -> None:
- training = client.trainings.create(
- datasource_id="datasource_id",
- body=[
- {
- "question": "question",
- "sql": "sql",
- }
- ],
- )
- assert_matches_type(TrainingCreateResponse, training, path=["response"])
-
- @parametrize
- def test_raw_response_create(self, client: Asktable) -> None:
- response = client.trainings.with_raw_response.create(
- datasource_id="datasource_id",
- body=[
- {
- "question": "question",
- "sql": "sql",
- }
- ],
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = response.parse()
- assert_matches_type(TrainingCreateResponse, training, path=["response"])
-
- @parametrize
- def test_streaming_response_create(self, client: Asktable) -> None:
- with client.trainings.with_streaming_response.create(
- datasource_id="datasource_id",
- body=[
- {
- "question": "question",
- "sql": "sql",
- }
- ],
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = response.parse()
- assert_matches_type(TrainingCreateResponse, training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- def test_method_update(self, client: Asktable) -> None:
- training = client.trainings.update(
- id="id",
- datasource_id="datasource_id",
- )
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- @parametrize
- def test_method_update_with_all_params(self, client: Asktable) -> None:
- training = client.trainings.update(
- id="id",
- datasource_id="datasource_id",
- active=True,
- question="question",
- role_id="role_id",
- sql="sql",
- )
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- @parametrize
- def test_raw_response_update(self, client: Asktable) -> None:
- response = client.trainings.with_raw_response.update(
- id="id",
- datasource_id="datasource_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = response.parse()
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- @parametrize
- def test_streaming_response_update(self, client: Asktable) -> None:
- with client.trainings.with_streaming_response.update(
- id="id",
- datasource_id="datasource_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = response.parse()
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- def test_path_params_update(self, client: Asktable) -> None:
- with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"):
- client.trainings.with_raw_response.update(
- id="",
- datasource_id="datasource_id",
- )
-
- @parametrize
- def test_method_list(self, client: Asktable) -> None:
- training = client.trainings.list(
- datasource_id="datasource_id",
- )
- assert_matches_type(SyncPage[TrainingListResponse], training, path=["response"])
-
- @parametrize
- def test_method_list_with_all_params(self, client: Asktable) -> None:
- training = client.trainings.list(
- datasource_id="datasource_id",
- page=1,
- size=1,
- )
- assert_matches_type(SyncPage[TrainingListResponse], training, path=["response"])
-
- @parametrize
- def test_raw_response_list(self, client: Asktable) -> None:
- response = client.trainings.with_raw_response.list(
- datasource_id="datasource_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = response.parse()
- assert_matches_type(SyncPage[TrainingListResponse], training, path=["response"])
-
- @parametrize
- def test_streaming_response_list(self, client: Asktable) -> None:
- with client.trainings.with_streaming_response.list(
- datasource_id="datasource_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = response.parse()
- assert_matches_type(SyncPage[TrainingListResponse], training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- def test_method_delete(self, client: Asktable) -> None:
- training = client.trainings.delete(
- id="id",
- datasource_id="datasource_id",
- )
- assert_matches_type(object, training, path=["response"])
-
- @parametrize
- def test_raw_response_delete(self, client: Asktable) -> None:
- response = client.trainings.with_raw_response.delete(
- id="id",
- datasource_id="datasource_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = response.parse()
- assert_matches_type(object, training, path=["response"])
-
- @parametrize
- def test_streaming_response_delete(self, client: Asktable) -> None:
- with client.trainings.with_streaming_response.delete(
- id="id",
- datasource_id="datasource_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = response.parse()
- assert_matches_type(object, training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- def test_path_params_delete(self, client: Asktable) -> None:
- with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"):
- client.trainings.with_raw_response.delete(
- id="",
- datasource_id="datasource_id",
- )
-
-
-class TestAsyncTrainings:
- parametrize = pytest.mark.parametrize(
- "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
- )
-
- @parametrize
- async def test_method_create(self, async_client: AsyncAsktable) -> None:
- training = await async_client.trainings.create(
- datasource_id="datasource_id",
- body=[
- {
- "question": "question",
- "sql": "sql",
- }
- ],
- )
- assert_matches_type(TrainingCreateResponse, training, path=["response"])
-
- @parametrize
- async def test_raw_response_create(self, async_client: AsyncAsktable) -> None:
- response = await async_client.trainings.with_raw_response.create(
- datasource_id="datasource_id",
- body=[
- {
- "question": "question",
- "sql": "sql",
- }
- ],
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = await response.parse()
- assert_matches_type(TrainingCreateResponse, training, path=["response"])
-
- @parametrize
- async def test_streaming_response_create(self, async_client: AsyncAsktable) -> None:
- async with async_client.trainings.with_streaming_response.create(
- datasource_id="datasource_id",
- body=[
- {
- "question": "question",
- "sql": "sql",
- }
- ],
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = await response.parse()
- assert_matches_type(TrainingCreateResponse, training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- async def test_method_update(self, async_client: AsyncAsktable) -> None:
- training = await async_client.trainings.update(
- id="id",
- datasource_id="datasource_id",
- )
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- @parametrize
- async def test_method_update_with_all_params(self, async_client: AsyncAsktable) -> None:
- training = await async_client.trainings.update(
- id="id",
- datasource_id="datasource_id",
- active=True,
- question="question",
- role_id="role_id",
- sql="sql",
- )
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- @parametrize
- async def test_raw_response_update(self, async_client: AsyncAsktable) -> None:
- response = await async_client.trainings.with_raw_response.update(
- id="id",
- datasource_id="datasource_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = await response.parse()
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- @parametrize
- async def test_streaming_response_update(self, async_client: AsyncAsktable) -> None:
- async with async_client.trainings.with_streaming_response.update(
- id="id",
- datasource_id="datasource_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = await response.parse()
- assert_matches_type(TrainingUpdateResponse, training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- async def test_path_params_update(self, async_client: AsyncAsktable) -> None:
- with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"):
- await async_client.trainings.with_raw_response.update(
- id="",
- datasource_id="datasource_id",
- )
-
- @parametrize
- async def test_method_list(self, async_client: AsyncAsktable) -> None:
- training = await async_client.trainings.list(
- datasource_id="datasource_id",
- )
- assert_matches_type(AsyncPage[TrainingListResponse], training, path=["response"])
-
- @parametrize
- async def test_method_list_with_all_params(self, async_client: AsyncAsktable) -> None:
- training = await async_client.trainings.list(
- datasource_id="datasource_id",
- page=1,
- size=1,
- )
- assert_matches_type(AsyncPage[TrainingListResponse], training, path=["response"])
-
- @parametrize
- async def test_raw_response_list(self, async_client: AsyncAsktable) -> None:
- response = await async_client.trainings.with_raw_response.list(
- datasource_id="datasource_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = await response.parse()
- assert_matches_type(AsyncPage[TrainingListResponse], training, path=["response"])
-
- @parametrize
- async def test_streaming_response_list(self, async_client: AsyncAsktable) -> None:
- async with async_client.trainings.with_streaming_response.list(
- datasource_id="datasource_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = await response.parse()
- assert_matches_type(AsyncPage[TrainingListResponse], training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- async def test_method_delete(self, async_client: AsyncAsktable) -> None:
- training = await async_client.trainings.delete(
- id="id",
- datasource_id="datasource_id",
- )
- assert_matches_type(object, training, path=["response"])
-
- @parametrize
- async def test_raw_response_delete(self, async_client: AsyncAsktable) -> None:
- response = await async_client.trainings.with_raw_response.delete(
- id="id",
- datasource_id="datasource_id",
- )
-
- assert response.is_closed is True
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
- training = await response.parse()
- assert_matches_type(object, training, path=["response"])
-
- @parametrize
- async def test_streaming_response_delete(self, async_client: AsyncAsktable) -> None:
- async with async_client.trainings.with_streaming_response.delete(
- id="id",
- datasource_id="datasource_id",
- ) as response:
- assert not response.is_closed
- assert response.http_request.headers.get("X-Stainless-Lang") == "python"
-
- training = await response.parse()
- assert_matches_type(object, training, path=["response"])
-
- assert cast(Any, response.is_closed) is True
-
- @parametrize
- async def test_path_params_delete(self, async_client: AsyncAsktable) -> None:
- with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"):
- await async_client.trainings.with_raw_response.delete(
- id="",
- datasource_id="datasource_id",
- )
diff --git a/tests/test_client.py b/tests/test_client.py
index 76c130aa..75c3f242 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -6,15 +6,13 @@
import os
import sys
import json
-import time
import asyncio
import inspect
-import subprocess
+import dataclasses
import tracemalloc
-from typing import Any, Union, cast
-from textwrap import dedent
+from typing import Any, Union, TypeVar, Callable, Iterable, Iterator, Optional, Coroutine, cast
from unittest import mock
-from typing_extensions import Literal
+from typing_extensions import Literal, AsyncIterator, override
import httpx
import pytest
@@ -23,19 +21,23 @@
from asktable import Asktable, AsyncAsktable, APIResponseValidationError
from asktable._types import Omit
+from asktable._utils import asyncify
from asktable._models import BaseModel, FinalRequestOptions
from asktable._exceptions import APIStatusError, APITimeoutError, APIResponseValidationError
from asktable._base_client import (
DEFAULT_TIMEOUT,
HTTPX_DEFAULT_TIMEOUT,
BaseClient,
+ OtherPlatform,
DefaultHttpxClient,
DefaultAsyncHttpxClient,
+ get_platform,
make_request_options,
)
from .utils import update_env
+T = TypeVar("T")
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
api_key = "My API Key"
@@ -50,6 +52,57 @@ def _low_retry_timeout(*_args: Any, **_kwargs: Any) -> float:
return 0.1
+def mirror_request_content(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, content=request.content)
+
+
+# note: we can't use the httpx.MockTransport class as it consumes the request
+# body itself, which means we can't test that the body is read lazily
+class MockTransport(httpx.BaseTransport, httpx.AsyncBaseTransport):
+ def __init__(
+ self,
+ handler: Callable[[httpx.Request], httpx.Response]
+ | Callable[[httpx.Request], Coroutine[Any, Any, httpx.Response]],
+ ) -> None:
+ self.handler = handler
+
+ @override
+ def handle_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ assert not inspect.iscoroutinefunction(self.handler), "handler must not be a coroutine function"
+ assert inspect.isfunction(self.handler), "handler must be a function"
+ return self.handler(request)
+
+ @override
+ async def handle_async_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ assert inspect.iscoroutinefunction(self.handler), "handler must be a coroutine function"
+ return await self.handler(request)
+
+
+@dataclasses.dataclass
+class Counter:
+ value: int = 0
+
+
+def _make_sync_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> Iterator[T]:
+ for item in iterable:
+ if counter:
+ counter.value += 1
+ yield item
+
+
+async def _make_async_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> AsyncIterator[T]:
+ for item in iterable:
+ if counter:
+ counter.value += 1
+ yield item
+
+
def _get_open_connections(client: Asktable | AsyncAsktable) -> int:
transport = client._client._transport
assert isinstance(transport, httpx.HTTPTransport) or isinstance(transport, httpx.AsyncHTTPTransport)
@@ -59,51 +112,49 @@ def _get_open_connections(client: Asktable | AsyncAsktable) -> int:
class TestAsktable:
- client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
-
@pytest.mark.respx(base_url=base_url)
- def test_raw_response(self, respx_mock: MockRouter) -> None:
+ def test_raw_response(self, respx_mock: MockRouter, client: Asktable) -> None:
respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))
- response = self.client.post("/foo", cast_to=httpx.Response)
+ response = client.post("/foo", cast_to=httpx.Response)
assert response.status_code == 200
assert isinstance(response, httpx.Response)
assert response.json() == {"foo": "bar"}
@pytest.mark.respx(base_url=base_url)
- def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None:
+ def test_raw_response_for_binary(self, respx_mock: MockRouter, client: Asktable) -> None:
respx_mock.post("/foo").mock(
return_value=httpx.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}')
)
- response = self.client.post("/foo", cast_to=httpx.Response)
+ response = client.post("/foo", cast_to=httpx.Response)
assert response.status_code == 200
assert isinstance(response, httpx.Response)
assert response.json() == {"foo": "bar"}
- def test_copy(self) -> None:
- copied = self.client.copy()
- assert id(copied) != id(self.client)
+ def test_copy(self, client: Asktable) -> None:
+ copied = client.copy()
+ assert id(copied) != id(client)
- copied = self.client.copy(api_key="another My API Key")
+ copied = client.copy(api_key="another My API Key")
assert copied.api_key == "another My API Key"
- assert self.client.api_key == "My API Key"
+ assert client.api_key == "My API Key"
- def test_copy_default_options(self) -> None:
+ def test_copy_default_options(self, client: Asktable) -> None:
# options that have a default are overridden correctly
- copied = self.client.copy(max_retries=7)
+ copied = client.copy(max_retries=7)
assert copied.max_retries == 7
- assert self.client.max_retries == 2
+ assert client.max_retries == 2
copied2 = copied.copy(max_retries=6)
assert copied2.max_retries == 6
assert copied.max_retries == 7
# timeout
- assert isinstance(self.client.timeout, httpx.Timeout)
- copied = self.client.copy(timeout=None)
+ assert isinstance(client.timeout, httpx.Timeout)
+ copied = client.copy(timeout=None)
assert copied.timeout is None
- assert isinstance(self.client.timeout, httpx.Timeout)
+ assert isinstance(client.timeout, httpx.Timeout)
def test_copy_default_headers(self) -> None:
client = Asktable(
@@ -138,6 +189,7 @@ def test_copy_default_headers(self) -> None:
match="`default_headers` and `set_default_headers` arguments are mutually exclusive",
):
client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"})
+ client.close()
def test_copy_default_query(self) -> None:
client = Asktable(
@@ -175,13 +227,15 @@ def test_copy_default_query(self) -> None:
):
client.copy(set_default_query={}, default_query={"foo": "Bar"})
- def test_copy_signature(self) -> None:
+ client.close()
+
+ def test_copy_signature(self, client: Asktable) -> None:
# ensure the same parameters that can be passed to the client are defined in the `.copy()` method
init_signature = inspect.signature(
# mypy doesn't like that we access the `__init__` property.
- self.client.__init__, # type: ignore[misc]
+ client.__init__, # type: ignore[misc]
)
- copy_signature = inspect.signature(self.client.copy)
+ copy_signature = inspect.signature(client.copy)
exclude_params = {"transport", "proxies", "_strict_response_validation"}
for name in init_signature.parameters.keys():
@@ -192,12 +246,12 @@ def test_copy_signature(self) -> None:
assert copy_param is not None, f"copy() signature is missing the {name} param"
@pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12")
- def test_copy_build_request(self) -> None:
+ def test_copy_build_request(self, client: Asktable) -> None:
options = FinalRequestOptions(method="get", url="/foo")
def build_request(options: FinalRequestOptions) -> None:
- client = self.client.copy()
- client._build_request(options)
+ client_copy = client.copy()
+ client_copy._build_request(options)
# ensure that the machinery is warmed up before tracing starts.
build_request(options)
@@ -254,14 +308,12 @@ def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.Statistic
print(frame)
raise AssertionError()
- def test_request_timeout(self) -> None:
- request = self.client._build_request(FinalRequestOptions(method="get", url="/foo"))
+ def test_request_timeout(self, client: Asktable) -> None:
+ request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == DEFAULT_TIMEOUT
- request = self.client._build_request(
- FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0))
- )
+ request = client._build_request(FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0)))
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == httpx.Timeout(100.0)
@@ -274,6 +326,8 @@ def test_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == httpx.Timeout(0)
+ client.close()
+
def test_http_client_timeout_option(self) -> None:
# custom timeout given to the httpx client should be used
with httpx.Client(timeout=None) as http_client:
@@ -285,6 +339,8 @@ def test_http_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == httpx.Timeout(None)
+ client.close()
+
# no timeout given to the httpx client should not use the httpx default
with httpx.Client() as http_client:
client = Asktable(
@@ -295,6 +351,8 @@ def test_http_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == DEFAULT_TIMEOUT
+ client.close()
+
# explicitly passing the default timeout currently results in it being ignored
with httpx.Client(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client:
client = Asktable(
@@ -305,6 +363,8 @@ def test_http_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == DEFAULT_TIMEOUT # our default
+ client.close()
+
async def test_invalid_http_client(self) -> None:
with pytest.raises(TypeError, match="Invalid `http_client` arg"):
async with httpx.AsyncClient() as http_client:
@@ -316,14 +376,14 @@ async def test_invalid_http_client(self) -> None:
)
def test_default_headers_option(self) -> None:
- client = Asktable(
+ test_client = Asktable(
base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
)
- request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
+ request = test_client._build_request(FinalRequestOptions(method="get", url="/foo"))
assert request.headers.get("x-foo") == "bar"
assert request.headers.get("x-stainless-lang") == "python"
- client2 = Asktable(
+ test_client2 = Asktable(
base_url=base_url,
api_key=api_key,
_strict_response_validation=True,
@@ -332,10 +392,13 @@ def test_default_headers_option(self) -> None:
"X-Stainless-Lang": "my-overriding-header",
},
)
- request = client2._build_request(FinalRequestOptions(method="get", url="/foo"))
+ request = test_client2._build_request(FinalRequestOptions(method="get", url="/foo"))
assert request.headers.get("x-foo") == "stainless"
assert request.headers.get("x-stainless-lang") == "my-overriding-header"
+ test_client.close()
+ test_client2.close()
+
def test_default_query_option(self) -> None:
client = Asktable(
base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"}
@@ -354,8 +417,10 @@ def test_default_query_option(self) -> None:
url = httpx.URL(request.url)
assert dict(url.params) == {"foo": "baz", "query_param": "overridden"}
- def test_request_extra_json(self) -> None:
- request = self.client._build_request(
+ client.close()
+
+ def test_request_extra_json(self, client: Asktable) -> None:
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -366,7 +431,7 @@ def test_request_extra_json(self) -> None:
data = json.loads(request.content.decode("utf-8"))
assert data == {"foo": "bar", "baz": False}
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -377,7 +442,7 @@ def test_request_extra_json(self) -> None:
assert data == {"baz": False}
# `extra_json` takes priority over `json_data` when keys clash
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -388,8 +453,8 @@ def test_request_extra_json(self) -> None:
data = json.loads(request.content.decode("utf-8"))
assert data == {"foo": "bar", "baz": None}
- def test_request_extra_headers(self) -> None:
- request = self.client._build_request(
+ def test_request_extra_headers(self, client: Asktable) -> None:
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -399,7 +464,7 @@ def test_request_extra_headers(self) -> None:
assert request.headers.get("X-Foo") == "Foo"
# `extra_headers` takes priority over `default_headers` when keys clash
- request = self.client.with_options(default_headers={"X-Bar": "true"})._build_request(
+ request = client.with_options(default_headers={"X-Bar": "true"})._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -410,8 +475,8 @@ def test_request_extra_headers(self) -> None:
)
assert request.headers.get("X-Bar") == "false"
- def test_request_extra_query(self) -> None:
- request = self.client._build_request(
+ def test_request_extra_query(self, client: Asktable) -> None:
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -424,7 +489,7 @@ def test_request_extra_query(self) -> None:
assert params == {"my_query_param": "Foo"}
# if both `query` and `extra_query` are given, they are merged
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -438,7 +503,7 @@ def test_request_extra_query(self) -> None:
assert params == {"bar": "1", "foo": "2"}
# `extra_query` takes priority over `query` when keys clash
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -481,7 +546,71 @@ def test_multipart_repeating_array(self, client: Asktable) -> None:
]
@pytest.mark.respx(base_url=base_url)
- def test_basic_union_response(self, respx_mock: MockRouter) -> None:
+ def test_binary_content_upload(self, respx_mock: MockRouter, client: Asktable) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ response = client.post(
+ "/upload",
+ content=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
+ def test_binary_content_upload_with_iterator(self) -> None:
+ file_content = b"Hello, this is a test file."
+ counter = Counter()
+ iterator = _make_sync_iterator([file_content], counter=counter)
+
+ def mock_handler(request: httpx.Request) -> httpx.Response:
+ assert counter.value == 0, "the request body should not have been read"
+ return httpx.Response(200, content=request.read())
+
+ with Asktable(
+ base_url=base_url,
+ api_key=api_key,
+ _strict_response_validation=True,
+ http_client=httpx.Client(transport=MockTransport(handler=mock_handler)),
+ ) as client:
+ response = client.post(
+ "/upload",
+ content=iterator,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+ assert counter.value == 1
+
+ @pytest.mark.respx(base_url=base_url)
+ def test_binary_content_upload_with_body_is_deprecated(self, respx_mock: MockRouter, client: Asktable) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ with pytest.deprecated_call(
+ match="Passing raw bytes as `body` is deprecated and will be removed in a future version. Please pass raw bytes via the `content` parameter instead."
+ ):
+ response = client.post(
+ "/upload",
+ body=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
+ @pytest.mark.respx(base_url=base_url)
+ def test_basic_union_response(self, respx_mock: MockRouter, client: Asktable) -> None:
class Model1(BaseModel):
name: str
@@ -490,12 +619,12 @@ class Model2(BaseModel):
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))
- response = self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
+ response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
assert isinstance(response, Model2)
assert response.foo == "bar"
@pytest.mark.respx(base_url=base_url)
- def test_union_response_different_types(self, respx_mock: MockRouter) -> None:
+ def test_union_response_different_types(self, respx_mock: MockRouter, client: Asktable) -> None:
"""Union of objects with the same field name using a different type"""
class Model1(BaseModel):
@@ -506,18 +635,18 @@ class Model2(BaseModel):
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))
- response = self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
+ response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
assert isinstance(response, Model2)
assert response.foo == "bar"
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": 1}))
- response = self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
+ response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
assert isinstance(response, Model1)
assert response.foo == 1
@pytest.mark.respx(base_url=base_url)
- def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter) -> None:
+ def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter, client: Asktable) -> None:
"""
Response that sets Content-Type to something other than application/json but returns json data
"""
@@ -533,7 +662,7 @@ class Model(BaseModel):
)
)
- response = self.client.get("/foo", cast_to=Model)
+ response = client.get("/foo", cast_to=Model)
assert isinstance(response, Model)
assert response.foo == 2
@@ -545,6 +674,8 @@ def test_base_url_setter(self) -> None:
assert client.base_url == "https://example.com/from_setter/"
+ client.close()
+
def test_base_url_env(self) -> None:
with update_env(ASKTABLE_BASE_URL="http://localhost:5000/from/env"):
client = Asktable(api_key=api_key, _strict_response_validation=True)
@@ -572,6 +703,7 @@ def test_base_url_trailing_slash(self, client: Asktable) -> None:
),
)
assert request.url == "http://localhost:5000/custom/path/foo"
+ client.close()
@pytest.mark.parametrize(
"client",
@@ -595,6 +727,7 @@ def test_base_url_no_trailing_slash(self, client: Asktable) -> None:
),
)
assert request.url == "http://localhost:5000/custom/path/foo"
+ client.close()
@pytest.mark.parametrize(
"client",
@@ -618,35 +751,36 @@ def test_absolute_request_url(self, client: Asktable) -> None:
),
)
assert request.url == "https://myapi.com/foo"
+ client.close()
def test_copied_client_does_not_close_http(self) -> None:
- client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
- assert not client.is_closed()
+ test_client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
+ assert not test_client.is_closed()
- copied = client.copy()
- assert copied is not client
+ copied = test_client.copy()
+ assert copied is not test_client
del copied
- assert not client.is_closed()
+ assert not test_client.is_closed()
def test_client_context_manager(self) -> None:
- client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
- with client as c2:
- assert c2 is client
+ test_client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
+ with test_client as c2:
+ assert c2 is test_client
assert not c2.is_closed()
- assert not client.is_closed()
- assert client.is_closed()
+ assert not test_client.is_closed()
+ assert test_client.is_closed()
@pytest.mark.respx(base_url=base_url)
- def test_client_response_validation_error(self, respx_mock: MockRouter) -> None:
+ def test_client_response_validation_error(self, respx_mock: MockRouter, client: Asktable) -> None:
class Model(BaseModel):
foo: str
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": {"invalid": True}}))
with pytest.raises(APIResponseValidationError) as exc:
- self.client.get("/foo", cast_to=Model)
+ client.get("/foo", cast_to=Model)
assert isinstance(exc.value.__cause__, ValidationError)
@@ -666,11 +800,14 @@ class Model(BaseModel):
with pytest.raises(APIResponseValidationError):
strict_client.get("/foo", cast_to=Model)
- client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=False)
+ non_strict_client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=False)
- response = client.get("/foo", cast_to=Model)
+ response = non_strict_client.get("/foo", cast_to=Model)
assert isinstance(response, str) # type: ignore[unreachable]
+ strict_client.close()
+ non_strict_client.close()
+
@pytest.mark.parametrize(
"remaining_retries,retry_after,timeout",
[
@@ -693,9 +830,9 @@ class Model(BaseModel):
],
)
@mock.patch("time.time", mock.MagicMock(return_value=1696004797))
- def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str, timeout: float) -> None:
- client = Asktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
-
+ def test_parse_retry_after_header(
+ self, remaining_retries: int, retry_after: str, timeout: float, client: Asktable
+ ) -> None:
headers = httpx.Headers({"retry-after": retry_after})
options = FinalRequestOptions(method="get", url="/foo", max_retries=3)
calculated = client._calculate_retry_timeout(remaining_retries, options, headers)
@@ -709,7 +846,7 @@ def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter, clien
with pytest.raises(APITimeoutError):
client.datasources.with_streaming_response.create(engine="mysql").__enter__()
- assert _get_open_connections(self.client) == 0
+ assert _get_open_connections(client) == 0
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@pytest.mark.respx(base_url=base_url)
@@ -718,7 +855,7 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter, client
with pytest.raises(APIStatusError):
client.datasources.with_streaming_response.create(engine="mysql").__enter__()
- assert _get_open_connections(self.client) == 0
+ assert _get_open_connections(client) == 0
@pytest.mark.parametrize("failures_before_success", [0, 2, 4])
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@@ -804,6 +941,14 @@ def retry_handler(_request: httpx.Request) -> httpx.Response:
def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None:
# Test that the proxy environment variables are set correctly
monkeypatch.setenv("HTTPS_PROXY", "https://example.org")
+ # Delete in case our environment has any proxy env vars set
+ monkeypatch.delenv("HTTP_PROXY", raising=False)
+ monkeypatch.delenv("ALL_PROXY", raising=False)
+ monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("http_proxy", raising=False)
+ monkeypatch.delenv("https_proxy", raising=False)
+ monkeypatch.delenv("all_proxy", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
client = DefaultHttpxClient()
@@ -824,83 +969,77 @@ def test_default_client_creation(self) -> None:
)
@pytest.mark.respx(base_url=base_url)
- def test_follow_redirects(self, respx_mock: MockRouter) -> None:
+ def test_follow_redirects(self, respx_mock: MockRouter, client: Asktable) -> None:
# Test that the default follow_redirects=True allows following redirects
respx_mock.post("/redirect").mock(
return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"})
)
respx_mock.get("/redirected").mock(return_value=httpx.Response(200, json={"status": "ok"}))
- response = self.client.post("/redirect", body={"key": "value"}, cast_to=httpx.Response)
+ response = client.post("/redirect", body={"key": "value"}, cast_to=httpx.Response)
assert response.status_code == 200
assert response.json() == {"status": "ok"}
@pytest.mark.respx(base_url=base_url)
- def test_follow_redirects_disabled(self, respx_mock: MockRouter) -> None:
+ def test_follow_redirects_disabled(self, respx_mock: MockRouter, client: Asktable) -> None:
# Test that follow_redirects=False prevents following redirects
respx_mock.post("/redirect").mock(
return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"})
)
with pytest.raises(APIStatusError) as exc_info:
- self.client.post(
- "/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx.Response
- )
+ client.post("/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx.Response)
assert exc_info.value.response.status_code == 302
assert exc_info.value.response.headers["Location"] == f"{base_url}/redirected"
class TestAsyncAsktable:
- client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
-
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
- async def test_raw_response(self, respx_mock: MockRouter) -> None:
+ async def test_raw_response(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))
- response = await self.client.post("/foo", cast_to=httpx.Response)
+ response = await async_client.post("/foo", cast_to=httpx.Response)
assert response.status_code == 200
assert isinstance(response, httpx.Response)
assert response.json() == {"foo": "bar"}
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
- async def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None:
+ async def test_raw_response_for_binary(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
respx_mock.post("/foo").mock(
return_value=httpx.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}')
)
- response = await self.client.post("/foo", cast_to=httpx.Response)
+ response = await async_client.post("/foo", cast_to=httpx.Response)
assert response.status_code == 200
assert isinstance(response, httpx.Response)
assert response.json() == {"foo": "bar"}
- def test_copy(self) -> None:
- copied = self.client.copy()
- assert id(copied) != id(self.client)
+ def test_copy(self, async_client: AsyncAsktable) -> None:
+ copied = async_client.copy()
+ assert id(copied) != id(async_client)
- copied = self.client.copy(api_key="another My API Key")
+ copied = async_client.copy(api_key="another My API Key")
assert copied.api_key == "another My API Key"
- assert self.client.api_key == "My API Key"
+ assert async_client.api_key == "My API Key"
- def test_copy_default_options(self) -> None:
+ def test_copy_default_options(self, async_client: AsyncAsktable) -> None:
# options that have a default are overridden correctly
- copied = self.client.copy(max_retries=7)
+ copied = async_client.copy(max_retries=7)
assert copied.max_retries == 7
- assert self.client.max_retries == 2
+ assert async_client.max_retries == 2
copied2 = copied.copy(max_retries=6)
assert copied2.max_retries == 6
assert copied.max_retries == 7
# timeout
- assert isinstance(self.client.timeout, httpx.Timeout)
- copied = self.client.copy(timeout=None)
+ assert isinstance(async_client.timeout, httpx.Timeout)
+ copied = async_client.copy(timeout=None)
assert copied.timeout is None
- assert isinstance(self.client.timeout, httpx.Timeout)
+ assert isinstance(async_client.timeout, httpx.Timeout)
- def test_copy_default_headers(self) -> None:
+ async def test_copy_default_headers(self) -> None:
client = AsyncAsktable(
base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
)
@@ -933,8 +1072,9 @@ def test_copy_default_headers(self) -> None:
match="`default_headers` and `set_default_headers` arguments are mutually exclusive",
):
client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"})
+ await client.close()
- def test_copy_default_query(self) -> None:
+ async def test_copy_default_query(self) -> None:
client = AsyncAsktable(
base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"}
)
@@ -970,13 +1110,15 @@ def test_copy_default_query(self) -> None:
):
client.copy(set_default_query={}, default_query={"foo": "Bar"})
- def test_copy_signature(self) -> None:
+ await client.close()
+
+ def test_copy_signature(self, async_client: AsyncAsktable) -> None:
# ensure the same parameters that can be passed to the client are defined in the `.copy()` method
init_signature = inspect.signature(
# mypy doesn't like that we access the `__init__` property.
- self.client.__init__, # type: ignore[misc]
+ async_client.__init__, # type: ignore[misc]
)
- copy_signature = inspect.signature(self.client.copy)
+ copy_signature = inspect.signature(async_client.copy)
exclude_params = {"transport", "proxies", "_strict_response_validation"}
for name in init_signature.parameters.keys():
@@ -987,12 +1129,12 @@ def test_copy_signature(self) -> None:
assert copy_param is not None, f"copy() signature is missing the {name} param"
@pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12")
- def test_copy_build_request(self) -> None:
+ def test_copy_build_request(self, async_client: AsyncAsktable) -> None:
options = FinalRequestOptions(method="get", url="/foo")
def build_request(options: FinalRequestOptions) -> None:
- client = self.client.copy()
- client._build_request(options)
+ client_copy = async_client.copy()
+ client_copy._build_request(options)
# ensure that the machinery is warmed up before tracing starts.
build_request(options)
@@ -1049,12 +1191,12 @@ def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.Statistic
print(frame)
raise AssertionError()
- async def test_request_timeout(self) -> None:
- request = self.client._build_request(FinalRequestOptions(method="get", url="/foo"))
+ async def test_request_timeout(self, async_client: AsyncAsktable) -> None:
+ request = async_client._build_request(FinalRequestOptions(method="get", url="/foo"))
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == DEFAULT_TIMEOUT
- request = self.client._build_request(
+ request = async_client._build_request(
FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0))
)
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
@@ -1069,6 +1211,8 @@ async def test_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == httpx.Timeout(0)
+ await client.close()
+
async def test_http_client_timeout_option(self) -> None:
# custom timeout given to the httpx client should be used
async with httpx.AsyncClient(timeout=None) as http_client:
@@ -1080,6 +1224,8 @@ async def test_http_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == httpx.Timeout(None)
+ await client.close()
+
# no timeout given to the httpx client should not use the httpx default
async with httpx.AsyncClient() as http_client:
client = AsyncAsktable(
@@ -1090,6 +1236,8 @@ async def test_http_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == DEFAULT_TIMEOUT
+ await client.close()
+
# explicitly passing the default timeout currently results in it being ignored
async with httpx.AsyncClient(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client:
client = AsyncAsktable(
@@ -1100,6 +1248,8 @@ async def test_http_client_timeout_option(self) -> None:
timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore
assert timeout == DEFAULT_TIMEOUT # our default
+ await client.close()
+
def test_invalid_http_client(self) -> None:
with pytest.raises(TypeError, match="Invalid `http_client` arg"):
with httpx.Client() as http_client:
@@ -1110,15 +1260,15 @@ def test_invalid_http_client(self) -> None:
http_client=cast(Any, http_client),
)
- def test_default_headers_option(self) -> None:
- client = AsyncAsktable(
+ async def test_default_headers_option(self) -> None:
+ test_client = AsyncAsktable(
base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
)
- request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
+ request = test_client._build_request(FinalRequestOptions(method="get", url="/foo"))
assert request.headers.get("x-foo") == "bar"
assert request.headers.get("x-stainless-lang") == "python"
- client2 = AsyncAsktable(
+ test_client2 = AsyncAsktable(
base_url=base_url,
api_key=api_key,
_strict_response_validation=True,
@@ -1127,11 +1277,14 @@ def test_default_headers_option(self) -> None:
"X-Stainless-Lang": "my-overriding-header",
},
)
- request = client2._build_request(FinalRequestOptions(method="get", url="/foo"))
+ request = test_client2._build_request(FinalRequestOptions(method="get", url="/foo"))
assert request.headers.get("x-foo") == "stainless"
assert request.headers.get("x-stainless-lang") == "my-overriding-header"
- def test_default_query_option(self) -> None:
+ await test_client.close()
+ await test_client2.close()
+
+ async def test_default_query_option(self) -> None:
client = AsyncAsktable(
base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"}
)
@@ -1149,8 +1302,10 @@ def test_default_query_option(self) -> None:
url = httpx.URL(request.url)
assert dict(url.params) == {"foo": "baz", "query_param": "overridden"}
- def test_request_extra_json(self) -> None:
- request = self.client._build_request(
+ await client.close()
+
+ def test_request_extra_json(self, client: Asktable) -> None:
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1161,7 +1316,7 @@ def test_request_extra_json(self) -> None:
data = json.loads(request.content.decode("utf-8"))
assert data == {"foo": "bar", "baz": False}
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1172,7 +1327,7 @@ def test_request_extra_json(self) -> None:
assert data == {"baz": False}
# `extra_json` takes priority over `json_data` when keys clash
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1183,8 +1338,8 @@ def test_request_extra_json(self) -> None:
data = json.loads(request.content.decode("utf-8"))
assert data == {"foo": "bar", "baz": None}
- def test_request_extra_headers(self) -> None:
- request = self.client._build_request(
+ def test_request_extra_headers(self, client: Asktable) -> None:
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1194,7 +1349,7 @@ def test_request_extra_headers(self) -> None:
assert request.headers.get("X-Foo") == "Foo"
# `extra_headers` takes priority over `default_headers` when keys clash
- request = self.client.with_options(default_headers={"X-Bar": "true"})._build_request(
+ request = client.with_options(default_headers={"X-Bar": "true"})._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1205,8 +1360,8 @@ def test_request_extra_headers(self) -> None:
)
assert request.headers.get("X-Bar") == "false"
- def test_request_extra_query(self) -> None:
- request = self.client._build_request(
+ def test_request_extra_query(self, client: Asktable) -> None:
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1219,7 +1374,7 @@ def test_request_extra_query(self) -> None:
assert params == {"my_query_param": "Foo"}
# if both `query` and `extra_query` are given, they are merged
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1233,7 +1388,7 @@ def test_request_extra_query(self) -> None:
assert params == {"bar": "1", "foo": "2"}
# `extra_query` takes priority over `query` when keys clash
- request = self.client._build_request(
+ request = client._build_request(
FinalRequestOptions(
method="post",
url="/foo",
@@ -1276,7 +1431,73 @@ def test_multipart_repeating_array(self, async_client: AsyncAsktable) -> None:
]
@pytest.mark.respx(base_url=base_url)
- async def test_basic_union_response(self, respx_mock: MockRouter) -> None:
+ async def test_binary_content_upload(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ response = await async_client.post(
+ "/upload",
+ content=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
+ async def test_binary_content_upload_with_asynciterator(self) -> None:
+ file_content = b"Hello, this is a test file."
+ counter = Counter()
+ iterator = _make_async_iterator([file_content], counter=counter)
+
+ async def mock_handler(request: httpx.Request) -> httpx.Response:
+ assert counter.value == 0, "the request body should not have been read"
+ return httpx.Response(200, content=await request.aread())
+
+ async with AsyncAsktable(
+ base_url=base_url,
+ api_key=api_key,
+ _strict_response_validation=True,
+ http_client=httpx.AsyncClient(transport=MockTransport(handler=mock_handler)),
+ ) as client:
+ response = await client.post(
+ "/upload",
+ content=iterator,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+ assert counter.value == 1
+
+ @pytest.mark.respx(base_url=base_url)
+ async def test_binary_content_upload_with_body_is_deprecated(
+ self, respx_mock: MockRouter, async_client: AsyncAsktable
+ ) -> None:
+ respx_mock.post("/upload").mock(side_effect=mirror_request_content)
+
+ file_content = b"Hello, this is a test file."
+
+ with pytest.deprecated_call(
+ match="Passing raw bytes as `body` is deprecated and will be removed in a future version. Please pass raw bytes via the `content` parameter instead."
+ ):
+ response = await async_client.post(
+ "/upload",
+ body=file_content,
+ cast_to=httpx.Response,
+ options={"headers": {"Content-Type": "application/octet-stream"}},
+ )
+
+ assert response.status_code == 200
+ assert response.request.headers["Content-Type"] == "application/octet-stream"
+ assert response.content == file_content
+
+ @pytest.mark.respx(base_url=base_url)
+ async def test_basic_union_response(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
class Model1(BaseModel):
name: str
@@ -1285,12 +1506,12 @@ class Model2(BaseModel):
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))
- response = await self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
+ response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
assert isinstance(response, Model2)
assert response.foo == "bar"
@pytest.mark.respx(base_url=base_url)
- async def test_union_response_different_types(self, respx_mock: MockRouter) -> None:
+ async def test_union_response_different_types(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
"""Union of objects with the same field name using a different type"""
class Model1(BaseModel):
@@ -1301,18 +1522,20 @@ class Model2(BaseModel):
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))
- response = await self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
+ response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
assert isinstance(response, Model2)
assert response.foo == "bar"
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": 1}))
- response = await self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
+ response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
assert isinstance(response, Model1)
assert response.foo == 1
@pytest.mark.respx(base_url=base_url)
- async def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter) -> None:
+ async def test_non_application_json_content_type_for_json_data(
+ self, respx_mock: MockRouter, async_client: AsyncAsktable
+ ) -> None:
"""
Response that sets Content-Type to something other than application/json but returns json data
"""
@@ -1328,11 +1551,11 @@ class Model(BaseModel):
)
)
- response = await self.client.get("/foo", cast_to=Model)
+ response = await async_client.get("/foo", cast_to=Model)
assert isinstance(response, Model)
assert response.foo == 2
- def test_base_url_setter(self) -> None:
+ async def test_base_url_setter(self) -> None:
client = AsyncAsktable(
base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True
)
@@ -1342,7 +1565,9 @@ def test_base_url_setter(self) -> None:
assert client.base_url == "https://example.com/from_setter/"
- def test_base_url_env(self) -> None:
+ await client.close()
+
+ async def test_base_url_env(self) -> None:
with update_env(ASKTABLE_BASE_URL="http://localhost:5000/from/env"):
client = AsyncAsktable(api_key=api_key, _strict_response_validation=True)
assert client.base_url == "http://localhost:5000/from/env/"
@@ -1362,7 +1587,7 @@ def test_base_url_env(self) -> None:
],
ids=["standard", "custom http client"],
)
- def test_base_url_trailing_slash(self, client: AsyncAsktable) -> None:
+ async def test_base_url_trailing_slash(self, client: AsyncAsktable) -> None:
request = client._build_request(
FinalRequestOptions(
method="post",
@@ -1371,6 +1596,7 @@ def test_base_url_trailing_slash(self, client: AsyncAsktable) -> None:
),
)
assert request.url == "http://localhost:5000/custom/path/foo"
+ await client.close()
@pytest.mark.parametrize(
"client",
@@ -1387,7 +1613,7 @@ def test_base_url_trailing_slash(self, client: AsyncAsktable) -> None:
],
ids=["standard", "custom http client"],
)
- def test_base_url_no_trailing_slash(self, client: AsyncAsktable) -> None:
+ async def test_base_url_no_trailing_slash(self, client: AsyncAsktable) -> None:
request = client._build_request(
FinalRequestOptions(
method="post",
@@ -1396,6 +1622,7 @@ def test_base_url_no_trailing_slash(self, client: AsyncAsktable) -> None:
),
)
assert request.url == "http://localhost:5000/custom/path/foo"
+ await client.close()
@pytest.mark.parametrize(
"client",
@@ -1412,7 +1639,7 @@ def test_base_url_no_trailing_slash(self, client: AsyncAsktable) -> None:
],
ids=["standard", "custom http client"],
)
- def test_absolute_request_url(self, client: AsyncAsktable) -> None:
+ async def test_absolute_request_url(self, client: AsyncAsktable) -> None:
request = client._build_request(
FinalRequestOptions(
method="post",
@@ -1421,37 +1648,37 @@ def test_absolute_request_url(self, client: AsyncAsktable) -> None:
),
)
assert request.url == "https://myapi.com/foo"
+ await client.close()
async def test_copied_client_does_not_close_http(self) -> None:
- client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
- assert not client.is_closed()
+ test_client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
+ assert not test_client.is_closed()
- copied = client.copy()
- assert copied is not client
+ copied = test_client.copy()
+ assert copied is not test_client
del copied
await asyncio.sleep(0.2)
- assert not client.is_closed()
+ assert not test_client.is_closed()
async def test_client_context_manager(self) -> None:
- client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
- async with client as c2:
- assert c2 is client
+ test_client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
+ async with test_client as c2:
+ assert c2 is test_client
assert not c2.is_closed()
- assert not client.is_closed()
- assert client.is_closed()
+ assert not test_client.is_closed()
+ assert test_client.is_closed()
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
- async def test_client_response_validation_error(self, respx_mock: MockRouter) -> None:
+ async def test_client_response_validation_error(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
class Model(BaseModel):
foo: str
respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": {"invalid": True}}))
with pytest.raises(APIResponseValidationError) as exc:
- await self.client.get("/foo", cast_to=Model)
+ await async_client.get("/foo", cast_to=Model)
assert isinstance(exc.value.__cause__, ValidationError)
@@ -1462,7 +1689,6 @@ async def test_client_max_retries_validation(self) -> None:
)
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
async def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None:
class Model(BaseModel):
name: str
@@ -1474,11 +1700,14 @@ class Model(BaseModel):
with pytest.raises(APIResponseValidationError):
await strict_client.get("/foo", cast_to=Model)
- client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=False)
+ non_strict_client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=False)
- response = await client.get("/foo", cast_to=Model)
+ response = await non_strict_client.get("/foo", cast_to=Model)
assert isinstance(response, str) # type: ignore[unreachable]
+ await strict_client.close()
+ await non_strict_client.close()
+
@pytest.mark.parametrize(
"remaining_retries,retry_after,timeout",
[
@@ -1501,13 +1730,12 @@ class Model(BaseModel):
],
)
@mock.patch("time.time", mock.MagicMock(return_value=1696004797))
- @pytest.mark.asyncio
- async def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str, timeout: float) -> None:
- client = AsyncAsktable(base_url=base_url, api_key=api_key, _strict_response_validation=True)
-
+ async def test_parse_retry_after_header(
+ self, remaining_retries: int, retry_after: str, timeout: float, async_client: AsyncAsktable
+ ) -> None:
headers = httpx.Headers({"retry-after": retry_after})
options = FinalRequestOptions(method="get", url="/foo", max_retries=3)
- calculated = client._calculate_retry_timeout(remaining_retries, options, headers)
+ calculated = async_client._calculate_retry_timeout(remaining_retries, options, headers)
assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType]
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@@ -1520,7 +1748,7 @@ async def test_retrying_timeout_errors_doesnt_leak(
with pytest.raises(APITimeoutError):
await async_client.datasources.with_streaming_response.create(engine="mysql").__aenter__()
- assert _get_open_connections(self.client) == 0
+ assert _get_open_connections(async_client) == 0
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@pytest.mark.respx(base_url=base_url)
@@ -1531,12 +1759,11 @@ async def test_retrying_status_errors_doesnt_leak(
with pytest.raises(APIStatusError):
await async_client.datasources.with_streaming_response.create(engine="mysql").__aenter__()
- assert _get_open_connections(self.client) == 0
+ assert _get_open_connections(async_client) == 0
@pytest.mark.parametrize("failures_before_success", [0, 2, 4])
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
@pytest.mark.parametrize("failure_mode", ["status", "exception"])
async def test_retries_taken(
self,
@@ -1568,7 +1795,6 @@ def retry_handler(_request: httpx.Request) -> httpx.Response:
@pytest.mark.parametrize("failures_before_success", [0, 2, 4])
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
async def test_omit_retry_count_header(
self, async_client: AsyncAsktable, failures_before_success: int, respx_mock: MockRouter
) -> None:
@@ -1594,7 +1820,6 @@ def retry_handler(_request: httpx.Request) -> httpx.Response:
@pytest.mark.parametrize("failures_before_success", [0, 2, 4])
@mock.patch("asktable._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout)
@pytest.mark.respx(base_url=base_url)
- @pytest.mark.asyncio
async def test_overwrite_retry_count_header(
self, async_client: AsyncAsktable, failures_before_success: int, respx_mock: MockRouter
) -> None:
@@ -1617,54 +1842,21 @@ def retry_handler(_request: httpx.Request) -> httpx.Response:
assert response.http_request.headers.get("x-stainless-retry-count") == "42"
- def test_get_platform(self) -> None:
- # A previous implementation of asyncify could leave threads unterminated when
- # used with nest_asyncio.
- #
- # Since nest_asyncio.apply() is global and cannot be un-applied, this
- # test is run in a separate process to avoid affecting other tests.
- test_code = dedent("""
- import asyncio
- import nest_asyncio
- import threading
-
- from asktable._utils import asyncify
- from asktable._base_client import get_platform
-
- async def test_main() -> None:
- result = await asyncify(get_platform)()
- print(result)
- for thread in threading.enumerate():
- print(thread.name)
-
- nest_asyncio.apply()
- asyncio.run(test_main())
- """)
- with subprocess.Popen(
- [sys.executable, "-c", test_code],
- text=True,
- ) as process:
- timeout = 10 # seconds
-
- start_time = time.monotonic()
- while True:
- return_code = process.poll()
- if return_code is not None:
- if return_code != 0:
- raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code")
-
- # success
- break
-
- if time.monotonic() - start_time > timeout:
- process.kill()
- raise AssertionError("calling get_platform using asyncify resulted in a hung process")
-
- time.sleep(0.1)
+ async def test_get_platform(self) -> None:
+ platform = await asyncify(get_platform)()
+ assert isinstance(platform, (str, OtherPlatform))
async def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None:
# Test that the proxy environment variables are set correctly
monkeypatch.setenv("HTTPS_PROXY", "https://example.org")
+ # Delete in case our environment has any proxy env vars set
+ monkeypatch.delenv("HTTP_PROXY", raising=False)
+ monkeypatch.delenv("ALL_PROXY", raising=False)
+ monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("http_proxy", raising=False)
+ monkeypatch.delenv("https_proxy", raising=False)
+ monkeypatch.delenv("all_proxy", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
client = DefaultAsyncHttpxClient()
@@ -1685,26 +1877,26 @@ async def test_default_client_creation(self) -> None:
)
@pytest.mark.respx(base_url=base_url)
- async def test_follow_redirects(self, respx_mock: MockRouter) -> None:
+ async def test_follow_redirects(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
# Test that the default follow_redirects=True allows following redirects
respx_mock.post("/redirect").mock(
return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"})
)
respx_mock.get("/redirected").mock(return_value=httpx.Response(200, json={"status": "ok"}))
- response = await self.client.post("/redirect", body={"key": "value"}, cast_to=httpx.Response)
+ response = await async_client.post("/redirect", body={"key": "value"}, cast_to=httpx.Response)
assert response.status_code == 200
assert response.json() == {"status": "ok"}
@pytest.mark.respx(base_url=base_url)
- async def test_follow_redirects_disabled(self, respx_mock: MockRouter) -> None:
+ async def test_follow_redirects_disabled(self, respx_mock: MockRouter, async_client: AsyncAsktable) -> None:
# Test that follow_redirects=False prevents following redirects
respx_mock.post("/redirect").mock(
return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"})
)
with pytest.raises(APIStatusError) as exc_info:
- await self.client.post(
+ await async_client.post(
"/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx.Response
)
diff --git a/tests/test_models.py b/tests/test_models.py
index 7864490f..e9493521 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -1,5 +1,5 @@
import json
-from typing import Any, Dict, List, Union, Optional, cast
+from typing import TYPE_CHECKING, Any, Dict, List, Union, Optional, cast
from datetime import datetime, timezone
from typing_extensions import Literal, Annotated, TypeAliasType
@@ -8,8 +8,8 @@
from pydantic import Field
from asktable._utils import PropertyInfo
-from asktable._compat import PYDANTIC_V2, parse_obj, model_dump, model_json
-from asktable._models import BaseModel, construct_type
+from asktable._compat import PYDANTIC_V1, parse_obj, model_dump, model_json
+from asktable._models import DISCRIMINATOR_CACHE, BaseModel, construct_type
class BasicModel(BaseModel):
@@ -294,12 +294,12 @@ class Model(BaseModel):
assert cast(bool, m.foo) is True
m = Model.construct(foo={"name": 3})
- if PYDANTIC_V2:
- assert isinstance(m.foo, Submodel1)
- assert m.foo.name == 3 # type: ignore
- else:
+ if PYDANTIC_V1:
assert isinstance(m.foo, Submodel2)
assert m.foo.name == "3"
+ else:
+ assert isinstance(m.foo, Submodel1)
+ assert m.foo.name == 3 # type: ignore
def test_list_of_unions() -> None:
@@ -426,10 +426,10 @@ class Model(BaseModel):
expected = datetime(2019, 12, 27, 18, 11, 19, 117000, tzinfo=timezone.utc)
- if PYDANTIC_V2:
- expected_json = '{"created_at":"2019-12-27T18:11:19.117000Z"}'
- else:
+ if PYDANTIC_V1:
expected_json = '{"created_at": "2019-12-27T18:11:19.117000+00:00"}'
+ else:
+ expected_json = '{"created_at":"2019-12-27T18:11:19.117000Z"}'
model = Model.construct(created_at="2019-12-27T18:11:19.117Z")
assert model.created_at == expected
@@ -531,7 +531,7 @@ class Model2(BaseModel):
assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)}
assert m4.to_dict(mode="json") == {"created_at": time_str}
- if not PYDANTIC_V2:
+ if PYDANTIC_V1:
with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"):
m.to_dict(warnings=False)
@@ -556,7 +556,7 @@ class Model(BaseModel):
assert m3.model_dump() == {"foo": None}
assert m3.model_dump(exclude_none=True) == {}
- if not PYDANTIC_V2:
+ if PYDANTIC_V1:
with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"):
m.model_dump(round_trip=True)
@@ -580,10 +580,10 @@ class Model(BaseModel):
assert json.loads(m.to_json()) == {"FOO": "hello"}
assert json.loads(m.to_json(use_api_names=False)) == {"foo": "hello"}
- if PYDANTIC_V2:
- assert m.to_json(indent=None) == '{"FOO":"hello"}'
- else:
+ if PYDANTIC_V1:
assert m.to_json(indent=None) == '{"FOO": "hello"}'
+ else:
+ assert m.to_json(indent=None) == '{"FOO":"hello"}'
m2 = Model()
assert json.loads(m2.to_json()) == {}
@@ -595,7 +595,7 @@ class Model(BaseModel):
assert json.loads(m3.to_json()) == {"FOO": None}
assert json.loads(m3.to_json(exclude_none=True)) == {}
- if not PYDANTIC_V2:
+ if PYDANTIC_V1:
with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"):
m.to_json(warnings=False)
@@ -622,7 +622,7 @@ class Model(BaseModel):
assert json.loads(m3.model_dump_json()) == {"foo": None}
assert json.loads(m3.model_dump_json(exclude_none=True)) == {}
- if not PYDANTIC_V2:
+ if PYDANTIC_V1:
with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"):
m.model_dump_json(round_trip=True)
@@ -679,12 +679,12 @@ class B(BaseModel):
)
assert isinstance(m, A)
assert m.type == "a"
- if PYDANTIC_V2:
- assert m.data == 100 # type: ignore[comparison-overlap]
- else:
+ if PYDANTIC_V1:
# pydantic v1 automatically converts inputs to strings
# if the expected type is a str
assert m.data == "100"
+ else:
+ assert m.data == 100 # type: ignore[comparison-overlap]
def test_discriminated_unions_unknown_variant() -> None:
@@ -768,12 +768,12 @@ class B(BaseModel):
)
assert isinstance(m, A)
assert m.foo_type == "a"
- if PYDANTIC_V2:
- assert m.data == 100 # type: ignore[comparison-overlap]
- else:
+ if PYDANTIC_V1:
# pydantic v1 automatically converts inputs to strings
# if the expected type is a str
assert m.data == "100"
+ else:
+ assert m.data == 100 # type: ignore[comparison-overlap]
def test_discriminated_unions_overlapping_discriminators_invalid_data() -> None:
@@ -809,7 +809,7 @@ class B(BaseModel):
UnionType = cast(Any, Union[A, B])
- assert not hasattr(UnionType, "__discriminator__")
+ assert not DISCRIMINATOR_CACHE.get(UnionType)
m = construct_type(
value={"type": "b", "data": "foo"}, type_=cast(Any, Annotated[UnionType, PropertyInfo(discriminator="type")])
@@ -818,7 +818,7 @@ class B(BaseModel):
assert m.type == "b"
assert m.data == "foo" # type: ignore[comparison-overlap]
- discriminator = UnionType.__discriminator__
+ discriminator = DISCRIMINATOR_CACHE.get(UnionType)
assert discriminator is not None
m = construct_type(
@@ -830,10 +830,10 @@ class B(BaseModel):
# if the discriminator details object stays the same between invocations then
# we hit the cache
- assert UnionType.__discriminator__ is discriminator
+ assert DISCRIMINATOR_CACHE.get(UnionType) is discriminator
-@pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1")
+@pytest.mark.skipif(PYDANTIC_V1, reason="TypeAliasType is not supported in Pydantic v1")
def test_type_alias_type() -> None:
Alias = TypeAliasType("Alias", str) # pyright: ignore
@@ -849,7 +849,7 @@ class Model(BaseModel):
assert m.union == "bar"
-@pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1")
+@pytest.mark.skipif(PYDANTIC_V1, reason="TypeAliasType is not supported in Pydantic v1")
def test_field_named_cls() -> None:
class Model(BaseModel):
cls: str
@@ -934,3 +934,30 @@ class Type2(BaseModel):
)
assert isinstance(model, Type1)
assert isinstance(model.value, InnerType2)
+
+
+@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2 for now")
+def test_extra_properties() -> None:
+ class Item(BaseModel):
+ prop: int
+
+ class Model(BaseModel):
+ __pydantic_extra__: Dict[str, Item] = Field(init=False) # pyright: ignore[reportIncompatibleVariableOverride]
+
+ other: str
+
+ if TYPE_CHECKING:
+
+ def __getattr__(self, attr: str) -> Item: ...
+
+ model = construct_type(
+ type_=Model,
+ value={
+ "a": {"prop": 1},
+ "other": "foo",
+ },
+ )
+ assert isinstance(model, Model)
+ assert model.a.prop == 1
+ assert isinstance(model.a, Item)
+ assert model.other == "foo"
diff --git a/tests/test_transform.py b/tests/test_transform.py
index 33ea35d8..35192dc9 100644
--- a/tests/test_transform.py
+++ b/tests/test_transform.py
@@ -8,14 +8,14 @@
import pytest
-from asktable._types import NOT_GIVEN, Base64FileInput
+from asktable._types import Base64FileInput, omit, not_given
from asktable._utils import (
PropertyInfo,
transform as _transform,
parse_datetime,
async_transform as _async_transform,
)
-from asktable._compat import PYDANTIC_V2
+from asktable._compat import PYDANTIC_V1
from asktable._models import BaseModel
_T = TypeVar("_T")
@@ -189,7 +189,7 @@ class DateModel(BaseModel):
@pytest.mark.asyncio
async def test_iso8601_format(use_async: bool) -> None:
dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00")
- tz = "Z" if PYDANTIC_V2 else "+00:00"
+ tz = "+00:00" if PYDANTIC_V1 else "Z"
assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap]
assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692" + tz} # type: ignore[comparison-overlap]
@@ -297,11 +297,11 @@ async def test_pydantic_unknown_field(use_async: bool) -> None:
@pytest.mark.asyncio
async def test_pydantic_mismatched_types(use_async: bool) -> None:
model = MyModel.construct(foo=True)
- if PYDANTIC_V2:
+ if PYDANTIC_V1:
+ params = await transform(model, Any, use_async)
+ else:
with pytest.warns(UserWarning):
params = await transform(model, Any, use_async)
- else:
- params = await transform(model, Any, use_async)
assert cast(Any, params) == {"foo": True}
@@ -309,11 +309,11 @@ async def test_pydantic_mismatched_types(use_async: bool) -> None:
@pytest.mark.asyncio
async def test_pydantic_mismatched_object_type(use_async: bool) -> None:
model = MyModel.construct(foo=MyModel.construct(hello="world"))
- if PYDANTIC_V2:
+ if PYDANTIC_V1:
+ params = await transform(model, Any, use_async)
+ else:
with pytest.warns(UserWarning):
params = await transform(model, Any, use_async)
- else:
- params = await transform(model, Any, use_async)
assert cast(Any, params) == {"foo": {"hello": "world"}}
@@ -450,4 +450,11 @@ async def test_transform_skipping(use_async: bool) -> None:
@pytest.mark.asyncio
async def test_strips_notgiven(use_async: bool) -> None:
assert await transform({"foo_bar": "bar"}, Foo1, use_async) == {"fooBar": "bar"}
- assert await transform({"foo_bar": NOT_GIVEN}, Foo1, use_async) == {}
+ assert await transform({"foo_bar": not_given}, Foo1, use_async) == {}
+
+
+@parametrize
+@pytest.mark.asyncio
+async def test_strips_omit(use_async: bool) -> None:
+ assert await transform({"foo_bar": "bar"}, Foo1, use_async) == {"fooBar": "bar"}
+ assert await transform({"foo_bar": omit}, Foo1, use_async) == {}
diff --git a/tests/test_utils/test_datetime_parse.py b/tests/test_utils/test_datetime_parse.py
new file mode 100644
index 00000000..e710e2d2
--- /dev/null
+++ b/tests/test_utils/test_datetime_parse.py
@@ -0,0 +1,110 @@
+"""
+Copied from https://github.com/pydantic/pydantic/blob/v1.10.22/tests/test_datetime_parse.py
+with modifications so it works without pydantic v1 imports.
+"""
+
+from typing import Type, Union
+from datetime import date, datetime, timezone, timedelta
+
+import pytest
+
+from asktable._utils import parse_date, parse_datetime
+
+
+def create_tz(minutes: int) -> timezone:
+ return timezone(timedelta(minutes=minutes))
+
+
+@pytest.mark.parametrize(
+ "value,result",
+ [
+ # Valid inputs
+ ("1494012444.883309", date(2017, 5, 5)),
+ (b"1494012444.883309", date(2017, 5, 5)),
+ (1_494_012_444.883_309, date(2017, 5, 5)),
+ ("1494012444", date(2017, 5, 5)),
+ (1_494_012_444, date(2017, 5, 5)),
+ (0, date(1970, 1, 1)),
+ ("2012-04-23", date(2012, 4, 23)),
+ (b"2012-04-23", date(2012, 4, 23)),
+ ("2012-4-9", date(2012, 4, 9)),
+ (date(2012, 4, 9), date(2012, 4, 9)),
+ (datetime(2012, 4, 9, 12, 15), date(2012, 4, 9)),
+ # Invalid inputs
+ ("x20120423", ValueError),
+ ("2012-04-56", ValueError),
+ (19_999_999_999, date(2603, 10, 11)), # just before watershed
+ (20_000_000_001, date(1970, 8, 20)), # just after watershed
+ (1_549_316_052, date(2019, 2, 4)), # nowish in s
+ (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms
+ (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs
+ (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns
+ ("infinity", date(9999, 12, 31)),
+ ("inf", date(9999, 12, 31)),
+ (float("inf"), date(9999, 12, 31)),
+ ("infinity ", date(9999, 12, 31)),
+ (int("1" + "0" * 100), date(9999, 12, 31)),
+ (1e1000, date(9999, 12, 31)),
+ ("-infinity", date(1, 1, 1)),
+ ("-inf", date(1, 1, 1)),
+ ("nan", ValueError),
+ ],
+)
+def test_date_parsing(value: Union[str, bytes, int, float], result: Union[date, Type[Exception]]) -> None:
+ if type(result) == type and issubclass(result, Exception): # pyright: ignore[reportUnnecessaryIsInstance]
+ with pytest.raises(result):
+ parse_date(value)
+ else:
+ assert parse_date(value) == result
+
+
+@pytest.mark.parametrize(
+ "value,result",
+ [
+ # Valid inputs
+ # values in seconds
+ ("1494012444.883309", datetime(2017, 5, 5, 19, 27, 24, 883_309, tzinfo=timezone.utc)),
+ (1_494_012_444.883_309, datetime(2017, 5, 5, 19, 27, 24, 883_309, tzinfo=timezone.utc)),
+ ("1494012444", datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)),
+ (b"1494012444", datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)),
+ (1_494_012_444, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)),
+ # values in ms
+ ("1494012444000.883309", datetime(2017, 5, 5, 19, 27, 24, 883, tzinfo=timezone.utc)),
+ ("-1494012444000.883309", datetime(1922, 8, 29, 4, 32, 35, 999117, tzinfo=timezone.utc)),
+ (1_494_012_444_000, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)),
+ ("2012-04-23T09:15:00", datetime(2012, 4, 23, 9, 15)),
+ ("2012-4-9 4:8:16", datetime(2012, 4, 9, 4, 8, 16)),
+ ("2012-04-23T09:15:00Z", datetime(2012, 4, 23, 9, 15, 0, 0, timezone.utc)),
+ ("2012-4-9 4:8:16-0320", datetime(2012, 4, 9, 4, 8, 16, 0, create_tz(-200))),
+ ("2012-04-23T10:20:30.400+02:30", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(150))),
+ ("2012-04-23T10:20:30.400+02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(120))),
+ ("2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))),
+ (b"2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))),
+ (datetime(2017, 5, 5), datetime(2017, 5, 5)),
+ (0, datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.utc)),
+ # Invalid inputs
+ ("x20120423091500", ValueError),
+ ("2012-04-56T09:15:90", ValueError),
+ ("2012-04-23T11:05:00-25:00", ValueError),
+ (19_999_999_999, datetime(2603, 10, 11, 11, 33, 19, tzinfo=timezone.utc)), # just before watershed
+ (20_000_000_001, datetime(1970, 8, 20, 11, 33, 20, 1000, tzinfo=timezone.utc)), # just after watershed
+ (1_549_316_052, datetime(2019, 2, 4, 21, 34, 12, 0, tzinfo=timezone.utc)), # nowish in s
+ (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms
+ (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs
+ (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in ns
+ ("infinity", datetime(9999, 12, 31, 23, 59, 59, 999999)),
+ ("inf", datetime(9999, 12, 31, 23, 59, 59, 999999)),
+ ("inf ", datetime(9999, 12, 31, 23, 59, 59, 999999)),
+ (1e50, datetime(9999, 12, 31, 23, 59, 59, 999999)),
+ (float("inf"), datetime(9999, 12, 31, 23, 59, 59, 999999)),
+ ("-infinity", datetime(1, 1, 1, 0, 0)),
+ ("-inf", datetime(1, 1, 1, 0, 0)),
+ ("nan", ValueError),
+ ],
+)
+def test_datetime_parsing(value: Union[str, bytes, int, float], result: Union[datetime, Type[Exception]]) -> None:
+ if type(result) == type and issubclass(result, Exception): # pyright: ignore[reportUnnecessaryIsInstance]
+ with pytest.raises(result):
+ parse_datetime(value)
+ else:
+ assert parse_datetime(value) == result
diff --git a/tests/test_utils/test_json.py b/tests/test_utils/test_json.py
new file mode 100644
index 00000000..0f447f23
--- /dev/null
+++ b/tests/test_utils/test_json.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import datetime
+from typing import Union
+
+import pydantic
+
+from asktable import _compat
+from asktable._utils._json import openapi_dumps
+
+
+class TestOpenapiDumps:
+ def test_basic(self) -> None:
+ data = {"key": "value", "number": 42}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"key":"value","number":42}'
+
+ def test_datetime_serialization(self) -> None:
+ dt = datetime.datetime(2023, 1, 1, 12, 0, 0)
+ data = {"datetime": dt}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"datetime":"2023-01-01T12:00:00"}'
+
+ def test_pydantic_model_serialization(self) -> None:
+ class User(pydantic.BaseModel):
+ first_name: str
+ last_name: str
+ age: int
+
+ model_instance = User(first_name="John", last_name="Kramer", age=83)
+ data = {"model": model_instance}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"first_name":"John","last_name":"Kramer","age":83}}'
+
+ def test_pydantic_model_with_default_values(self) -> None:
+ class User(pydantic.BaseModel):
+ name: str
+ role: str = "user"
+ active: bool = True
+ score: int = 0
+
+ model_instance = User(name="Alice")
+ data = {"model": model_instance}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"name":"Alice"}}'
+
+ def test_pydantic_model_with_default_values_overridden(self) -> None:
+ class User(pydantic.BaseModel):
+ name: str
+ role: str = "user"
+ active: bool = True
+
+ model_instance = User(name="Bob", role="admin", active=False)
+ data = {"model": model_instance}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"name":"Bob","role":"admin","active":false}}'
+
+ def test_pydantic_model_with_alias(self) -> None:
+ class User(pydantic.BaseModel):
+ first_name: str = pydantic.Field(alias="firstName")
+ last_name: str = pydantic.Field(alias="lastName")
+
+ model_instance = User(firstName="John", lastName="Doe")
+ data = {"model": model_instance}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"firstName":"John","lastName":"Doe"}}'
+
+ def test_pydantic_model_with_alias_and_default(self) -> None:
+ class User(pydantic.BaseModel):
+ user_name: str = pydantic.Field(alias="userName")
+ user_role: str = pydantic.Field(default="member", alias="userRole")
+ is_active: bool = pydantic.Field(default=True, alias="isActive")
+
+ model_instance = User(userName="charlie")
+ data = {"model": model_instance}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"userName":"charlie"}}'
+
+ model_with_overrides = User(userName="diana", userRole="admin", isActive=False)
+ data = {"model": model_with_overrides}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"userName":"diana","userRole":"admin","isActive":false}}'
+
+ def test_pydantic_model_with_nested_models_and_defaults(self) -> None:
+ class Address(pydantic.BaseModel):
+ street: str
+ city: str = "Unknown"
+
+ class User(pydantic.BaseModel):
+ name: str
+ address: Address
+ verified: bool = False
+
+ if _compat.PYDANTIC_V1:
+ # to handle forward references in Pydantic v1
+ User.update_forward_refs(**locals()) # type: ignore[reportDeprecated]
+
+ address = Address(street="123 Main St")
+ user = User(name="Diana", address=address)
+ data = {"user": user}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"user":{"name":"Diana","address":{"street":"123 Main St"}}}'
+
+ address_with_city = Address(street="456 Oak Ave", city="Boston")
+ user_verified = User(name="Eve", address=address_with_city, verified=True)
+ data = {"user": user_verified}
+ json_bytes = openapi_dumps(data)
+ assert (
+ json_bytes == b'{"user":{"name":"Eve","address":{"street":"456 Oak Ave","city":"Boston"},"verified":true}}'
+ )
+
+ def test_pydantic_model_with_optional_fields(self) -> None:
+ class User(pydantic.BaseModel):
+ name: str
+ email: Union[str, None]
+ phone: Union[str, None]
+
+ model_with_none = User(name="Eve", email=None, phone=None)
+ data = {"model": model_with_none}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"name":"Eve","email":null,"phone":null}}'
+
+ model_with_values = User(name="Frank", email="frank@example.com", phone=None)
+ data = {"model": model_with_values}
+ json_bytes = openapi_dumps(data)
+ assert json_bytes == b'{"model":{"name":"Frank","email":"frank@example.com","phone":null}}'
diff --git a/tests/test_utils/test_path.py b/tests/test_utils/test_path.py
new file mode 100644
index 00000000..1c6c154b
--- /dev/null
+++ b/tests/test_utils/test_path.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from asktable._utils._path import path_template
+
+
+@pytest.mark.parametrize(
+ "template, kwargs, expected",
+ [
+ ("/v1/{id}", dict(id="abc"), "/v1/abc"),
+ ("/v1/{a}/{b}", dict(a="x", b="y"), "/v1/x/y"),
+ ("/v1/{a}{b}/path/{c}?val={d}#{e}", dict(a="x", b="y", c="z", d="u", e="v"), "/v1/xy/path/z?val=u#v"),
+ ("/{w}/{w}", dict(w="echo"), "/echo/echo"),
+ ("/v1/static", {}, "/v1/static"),
+ ("", {}, ""),
+ ("/v1/?q={n}&count=10", dict(n=42), "/v1/?q=42&count=10"),
+ ("/v1/{v}", dict(v=None), "/v1/null"),
+ ("/v1/{v}", dict(v=True), "/v1/true"),
+ ("/v1/{v}", dict(v=False), "/v1/false"),
+ ("/v1/{v}", dict(v=".hidden"), "/v1/.hidden"), # dot prefix ok
+ ("/v1/{v}", dict(v="file.txt"), "/v1/file.txt"), # dot in middle ok
+ ("/v1/{v}", dict(v="..."), "/v1/..."), # triple dot ok
+ ("/v1/{a}{b}", dict(a=".", b="txt"), "/v1/.txt"), # dot var combining with adjacent to be ok
+ ("/items?q={v}#{f}", dict(v=".", f=".."), "/items?q=.#.."), # dots in query/fragment are fine
+ (
+ "/v1/{a}?query={b}",
+ dict(a="../../other/endpoint", b="a&bad=true"),
+ "/v1/..%2F..%2Fother%2Fendpoint?query=a%26bad%3Dtrue",
+ ),
+ ("/v1/{val}", dict(val="a/b/c"), "/v1/a%2Fb%2Fc"),
+ ("/v1/{val}", dict(val="a/b/c?query=value"), "/v1/a%2Fb%2Fc%3Fquery=value"),
+ ("/v1/{val}", dict(val="a/b/c?query=value&bad=true"), "/v1/a%2Fb%2Fc%3Fquery=value&bad=true"),
+ ("/v1/{val}", dict(val="%20"), "/v1/%2520"), # escapes escape sequences in input
+ # Query: slash and ? are safe, # is not
+ ("/items?q={v}", dict(v="a/b"), "/items?q=a/b"),
+ ("/items?q={v}", dict(v="a?b"), "/items?q=a?b"),
+ ("/items?q={v}", dict(v="a#b"), "/items?q=a%23b"),
+ ("/items?q={v}", dict(v="a b"), "/items?q=a%20b"),
+ # Fragment: slash and ? are safe
+ ("/docs#{v}", dict(v="a/b"), "/docs#a/b"),
+ ("/docs#{v}", dict(v="a?b"), "/docs#a?b"),
+ # Path: slash, ? and # are all encoded
+ ("/v1/{v}", dict(v="a/b"), "/v1/a%2Fb"),
+ ("/v1/{v}", dict(v="a?b"), "/v1/a%3Fb"),
+ ("/v1/{v}", dict(v="a#b"), "/v1/a%23b"),
+ # same var encoded differently by component
+ (
+ "/v1/{v}?q={v}#{v}",
+ dict(v="a/b?c#d"),
+ "/v1/a%2Fb%3Fc%23d?q=a/b?c%23d#a/b?c%23d",
+ ),
+ ("/v1/{val}", dict(val="x?admin=true"), "/v1/x%3Fadmin=true"), # query injection
+ ("/v1/{val}", dict(val="x#admin"), "/v1/x%23admin"), # fragment injection
+ ],
+)
+def test_interpolation(template: str, kwargs: dict[str, Any], expected: str) -> None:
+ assert path_template(template, **kwargs) == expected
+
+
+def test_missing_kwarg_raises_key_error() -> None:
+ with pytest.raises(KeyError, match="org_id"):
+ path_template("/v1/{org_id}")
+
+
+@pytest.mark.parametrize(
+ "template, kwargs",
+ [
+ ("{a}/path", dict(a=".")),
+ ("{a}/path", dict(a="..")),
+ ("/v1/{a}", dict(a=".")),
+ ("/v1/{a}", dict(a="..")),
+ ("/v1/{a}/path", dict(a=".")),
+ ("/v1/{a}/path", dict(a="..")),
+ ("/v1/{a}{b}", dict(a=".", b=".")), # adjacent vars → ".."
+ ("/v1/{a}.", dict(a=".")), # var + static → ".."
+ ("/v1/{a}{b}", dict(a="", b=".")), # empty + dot → "."
+ ("/v1/%2e/{x}", dict(x="ok")), # encoded dot in static text
+ ("/v1/%2e./{x}", dict(x="ok")), # mixed encoded ".." in static
+ ("/v1/.%2E/{x}", dict(x="ok")), # mixed encoded ".." in static
+ ("/v1/{v}?q=1", dict(v="..")),
+ ("/v1/{v}#frag", dict(v="..")),
+ ],
+)
+def test_dot_segment_rejected(template: str, kwargs: dict[str, Any]) -> None:
+ with pytest.raises(ValueError, match="dot-segment"):
+ path_template(template, **kwargs)
diff --git a/tests/utils.py b/tests/utils.py
index 7497343a..b84eaf23 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -4,7 +4,7 @@
import inspect
import traceback
import contextlib
-from typing import Any, TypeVar, Iterator, cast
+from typing import Any, TypeVar, Iterator, Sequence, cast
from datetime import date, datetime
from typing_extensions import Literal, get_args, get_origin, assert_type
@@ -15,10 +15,11 @@
is_list_type,
is_union_type,
extract_type_arg,
+ is_sequence_type,
is_annotated_type,
is_type_alias_type,
)
-from asktable._compat import PYDANTIC_V2, field_outer_type, get_model_fields
+from asktable._compat import PYDANTIC_V1, field_outer_type, get_model_fields
from asktable._models import BaseModel
BaseModelT = TypeVar("BaseModelT", bound=BaseModel)
@@ -27,12 +28,12 @@
def assert_matches_model(model: type[BaseModelT], value: BaseModelT, *, path: list[str]) -> bool:
for name, field in get_model_fields(model).items():
field_value = getattr(value, name)
- if PYDANTIC_V2:
- allow_none = False
- else:
+ if PYDANTIC_V1:
# in v1 nullability was structured differently
# https://docs.pydantic.dev/2.0/migration/#required-optional-and-nullable-fields
allow_none = getattr(field, "allow_none", False)
+ else:
+ allow_none = False
assert_matches_type(
field_outer_type(field),
@@ -71,6 +72,13 @@ def assert_matches_type(
if is_list_type(type_):
return _assert_list_type(type_, value)
+ if is_sequence_type(type_):
+ assert isinstance(value, Sequence)
+ inner_type = get_args(type_)[0]
+ for entry in value: # type: ignore
+ assert_type(inner_type, entry) # type: ignore
+ return
+
if origin == str:
assert isinstance(value, str)
elif origin == int: