diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3b4781f21..f74892b1d 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.3.0 +current_version = 11.1.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index dad38e7f5..c5175d316 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -21,11 +21,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.7', '3.8', '3.9'] - os: [ubuntu-latest, windows-latest] - exclude: - - os: windows-latest - python-version: '3.7' + python-version: ['3.11', '3.12', '3.13'] + os: [ubuntu-latest] steps: - uses: actions/checkout@v2 @@ -39,39 +36,23 @@ jobs: pip3 install -r requirements.txt pip3 install -r requirements-dev.txt pip3 install --editable . - - name: Install dependencies (windows) - if: matrix.os == 'windows-latest' - run: | - pip3 install -r requirements.txt --use-deprecated=legacy-resolver - pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver - pip3 install --editable . --use-deprecated=legacy-resolver - - name: Execute Python 3.7 unit tests - if: matrix.python-version == '3.7' + - name: Execute Python 3.11 unit tests + if: matrix.python-version == '3.11' run: | pip3 install -U python-dotenv py.test test/unit - - name: Execute Python 3.8 unit tests (windows) - if: matrix.python-version == '3.8' && matrix.os == 'windows-latest' - run: | - pip3 install -U python-dotenv - py.test test/unit --reruns 3 - - name: Execute Python 3.8 unit tests (ubuntu) - if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.12 unit tests (ubuntu) + if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 --cov=ibm_watson - - name: Execute Python 3.9 unit tests (windows) - if: matrix.python-version == '3.9' && matrix.os == 'windows-latest' - run: | - pip3 install -U python-dotenv - py.test test/unit --reruns 3 - - name: Execute Python 3.9 unit tests (ubuntu) - if: matrix.python-version == '3.9' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.13 unit tests (ubuntu) + if: matrix.python-version == '3.13' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - name: Upload coverage to Codecov - if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 with: name: py${{ matrix.python-version }}-${{ matrix.os }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d8bae9d26..a99ab6f9b 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -15,63 +15,90 @@ on: # Allows you to run this workflow manually from the Actions tab workflow_dispatch: +# default: least privileged permissions across all jobs +permissions: + contents: read + jobs: + release: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + concurrency: + group: ${{ github.workflow }}-release-${{ github.ref_name }} + cancel-in-progress: false + + permissions: + contents: write + + steps: + # Note: We checkout the repository at the branch that triggered the workflow. + # Python Semantic Release will automatically convert shallow clones to full clones + # if needed to ensure proper history evaluation. However, we forcefully reset the + # branch to the workflow sha because it is possible that the branch was updated + # while the workflow was running, which prevents accidentally releasing un-evaluated + # changes. + - name: Setup | Checkout Repository on Release Branch + uses: actions/checkout@v6 + with: + ref: ${{ github.ref_name }} + + - name: Setup | Force release branch to be at workflow sha + run: | + git reset --hard ${{ github.sha }} + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.13" + + - name: Action | Semantic Version Release + id: release + # Adjust tag with desired version if applicable. + uses: python-semantic-release/python-semantic-release@v10.5.3 + with: + github_token: ${{ secrets.GH_TOKEN }} + git_committer_name: "Watson Github Bot" + git_committer_email: "watdevex@us.ibm.com" + + - name: Build a binary wheel and a source tarball + run: pip3 install setuptools wheel twine build && python setup.py sdist + + - name: Publish | Upload to GitHub Release Assets + uses: python-semantic-release/publish-action@v10.5.3 + if: steps.release.outputs.released == 'true' + with: + github_token: ${{ secrets.GH_TOKEN }} + tag: ${{ steps.release.outputs.tag }} + + - name: Upload | Distribution Artifacts + uses: actions/upload-artifact@v5 + with: + name: distribution-artifacts + path: dist/ + if-no-files-found: error + + outputs: + released: ${{ steps.release.outputs.released || 'false' }} + deploy: - if: "!contains(github.event.head_commit.message, 'skip ci')" - name: Deploy and Publish + # 1. Separate out the deploy step from the publish step to run each step at + # the least amount of token privilege + # 2. Also, deployments can fail, and its better to have a separate job if you need to retry + # and it won't require reversing the release. runs-on: ubuntu-latest + needs: release + if: ${{ needs.release.outputs.released == 'true' }} + + permissions: + contents: read + id-token: write # IMPORTANT: mandatory for trusted publishing steps: - - uses: actions/checkout@v2 - with: - persist-credentials: false - - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.9' - - - name: Setup Node - uses: actions/setup-node@v1 - with: - node-version: 14 - - - name: Install Semantic Release dependencies - run: | - sudo apt-get install bumpversion - npm install -g semantic-release - npm install -g @semantic-release/changelog - npm install -g @semantic-release/exec - npm install -g @semantic-release/git - npm install -g @semantic-release/github - npm install -g @semantic-release/commit-analyzer - npm install -g @semantic-release/release-notes-generator - - - name: Publish js docs - if: ${{ github.event.workflow_run.conclusion == 'success' }} - env: - GH_TOKEN: ${{ secrets.GH_TOKEN }} - GHA_BRANCH: ${{ github.ref }} # non PR only need to get last part - GHA_COMMIT: ${{ github.sha }} - run: | - sudo apt-get install python3-sphinx - docs/publish_gha.sh - - - name: Publish to Git Releases and Tags - if: ${{ github.event.workflow_run.conclusion == 'success' }} - env: - GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testxing purposes - - - name: Build binary wheel and a source tarball - run: | - pip3 install setuptools wheel twine build - python -m build --sdist --outdir dist/ - - - name: Publish distribution to Test PyPI - continue-on-error: true - uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release - with: - password: ${{ secrets.PYPI_TOKEN }} - repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org \ No newline at end of file + - name: Download all the dists + uses: actions/download-artifact@v6 + with: + name: distribution-artifacts + path: dist/ + + - name: Publish distribution 📦 to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 059bf7220..d95c423b1 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -15,7 +15,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ["3.8"] + python-version: ["3.11"] os: [ubuntu-latest] steps: @@ -35,8 +35,6 @@ jobs: - name: Execute Python integration tests # continue-on-error: true env: - LANGUAGE_TRANSLATOR_APIKEY: ${{ secrets.LT_APIKEY }} - LANGUAGE_TRANSLATOR_URL: "https://api.us-south.language-translator.watson.cloud.ibm.com" NATURAL_LANGUAGE_UNDERSTANDING_APIKEY: ${{ secrets.NLU_APIKEY }} NATURAL_LANGUAGE_UNDERSTANDING_URL: "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" SPEECH_TO_TEXT_APIKEY: ${{ secrets.STT_APIKEY }} @@ -47,20 +45,13 @@ jobs: ASSISTANT_WORKSPACE_ID: ${{ secrets.WA_WORKSPACE_ID }} ASSISTANT_ASSISTANT_ID: ${{ secrets.WA_ASSISTANT_ID }} ASSISTANT_URL: "https://api.us-south.assistant.watson.cloud.ibm.com" - DISCOVERY_APIKEY: ${{ secrets.D1_APIKEY }} - DISCOVERY_ENVIRONMENT_ID: ${{ secrets.D1_ENVIRONMENT_ID }} - DISCOVERY_COLLECTION_ID: ${{ secrets.D1_COLLECTION_ID }} - DISCOVERY_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" DISCOVERY_V2_APIKEY: ${{ secrets.D2_APIKEY }} DISCOVERY_V2_PROJECT_ID: ${{ secrets.D2_PROJECT_ID }} DISCOVERY_V2_COLLECTION_ID: ${{ secrets.D2_COLLECTION_ID }} DISCOVERY_V2_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" run: | pip3 install -U python-dotenv - pytest test/integration/test_assistant_v1.py -rap - pytest test/integration/test_discovery_v1.py -rap pytest test/integration/test_discovery_v2.py -rap - pytest test/integration/test_language_translator_v3.py -rap pytest test/integration/test_natural_language_understanding_v1.py -rap pytest test/integration/test_speech_to_text_v1.py -rap pytest test/integration/test_text_to_speech_v1.py -rap diff --git a/.secrets.baseline b/.secrets.baseline index a9c0826d5..171a5e191 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|^.secrets.baseline$", "lines": null }, - "generated_at": "2022-03-21T19:21:18Z", + "generated_at": "2024-02-26T19:01:03Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -25,9 +25,7 @@ "name": "CloudantDetector" }, { - "name": "Db2Detector" - }, - { + "ghe_instance": "github.ibm.com", "name": "GheDetector" }, { @@ -67,22 +65,12 @@ } ], "results": { - ".github/workflows/deploy.yml": [ - { - "hashed_secret": "51543e129a641c2ece91b32b5bbeaa704dbfe764", - "is_secret": false, - "is_verified": false, - "line_number": 76, - "type": "DB2 Credentials", - "verified_result": null - } - ], "README.md": [ { "hashed_secret": "d9e9019d9eb455a3d72a3bc252c26927bb148a10", "is_secret": false, "is_verified": false, - "line_number": 132, + "line_number": 118, "type": "Secret Keyword", "verified_result": null }, @@ -90,23 +78,7 @@ "hashed_secret": "32e8612d8ca77c7ea8374aa7918db8e5df9252ed", "is_secret": false, "is_verified": false, - "line_number": 174, - "type": "Secret Keyword", - "verified_result": null - }, - { - "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", - "is_secret": false, - "is_verified": false, - "line_number": 228, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", - "is_secret": false, - "is_verified": false, - "line_number": 228, + "line_number": 162, "type": "Secret Keyword", "verified_result": null } @@ -123,34 +95,18 @@ ], "ibm_watson/discovery_v1.py": [ { - "hashed_secret": "3442496b96dd01591a8cd44b1eec1368ab728aba", - "is_secret": false, - "is_verified": false, - "line_number": 4723, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "b16c7ac6faff07d7e255da685e52bd66d3bf1575", - "is_secret": false, - "is_verified": false, - "line_number": 4781, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", "is_secret": false, "is_verified": false, - "line_number": 4828, - "type": "DB2 Credentials", + "line_number": 5683, + "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", + "hashed_secret": "fdee05598fdd57ff8e9ae29e92c25a04f2c52fa6", "is_secret": false, "is_verified": false, - "line_number": 4967, + "line_number": 5684, "type": "Secret Keyword", "verified_result": null } @@ -171,32 +127,52 @@ "is_secret": false, "is_verified": false, "line_number": 168, - "type": "DB2 Credentials", + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_assistant_v1.py": [ + { + "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", + "is_secret": false, + "is_verified": false, + "line_number": 7986, + "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "b60d121b438a380c343d5ec3c2037564b82ffef3", + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 168, + "line_number": 11590, "type": "Secret Keyword", "verified_result": null } ], - "test/unit/test_discovery_v1.py": [ + "test/unit/test_assistant_v2.py": [ { - "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 6789, - "type": "DB2 Credentials", + "line_number": 1393, + "type": "Secret Keyword", "verified_result": null }, + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 8441, + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_discovery_v1.py": [ { "hashed_secret": "8318df9ecda039deac9868adf1944a29a95c7114", "is_secret": false, "is_verified": false, - "line_number": 6789, + "line_number": 7053, "type": "Secret Keyword", "verified_result": null }, @@ -204,7 +180,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 7961, + "line_number": 8245, "type": "Secret Keyword", "verified_result": null }, @@ -212,23 +188,33 @@ "hashed_secret": "b8e758b5ad59a72f146fcf065239d5c7b695a39a", "is_secret": false, "is_verified": false, - "line_number": 10241, + "line_number": 10479, "type": "Hex High Entropy String", "verified_result": null } ], + "test/unit/test_discovery_v2.py": [ + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 6882, + "type": "Secret Keyword", + "verified_result": null + } + ], "test/unit/test_speech_to_text_v1.py": [ { "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 418, + "line_number": 432, "type": "Secret Keyword", "verified_result": null } ] }, - "version": "0.13.1+ibm.26.dss", + "version": "0.13.1+ibm.56.dss", "word_list": { "file": null, "hash": null diff --git a/CHANGELOG.md b/CHANGELOG.md index cbb2fead0..d3d27edf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,182 @@ +# [9.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v8.1.0...v9.0.0) (2024-12-04) + + +### Features + +* **discov2:** add functions for new batches api ([043eed4](https://github.com/watson-developer-cloud/python-sdk/commit/043eed48f1808ad3c0c325be18e2bd7ecc339c14)) +* **stt:** add new speech models ([4948b8f](https://github.com/watson-developer-cloud/python-sdk/commit/4948b8f210e5b9cd2d856aa90f2262a8bdf64444)) +* **stt:** readd interimResults and lowLatency wss params ([ffc67b8](https://github.com/watson-developer-cloud/python-sdk/commit/ffc67b8a0b213530cda23157848d79b5fea4b146)) +* **WxA:** add new functions and update required params ([3fe6243](https://github.com/watson-developer-cloud/python-sdk/commit/3fe62430c57e660b0903b0988fa3c53c489012d3)) +* Add support for message streaming and new APIs + +New functions: create_providers, list_providers, update_providers, create_release_export, download_release_export, create_release_import, get_release_import_status, message_stream, message_stream_stateless, parse_sse_stream_data, list_batches, pull_batches, push_batches + +### BREAKING CHANGES + +* **WxA:** `environmentId` now required for `message` and `messageStateless` functions +* **lt:** LanguageTranslator functionality has been removed +* **discov1:** DiscoveryV1 functionality has been removed +* **nlu:** training_data_content_type default changed to None + +# [8.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v8.0.0...v8.1.0) (2024-05-17) + + +### Features + +* **stt:** remove interim_results and low_latency wss params ([035b29d](https://github.com/watson-developer-cloud/python-sdk/commit/035b29d82c35789f782359a9842e50956665b96c)) +* **stt:** add speech_begin_event param to recognize func ([d026ab2](https://github.com/watson-developer-cloud/python-sdk/commit/d026ab2a7ffa950a7ba6b655357f2523cda337ef)) +* **disco-v2:** add ocr_enabled parameter ([460593f](https://github.com/watson-developer-cloud/python-sdk/commit/460593f48fe7e32ea3fc205da05d1dad7318255b)) + +# [8.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v7.0.1...v8.0.0) (2024-02-26) + + +### Features + +* **disco-v2:** class changes ([a109e2e](https://github.com/watson-developer-cloud/python-sdk/commit/a109e2e3f43442fdc0d0c7c09bdf3ccd0682628e)) +* **disco-v2:** new params for EnrichmentOptions ([d980178](https://github.com/watson-developer-cloud/python-sdk/commit/d980178de2ffbf9ffd491113a9a5fd1f82ed4557)) +* **nlu:** add support for userMetadata param ([134fa6d](https://github.com/watson-developer-cloud/python-sdk/commit/134fa6d868396875a33806d1e688156ceecd60c5)) +* **stt:** new params smart_formatting_version, force, mapping_only ([0fa495c](https://github.com/watson-developer-cloud/python-sdk/commit/0fa495cf24438d7a937904735f1dd23e33f3cd31)) +* **wa-v2:** new params orchestration and asyncCallout ([69523c5](https://github.com/watson-developer-cloud/python-sdk/commit/69523c5f023717ff911b714e2a58571f19b51b04)) +* **wa-v2:** support for private variables ([6cd5eba](https://github.com/watson-developer-cloud/python-sdk/commit/6cd5ebae52f93ab64f89bb1dea52b3ef4b27f444)) + + +### BREAKING CHANGES + +* **wa-v2:** Renaming and changing of multiple interfaces + +## [7.0.1](https://github.com/watson-developer-cloud/python-sdk/compare/v7.0.0...v7.0.1) (2022-08-07) + + +### Bug Fixes + +* **tts,stt,version:** unpinned websocket-client ([75432a6](https://github.com/watson-developer-cloud/python-sdk/commit/75432a6ab4b737a3a7afd8009e70f68e6f02d312)) + +# [7.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v6.0.1...v7.0.0) (2023-03-17) + + +### Bug Fixes + +* **assistantv2:** use original createSession method signature ([ac82c45](https://github.com/watson-developer-cloud/python-sdk/commit/ac82c45c14ddcd0d608496d1193da09d555b6f15)) +* **nlu:** require training_data_content_type ([d91f007](https://github.com/watson-developer-cloud/python-sdk/commit/d91f007fafd568cc30abf15d54c53935f32197a8)) +* **version:** change version strings for release ([aee877c](https://github.com/watson-developer-cloud/python-sdk/commit/aee877ce8ae50f495f1dacfd7cbd26a117aab594)) + + +### Features + +* **assistant-v1:** update models and add new methods ([fbcebd0](https://github.com/watson-developer-cloud/python-sdk/commit/fbcebd088c205070e9bae22821b2a2e8920a07c5)) +* **assistant-v2:** update models and add new methods ([a1586ec](https://github.com/watson-developer-cloud/python-sdk/commit/a1586ec6750e5130493fa8d08ac01d13a36e3715)) +* **assistantv2:** add several new functions ([d2d6fbf](https://github.com/watson-developer-cloud/python-sdk/commit/d2d6fbfce304bdb197b665e612022d4c4cc6b5bd)) +* **assistantv2:** improved typing ([a84cd6c](https://github.com/watson-developer-cloud/python-sdk/commit/a84cd6c983d913811b7943e579126e6a1c71781f)) +* **discov2:** new aggregation types ([41cb185](https://github.com/watson-developer-cloud/python-sdk/commit/41cb1853267528dcedfd49f42710ff28e6885d37)) +* **discovery-v2:** update models and add several new methods ([972a1ae](https://github.com/watson-developer-cloud/python-sdk/commit/972a1ae6f774a4849ffc6e8fe1a77e04090a7441)) +* **nlu:** add trainingParameters ([c8e056c](https://github.com/watson-developer-cloud/python-sdk/commit/c8e056c8d503656271bde6315b84838771975179)) +* **nlu:** remove all sentimentModel functions ([d6e342f](https://github.com/watson-developer-cloud/python-sdk/commit/d6e342f7fc34fdc82cf6042f585d3110bd38abfd)) +* **nlu:** remove beta model param from Sentiment ([1469190](https://github.com/watson-developer-cloud/python-sdk/commit/1469190590cdaff60156816964b88822fef5e933)) +* **release:** trigger release ([c08a117](https://github.com/watson-developer-cloud/python-sdk/commit/c08a117294c9d2a52b8493c1cec55b8826621abc)) +* **stt, tts:** add more models ([8b9f6a8](https://github.com/watson-developer-cloud/python-sdk/commit/8b9f6a897e2e9d3fdb43aa0ce1adc8b2a581f4e9)) +* **stt:** add and remove models ([14fd5f2](https://github.com/watson-developer-cloud/python-sdk/commit/14fd5f22096ac83e99a5c6092fbead23cf309f45)) +* **stt:** update parameters ([e40c06c](https://github.com/watson-developer-cloud/python-sdk/commit/e40c06c52ec00168d9a5f7f0e174c8a1fef65d21)) +* **tts:** add parameters ([b300c55](https://github.com/watson-developer-cloud/python-sdk/commit/b300c5527794eee5ab692a51eb858164dddfef93)) +* **tts:** add params and add model constants ([546796d](https://github.com/watson-developer-cloud/python-sdk/commit/546796d3db37f4af52a7745a62f24e769094b567)) +* **wss:** add and remove websocket params ([1b5f171](https://github.com/watson-developer-cloud/python-sdk/commit/1b5f1715ad92573bc8fce2e44ba8b6e5efda3780)) + + +### BREAKING CHANGES + +* **release:** trigger release +* **assistantv2:** createSession param removed +* **assistantv2:** removing and changing of classes +* **discov2:** confidence property removed +* **discov2:** smartDocumentUnderstanding param removed +* **discov2:** QueryAggregation structure changed +* **nlu:** remove all sentimentModel functions and models + +# [6.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v6.0.1...v6.1.0) (2022-08-10) + + +### Bug Fixes + +* **assistantv2:** use original createSession method signature ([ac82c45](https://github.com/watson-developer-cloud/python-sdk/commit/ac82c45c14ddcd0d608496d1193da09d555b6f15)) + + +### Features + +* **assistant-v1:** update models and add new methods ([fbcebd0](https://github.com/watson-developer-cloud/python-sdk/commit/fbcebd088c205070e9bae22821b2a2e8920a07c5)) +* **assistant-v2:** update models and add new methods ([a1586ec](https://github.com/watson-developer-cloud/python-sdk/commit/a1586ec6750e5130493fa8d08ac01d13a36e3715)) +* **discovery-v2:** update models and add several new methods ([972a1ae](https://github.com/watson-developer-cloud/python-sdk/commit/972a1ae6f774a4849ffc6e8fe1a77e04090a7441)) +* **nlu:** add trainingParameters ([c8e056c](https://github.com/watson-developer-cloud/python-sdk/commit/c8e056c8d503656271bde6315b84838771975179)) +* **stt:** update parameters ([e40c06c](https://github.com/watson-developer-cloud/python-sdk/commit/e40c06c52ec00168d9a5f7f0e174c8a1fef65d21)) +* **tts:** add parameters ([b300c55](https://github.com/watson-developer-cloud/python-sdk/commit/b300c5527794eee5ab692a51eb858164dddfef93)) +* **wss:** add and remove websocket params ([1b5f171](https://github.com/watson-developer-cloud/python-sdk/commit/1b5f1715ad92573bc8fce2e44ba8b6e5efda3780)) + +# [6.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.3.0...v6.0.0) (2022-03-21) + + +### Bug Fixes + +* **ws:** remove websocket debug code ([21399b7](https://github.com/watson-developer-cloud/python-sdk/commit/21399b769608a25f00fe4790b850ced77a8fc748)) + + +* Major release 2022 (#816) ([97de097](https://github.com/watson-developer-cloud/python-sdk/commit/97de097b8c86622ab2f30f5386bb74321d28addf)), closes [#816](https://github.com/watson-developer-cloud/python-sdk/issues/816) + + +### BREAKING CHANGES + +* OutputData: required text property removed, RuntimeEntity: optional metadata property removed +RuntimeResponseGeneric: Three new response types added +Workspace: workspaceID changed form required to optional + +* feat(assistantv2): add three new response types, rename model, remove properties +* RuntimeEntity: optional metadata property removed, MessageOutputDebug: nodesVisited type DialogNodesVisited changed to DialogNodeVisited. +MessageContext: integrations property added +MessageContextGlobalSystem: skipUserInput property added +MessageContextStateless: integrations property added +MessageInput: attachments property added +MessageInputStateless: attachments property added +RuntimeResponseGeneric: Three new response types added + +* refactor(cc): remove compare and comply ヾ(・‿・) + +* refactor(nlc): remove nlc ヾ(・‿・) + +* feat(nlu): remove MetadataOptions model + +* refactor(lt): comment change and test updates + +* refactor(pi): remove personality insights ヾ(・‿・) + +* feat(stt/tts): add new property and comment changes + +* refactor(ta/visrec): remove ta and visrec ヾ(・‿・) + +* refactor(all): remove remaining traces of removed services + +* feat(assistantv1): add new dialogNode models and additional properties for Workspace + +* feat(discov1): update QueryAggregation subclasses +* QueryAggregation: QueryAggregation subclasses changed. +DocumentStatus: documentID, status, and statusDescription are now optional + +* feat(stt): change grammarFile property type +* addGrammar parameter grammarFile changed from String to Data type + +SupportedFeatures: customAcousticModel property added + +* chore: copyright changes + +* build(secrets): upload detect-secrets baseline + +* docs(readme): add deprecation note and remove old references + +* ci(version): remove python 3.6 support and add 3.9 support + +## [5.3.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.3.0...v5.3.1) (2022-01-26) + + +### Bug Fixes + +* **ws:** remove websocket debug code ([21399b7](https://github.com/watson-developer-cloud/python-sdk/commit/21399b769608a25f00fe4790b850ced77a8fc748)) + # [5.3.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.3...v5.3.0) (2021-09-14) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85c67d0af..3fbf576f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ If you want to contribute to the repository, here's a quick guide: - Only use spaces for indentation. - Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. - Check for unnecessary whitespace with `git diff --check` before committing. - - Make sure your code supports Python 3.7, 3.8, 3.9. You can use `pyenv` and `tox` for this + - Make sure your code supports Python 3.9, 3.10, 3.11. You can use `pyenv` and `tox` for this 1. Make the test pass 1. Commit your changes @@ -49,6 +49,9 @@ You probably want to set up a [virtualenv]. py.test test ``` +## Bug Bounty Hunters Notice +API keys found from commit bec3ae23b53782370851e28cbda5033a596b58b5 have already been revoked and will not be accepted for bug bounties. + ## Additional Resources - [General GitHub documentation](https://help.github.com/) diff --git a/MIGRATION-V4.md b/MIGRATION-V4.md deleted file mode 100644 index 52fc40182..000000000 --- a/MIGRATION-V4.md +++ /dev/null @@ -1,215 +0,0 @@ -Here are simple steps to move from `v3.0.0` to `v4.0.0`. Note that `v4.0,0` supports only python `3.5` and above - -## AUTHENTICATION MECHANISM -The constructor no longer accepts individual credentials like `iam_apikey`, etc. We initialize authenticators from the [core](https://github.com/IBM/python-sdk-core). The core supports various authentication mechanisms, choose the one appropriate to your instance and use case. - -For example, to pass a IAM apikey: -#### Before -```python -from ibm_watson import MyService - -service = MyService( - iam_apikey='{apikey}', - url='{url}' -) -``` - -#### After(V4.0) -```python -from ibm_watson import MyService -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('{apikey}') -service = MyService( - authenticator=authenticator -) -service.set_service_url('{url}') -``` - -There are 5 authentication variants supplied in the SDK (shown below), and it's possible now to create your own authentication implementation if you need something specific by implementing the Authenticator implementation. - -#### BasicAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -authenticator = BasicAuthenticator(, ) -service = MyService(authenticator=authenticator) -``` - -#### BearerTokenAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator - -authenticator = BearerTokenAuthenticator() -service = MyService(authenticator=authenticator) - -# can set bearer token -service.get_authenticator().set_bearer_token('xxx'); -``` - -#### CloudPakForDataAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator - -authenticator = CloudPakForDataAuthenticator( - 'my_username', - 'my_password', - 'https://my-cp4d-url', - disable_ssl_verification=True) -service = MyService(authenticator=authenticator) -``` - -#### IAMAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('my_apikey') -service = MyService(authenticator=authenticator) -``` - -#### NoAuthAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator - -authenticator = NoAuthAuthenticator() -service = MyService(authenticator=authenticator) -``` - -#### Creating an Authenticator from Environmental Configuration -```python -from ibm_cloud_sdk_core import get_authenticator_from_environment - -authenticator = get_authenticator_from_environment('Assistant') -service = MyService(authenticator=authenticator) -``` - -## SETTING THE SERVICE URL -We can set the service url using `set_service_url()` or from external configurations. - -#### Before -```python -service = MyService( - iam_apikey='{apikey}', - url='{url}' # <= here -) -``` - -#### After(V4.0) -```python -service = MyService( - authenticator=authenticator, -) -service.set_service_url('{url}') -``` - -OR, pass from external configurations like environment variable -```bash -export MY_SERVICE_URL="" -``` - -## METHOD OPTIONAL PARAM -The method params which are optional would need to be specified by name rather than position. For example - -#### Before -The list_workspaces with page_limit as 10 was: - -```python -assistant_service.list_workspaces(10) -``` - -#### After(V4.0) -We need to specify the optional param name: - -```python -assistant_service.list_workspaces(page_limit=10) -``` - -## DISABLING SSL VERIFICATION -#### Before -```python -service.disable_ssl_verification(True) -``` - -#### After(v4.0) -```python -service.set_disable_ssl_verification(True) -``` - -## SUPPORT FOR CONSTANTS -Constants for methods and models are shown in the form of Enums - -## SUPPORT FOR PYTHON 2.7 and 3.4 AND BELOW DROPPED -The SDK no longer supports Pyhton versions 2.7 and <=3.4. - -## SERVICE CHANGES -#### AssistantV1 -* `include_count` is no longer a parameter of the list_workspaces() method -* `include_count` is no longer a parameter of the list_intents() method -* `include_count` is no longer a parameter of the list_examples() method -* `include_count` is no longer a parameter of the list_counterexamples() method -* `include_count` is no longer a parameter of the list_entities() method -* `include_count` is no longer a parameter of the list_values() method -* `include_count` is no longer a parameter of the list_synonyms() method -* `include_count` is no longer a parameter of the list_dialog_nodes() method -* `value_type` was renamed to `type` in the create_value() method -* `new_value_type` was renamed to `new_type` in the update_value() method -* `node_type` was renamed to `type` in the create_dialog_node() method -* `new_node_type` was renamed to `new_type` in the update_dialog_node() method -* `value_type` was renamed to `type` in the CreateValue model -* `node_type` was renamed to `type` in the DialogNode model -* `action_type` was renamed to `type` in the DialogNodeAction model -* `query_type` property was added to the DialogNodeOutputGeneric model -* `query` property was added to the DialogNodeOutputGeneric model -* `filter` property was added to the DialogNodeOutputGeneric model -* `discovery_version` property was added to the DialogNodeOutputGeneric model -* LogMessage model no longer has `_additionalProperties` -* `DialogRuntimeResponseGeneric` was renamed to `RuntimeResponseGeneric` -* RuntimeEntity model no longer has `_additionalProperties` -* RuntimeIntent model no longer has `_additionalProperties` -* `value_type` was renamed to `type` in the Value model - -#### AssistantV2 -* `action_type` was renamed to `type` in the DialogNodeAction model -* DialogRuntimeResponseGeneric was renamed to RuntimeResponseGeneric - -#### Compare and Comply -* `convert_to_html()` method does not require a filename parameter - -#### DiscoveryV1 -* `return_fields` was renamed to `return_` in the query() method -* `logging_opt_out` was renamed to `x_watson_logging_opt_out` in the query() method -* `spelling_suggestions` was added to the query() method -* `collection_ids` is no longer a parameter of the query() method -* `return_fields` was renamed to `return_` in the QueryNotices() method -* `logging_opt_out` was renamed to `x_watson_logging_opt_out` in the federated_query() method -* `collection_ids` is now required in the federated_query() method -* `collection_ids` changed position in the federated_query() method -* `return_fields` was renamed to `return_` in the federated_query() method -* `return_fields` was renamed to `return_` in the federated_query_notices() method -* `enrichment_name` was renamed to `enrichment` in the Enrichment model -* `field_type` was renamed to `type` in the Field model -* `field_name` was renamed to `field` in the Field model -* test_configuration_in_environment() method was removed -* query_entities() method was removed -* query_relations() method was removed - -#### Language Translator V3 -* `default_models` was renamed to `default` in the list_models() method -* `translation_output` was renamed to `translation` in the Translation model - -#### Natural Language Classifier V1 -* `metadata` was renamed to `training_metadata` in the `create_classifier()` method - -#### Speech to Text V1 -* `final_results` was renamed to `final` in the SpeakerLabelsResult model -* `final_results` was renamed to `final` in the SpeechRecognitionResult model - -#### Visual Recognition V3 -* `detect_faces()` method was removed -* `class_name` was renamed to `class_` in the ClassResult model -* `class_name` was renamed to `class_` in the ModelClass model - -#### Visual Recognition V4 -* New Service! - - diff --git a/MIGRATION-V5.md b/MIGRATION-V5.md deleted file mode 100644 index 88b36428f..000000000 --- a/MIGRATION-V5.md +++ /dev/null @@ -1,175 +0,0 @@ -## Python SDK V5 Migration guide - -### Service changes - -#### Assistant v1 - -* `include_count` is now a parameter of the `list_workspaces()` method -* `include_count` is now a parameter of the `list_intents()` method -* `include_count` is now a parameter of the `list_examples()` method -* `include_count` is now a parameter of the `list_counterexamples()` method -* `include_count` is now a parameter of the `list_entities()` method -* `include_count` is now a parameter of the `list_values()` method -* `include_count` is now a parameter of the `list_synonyms()` method -* `include_count` is now a parameter of the `list_dialogNodes()` method -* `context` type was changed from `dict` to `DialogNodeContext` in the `create_dialog_node()` method -* `new_context` type was changed from `dict` to `DialogNodeContext` in the `update_dialog_node()` method -* `bulk_classify()` method was addded - -##### Models Added - -`BulkClassifyOutput`, -`BulkClassifyResponse`, -`BulkClassifyUtterance`, -`DialogNodeContext`, -`DialogNodeOutputConnectToAgentTransferInfo`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeImage`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeOption`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypePause`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeText`, -`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, -`RuntimeResponseGenericRuntimeResponseTypeImage`, -`RuntimeResponseGenericRuntimeResponseTypeOption`, -`RuntimeResponseGenericRuntimeResponseTypePause`, -`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, -`RuntimeResponseGenericRuntimeResponseTypeText` - -##### Models Removed - -`DialogSuggestionOutput`, -`DialogSuggestionResponseGeneric` - -##### Model Properties Changed - -`DialogNode` -* `context` property type changed from `Dictionary` to `DialogNodeContext` - -`DialogNodeOutput` -* Added `Integrations` property with getter and setter - -`DialogNodeOutputGeneric`, `RuntimeResponseGeneric` -* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties - -`DialogSuggestion` -* `output` property type changed from `DialogSuggestionOutput` to `Dictionary` - -#### Assistant v2 - -* `bulk_classify()` method was addded - -##### Models Added - -`BulkClassifyOutput`, -`BulkClassifyResponse`, -`BulkClassifyUtterance`, -`DialogNodeOutputConnectToAgentTransferInfo`, -`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, -`RuntimeResponseGenericRuntimeResponseTypeImage`, -`RuntimeResponseGenericRuntimeResponseTypeOption`, -`RuntimeResponseGenericRuntimeResponseTypePause`, -`RuntimeResponseGenericRuntimeResponseTypeSearch`, -`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, -`RuntimeResponseGenericRuntimeResponseTypeText` - -##### Model Properties Changed - -`MessageContext`, `MessageContextStateless` -* `Skills` property type changed from `MessageContextSkills` to `Dictionary` - -`MessageContextSkill` -* `System` property type changed from `Dictionary` to `MessageContextSkillSystem` - -`RuntimeResponseGeneric` -* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties - -#### Compare Comply v1 - -* `before` and `after` parameters were removed from `list_feedback` method - -##### Model Properties Changed - -`Category`, `TypeLabel` -* Added `modification` property - -`OriginalLabelsOut`, `UpdatedLabelsOut` -* Removed `modification` property - -#### Discovery v1 - -No changes - -#### Discovery v2 - -##### Models Added - -`QueryResponsePassage` - -##### Models Removed - -`QueryNoticesResult` - -##### Model Properties Changed - -`QueryResponse` -* Added `Passages` property - -#### Language Translator v3 - -No changes - -#### Natural Language Classifier v1 - -No changes - -#### Natural Language Understanding v1 - -No changes - -#### Personality Insights - -No changes - -#### Speech To Text v1 - -No changes - -#### Text To Speech v1 - -* Renamed `CreateVoiceModel()` method to `CreateCustomModel()` - -* Renamed `ListVoiceModels()` method to `ListCustomModels()` - -* Renamed `UpdateVoiceModel()` method to `UpdateCustomModel()` - -* Renamed `GetVoiceModel()` method to `GetCustomModel()` - -* Renamed `DeleteVoiceModel()` method to `GetCustomModel()` - -##### Models Added - -`CustomModel`, -`CustomModels` - -##### Models Removed - -`VoiceModel`, -`VoiceModels` - -##### Model Properties Changed - -`Voice` -* Change return type of `customization` from `VoiceModel` to `CustomModel` - -#### Tone Analyzer v3 - -No changes - -#### Visual Recognition v3 - -No changes - -#### Visual Recognition v4 - -* Changed `start_time` and `end_time` parameter types from `string` to `date` in `get_training_usage()` method \ No newline at end of file diff --git a/MIGRATION-V7.md b/MIGRATION-V7.md new file mode 100644 index 000000000..765ac9ad7 --- /dev/null +++ b/MIGRATION-V7.md @@ -0,0 +1,55 @@ +# Upgrading to ibm-watson@8.0 + [Breaking Changes](#breaking-changes) + - [Breaking changes by service](#breaking-changes-by-service) + +- [New Features by Service](#new-features-by-service) + +### Breaking changes by service + +#### Assistant v2 +- Parameter `createSession` removed from `createSession` function +- Class `Environment` property `language` removed +- Class `EnvironmentReleaseReference` renamed to `BaseEnvironmentReleaseReference` +- Class `EnvironmentOrchestration` renamed to `BaseEnvironmentOrchestration` +- Class `SkillReference` renamed to `EnvironmentSkill` + +#### Discovery v2 +- Parameter `smartDocumentUnderstanding` removed from `createCollection` function +- Class `QueryResponsePassage` and `QueryResultPassage` property `confidence` removed +- Class `DocumentClassifierEnrichment` property `enrichmentId` is no longer an optional +- QueryAggregation classes restructured + +#### Natural Language Understanding +- All `sentiment_model` functions removed +- `create_classifications_model`, `update_classifications_model`, `create_categories_model`, and `update_categories_model` now require `training_data_content_type` + +#### Speech to Text +- `AR_AR_BROADBANDMODEL` model removed in favor of `AR_MS_BROADBANDMODEL` model + +### New Features by Service + +#### Assistant v2 +- `create_assistant` function +- `list_assistants` function +- `delete_assistant` function +- `update_environment` function +- `create_release` function +- `delete_release` function +- `get_skill` function +- `update_skill` function +- `export_skills` function +- `import_skills` function +- `import_skills_status` function +- Improved typing for `message` function call +See details of these functions on IBM's documentation site [here](https://cloud.ibm.com/apidocs/assistant-v2?code=python) + +#### Discovery v2 +- Aggregation types `QueryTopicAggregation` and `QueryTrendAggregation` added + +#### Speech to Text +- added `FR_CA_MULTIMEDIA`, `JA_JP_TELEPHONY`, `NL_NL_MULTIMEDIA`, `SV_SE_TELEPHONY` models + +#### Text to Speech +- added `EN_AU_HEIDIEXPRESSIVE`, `EN_AU_JACKEXPRESSIVE`, `EN_US_ALLISONEXPRESSIVE`, `EN_US_EMMAEXPRESSIVE`, `EN_US_LISAEXPRESSIVE`, `EN_US_MICHAELEXPRESSIVE`, `KO_KR_JINV3VOICE` +- Parameters `rate_percentage` and `pitch_percentage` added to `synthesize` function +See details of these new parameters on IBM's documentation site [here](https://cloud.ibm.com/apidocs/text-to-speech?code=python#synthesize) diff --git a/README.md b/README.md index 8fb71fc37..e99a46d4a 100755 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ [![Build and Test](https://github.com/watson-developer-cloud/python-sdk/workflows/Build%20and%20Test/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A"Build+and+Test") [![Deploy and Publish](https://github.com/watson-developer-cloud/python-sdk/workflows/Deploy%20and%20Publish/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A%22Deploy+and+Publish%22) -[![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net) [![Latest Stable Version](https://img.shields.io/pypi/v/ibm-watson.svg)](https://pypi.python.org/pypi/ibm-watson) [![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk)](https://cla-assistant.io/watson-developer-cloud/python-sdk) @@ -12,24 +11,6 @@ Python client library to quickly get started with the various [Watson APIs][wdc] services. -## Announcements - -### Tone Analyzer Deprecation - -As of this major release, 6.0.0, the Tone Analyzer api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to Tone Analyzer until its final deprecation, you will have to use a previous version. - -On 24 February 2022, IBM announced the deprecation of the Tone Analyzer service. The service will no longer be available as of 24 February 2023. As of 24 February 2022, you will not be able to create new instances. Existing instances will be supported until 24 February 2023. - -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud. With Natural Language Understanding, tone analysis is done by using a pre-built classifications model, which provides an easy way to detect language tones in written text. For more information, see [Migrating from Watson Tone Analyzer Customer Engagement endpoint to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics). - -### Natural Language Classifier Deprecation - -As of this major release, 6.0.0, the NLC api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to NLC until its final deprecation, you will have to use a previous version. - -On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. - -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). - ## Before you begin - You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above @@ -114,7 +95,7 @@ The file downloaded will be called `ibm-credentials.env`. This is the name the S As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: ```python -discovery = DiscoveryV1(version='2019-04-30') +assistant = AssistantV2(version='2024-08-25') ``` And that's it! @@ -141,7 +122,7 @@ export ASSISTANT_AUTH_TYPE="iam" The credentials will be loaded from the environment automatically ```python -assistant = AssistantV1(version='2018-08-01') +assistant = AssistantV2(version='2024-08-25') ``` #### Manually @@ -161,15 +142,15 @@ You supply either an IAM service **API key** or a **bearer token**: #### Supplying the API key ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # In the constructor, letting the SDK manage the token authenticator = IAMAuthenticator('apikey', url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token -discovery = DiscoveryV1(version='2019-04-30', +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) -discovery.set_service_url('') +assistant.set_service_url('') ``` #### Generating bearer tokens using API key @@ -185,109 +166,72 @@ token = iam_token_manager.get_token() ##### Supplying the bearer token ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator # in the constructor, assuming control of managing the token authenticator = BearerTokenAuthenticator('your bearer token') -discovery = DiscoveryV1(version='2019-04-30', +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) -discovery.set_service_url('') +assistant.set_service_url('') ``` -### Username and password +#### Username and password ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator authenticator = BasicAuthenticator('username', 'password') -discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) -discovery.set_service_url('') +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) +assistant.set_service_url('') ``` -### No Authentication +#### No Authentication ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator authenticator = NoAuthAuthenticator() -discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) -discovery.set_service_url('') +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) +assistant.set_service_url('') ``` -## Python version - -Tested on Python 3.5, 3.6, and 3.7. +### MCSP -## Questions - -If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). - -## Changes for v1.0 - -Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v2.0 - -`DetailedResponse` which contains the result, headers and HTTP status code is now the default response for all methods. +To use the SDK through a third party cloud provider (such as AWS), use the `MCSPAuthenticator`. This will require the base endpoint URL for the MCSP token service (e.g. https://iam.platform.saas.ibm.com) and an apikey. ```python -from ibm_watson import AssistantV1 - -assistant = AssistantV1( - username='xxx', - password='yyy', - url='', - version='2018-07-10') +from ibm_watson import AssistantV2 +from ibm_cloud_sdk_core.authenticators import MCSPAuthenticator -response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}) -print(response.get_result()) -print(response.get_headers()) -print(response.get_status_code()) +# In the constructor, letting the SDK manage the token +authenticator = MCSPAuthenticator('apikey', 'token_service_endpoint') +assistant = AssistantV2(version='2023-06-15', + authenticator=authenticator) +assistant.set_service_url('') ``` -See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v3.0 - -The SDK is generated using OpenAPI Specification(OAS3). Changes are basic reordering of parameters in function calls. - -The package is renamed to ibm_watson. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v4.0 - -Authenticator variable indicates the type of authentication to be used. - -```python -from ibm_watson import AssistantV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', - authenticator=authenticator) -assistant.set_service_url('') -``` +## Python version -For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md) +Tested on Python 3.9, 3.10, and 3.11. -## Migration +## Questions -To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). +If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). -## Configuring the http client (Supported from v1.1.0) +## Configuring the http client -To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance +To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://requests.readthedocs.io/en/latest/api/) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -304,12 +248,12 @@ To use the SDK with any proxies you may have they can be set as shown below. For See this example configuration: ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -324,12 +268,12 @@ assistant.set_http_config({'proxies': { To send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent. ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -378,14 +322,14 @@ For example, to send a header called `Custom-Header` to a call in Watson Assista the headers parameter as: ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` @@ -395,14 +339,14 @@ response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}). If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() @@ -428,9 +372,9 @@ Every SDK call returns a response with a transaction ID in the `X-Global-Transac ### Suceess ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 -service = AssistantV1(authenticator={my_authenticator}) +service = AssistantV2(authenticator={my_authenticator}) response_headers = service.my_service_call().get_headers() print(response_headers.get('X-Global-Transaction-Id')) ``` @@ -438,10 +382,10 @@ print(response_headers.get('X-Global-Transaction-Id')) ### Failure ```python -from ibm_watson import AssistantV1, ApiException +from ibm_watson import AssistantV2, ApiException try: - service = AssistantV1(authenticator={my_authenticator}) + service = AssistantV2(authenticator={my_authenticator}) service.my_service_call() except ApiException as e: print(e.global_transaction_id) @@ -452,9 +396,9 @@ except ApiException as e: However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace `` in the following example with a unique transaction ID. ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 -service = AssistantV1(authenticator={my_authenticator}) +service = AssistantV2(authenticator={my_authenticator}) service.my_service_call(headers={'X-Global-Transaction-Id': ''}) ``` @@ -492,7 +436,7 @@ If your service instance is of CP4D, below are two ways of initializing the assi The SDK will manage the token for the user ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator authenticator = CloudPakForDataAuthenticator( @@ -501,7 +445,7 @@ authenticator = CloudPakForDataAuthenticator( '', # should be of the form https://{icp_cluster_host}{instance-id}/api disable_ssl_verification=True) # Disable ssl verification for authenticator -assistant = AssistantV1( +assistant = AssistantV2( version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api @@ -511,11 +455,11 @@ assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DIS ### 2) Supplying the access token ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator authenticator = BearerTokenAuthenticator('your managed access token') -assistant = AssistantV1(version='', +assistant = AssistantV2(version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED @@ -558,33 +502,13 @@ HTTPConnection.debuglevel = 1 - `python_dateutil` >= 2.5.3 - [responses] for testing - Following for web sockets support in speech to text - - `websocket-client` 0.48.0 -- `ibm_cloud_sdk_core` == 1.0.0 + - `websocket-client` 1.1.0 +- `ibm_cloud_sdk_core` >= 3.16.2 ## Contributing See [CONTRIBUTING.md][contributing]. -## Featured Projects - -Here are some projects that have been using the SDK: - -- [NLC ICD-10 Classifier](https://github.com/IBM/nlc-icd10-classifier) -- [Cognitive Moderator Service](https://github.com/IBM/cognitive-moderator-service) - -We'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it. - ## License This library is licensed under the [Apache 2.0 license][license]. - -[wdc]: http://www.ibm.com/watson/developercloud/ -[ibm_cloud]: https://cloud.ibm.com/ -[watson-dashboard]: https://cloud.ibm.com/catalog?category=ai -[responses]: https://github.com/getsentry/responses -[requests]: http://docs.python-requests.org/en/latest/ -[examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples -[contributing]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md -[license]: http://www.apache.org/licenses/LICENSE-2.0 -[vcap_services]: https://cloud.ibm.com/docs/watson?topic=watson-vcapServices -[ibm-cloud-onboarding]: https://cloud.ibm.com/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Python diff --git a/examples/discovery_v1.py b/examples/discovery_v1.py deleted file mode 100644 index 4f32acf22..000000000 --- a/examples/discovery_v1.py +++ /dev/null @@ -1,65 +0,0 @@ -import json -from ibm_watson import DiscoveryV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -discovery = DiscoveryV1( - version='2018-08-01', - authenticator=authenticator) -discovery.set_service_url('https://api.us-south.discovery.watson.cloud.ibm.com') - -environments = discovery.list_environments().get_result() -print(json.dumps(environments, indent=2)) - -news_environment_id = 'system' -print(json.dumps(news_environment_id, indent=2)) - -collections = discovery.list_collections(news_environment_id).get_result() -news_collections = [x for x in collections['collections']] -print(json.dumps(collections, indent=2)) - -configurations = discovery.list_configurations( - environment_id=news_environment_id).get_result() -print(json.dumps(configurations, indent=2)) - -query_results = discovery.query( - news_environment_id, - news_collections[0]['collection_id'], - filter='extracted_metadata.sha1::f5*', - return_fields='extracted_metadata.sha1').get_result() -print(json.dumps(query_results, indent=2)) - -# new_environment = discovery.create_environment(name="new env", description="bogus env").get_result() -# print(new_environment) - -# environment = discovery.get_environment(environment_id=new_environment['environment_id']).get_result() -# if environment['status'] == 'active': -# writable_environment_id = new_environment['environment_id'] -# new_collection = discovery.create_collection(environment_id=writable_environment_id, -# name='Example Collection', -# description="just a test").get_result() - -# print(new_collection) - -# collections = discovery.list_collections(environment_id=writable_environment_id).get_result() -# print(collections) - -# res = discovery.delete_collection(environment_id='', -# collection_id=new_collection['collection_id']).get_result() -# print(res) - -# collections = discovery.list_collections(environment_id=writable_environment_id).get_result() -# print(collections) - -# with open(os.path.join(os.getcwd(), '..','resources', 'simple.html')) as fileinfo: -# res = discovery.add_document(environment_id=writable_environment_id, -# collection_id=collections['collections'][0]['collection_id'], -# file=fileinfo).get_result() -# print(res) - -# res = discovery.get_collection(environment_id=writable_environment_id, -# collection_id=collections['collections'][0]['collection_id']).get_result() -# print(res['document_counts']) - -#res = discovery.delete_environment(environment_id=writable_environment_id).get_result() -#print(res) diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py deleted file mode 100644 index da7aecf8f..000000000 --- a/examples/language_translator_v3.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -import json -from ibm_watson import LanguageTranslatorV3 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -language_translator = LanguageTranslatorV3( - version='2018-05-01', - authenticator=authenticator) -language_translator.set_service_url('https://api.us-south.language-translator.watson.cloud.ibm.com') - -## Translate -translation = language_translator.translate( - text='Hello', model_id='en-es').get_result() -print(json.dumps(translation, indent=2, ensure_ascii=False)) - -# List identifiable languages -# languages = language_translator.list_identifiable_languages().get_result() -# print(json.dumps(languages, indent=2)) - -# # Identify -# language = language_translator.identify( -# 'Language translator translates text from one language to another').get_result() -# print(json.dumps(language, indent=2)) - -# # List models -# models = language_translator.list_models( -# source='en').get_result() -# print(json.dumps(models, indent=2)) - -# # Create model -# with open('glossary.tmx', 'rb') as glossary: -# response = language_translator.create_model( -# base_model_id='en-es', -# name='custom-english-to-spanish', -# forced_glossary=glossary).get_result() -# print(json.dumps(response, indent=2)) - -# # Delete model -# response = language_translator.delete_model(model_id='').get_result() -# print(json.dumps(response, indent=2)) - -# # Get model details -# model = language_translator.get_model(model_id='').get_result() -# print(json.dumps(model, indent=2)) - -#### Document Translation #### -# List Documents -result = language_translator.list_documents().get_result() -print(json.dumps(result, indent=2)) - -# Translate Document -with open('en.pdf', 'rb') as file: - result = language_translator.translate_document( - file=file, - file_content_type='application/pdf', - filename='en.pdf', - model_id='en-fr').get_result() - print(json.dumps(result, indent=2)) - -# Document Status -result = language_translator.get_document_status( - document_id='{document id}').get_result() -print(json.dumps(result, indent=2)) - -# Translated Document -with open('translated.pdf', 'wb') as f: - result = language_translator.get_translated_document( - document_id='{document id}', - accept='application/pdf').get_result() - f.write(result.content) - -# Delete Document -language_translator.delete_document(document_id='{document id}') diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index aed80a796..aaa767998 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -17,10 +17,8 @@ from .assistant_v1 import AssistantV1 from .assistant_v2 import AssistantV2 -from .language_translator_v3 import LanguageTranslatorV3 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 from .text_to_speech_v1 import TextToSpeechV1 -from .discovery_v1 import DiscoveryV1 from .discovery_v2 import DiscoveryV2 from .version import __version__ from .common import get_sdk_headers diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index bbdb45f5b..7528355d4 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -28,7 +28,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import Dict, List, Optional import json import sys @@ -81,18 +81,20 @@ def __init__( # Message ######################### - def message(self, - workspace_id: str, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - alternate_intents: bool = None, - context: 'Context' = None, - output: 'OutputData' = None, - user_id: str = None, - nodes_visited_details: bool = None, - **kwargs) -> DetailedResponse: + def message( + self, + workspace_id: str, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + alternate_intents: Optional[bool] = None, + context: Optional['Context'] = None, + output: Optional['OutputData'] = None, + user_id: Optional[str] = None, + nodes_visited_details: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get response to user input. @@ -138,7 +140,7 @@ def message(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if input is not None: input = convert_model(input) @@ -151,14 +153,16 @@ def message(self, if output is not None: output = convert_model(output) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='message') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='message', + ) headers.update(sdk_headers) params = { 'version': self.version, - 'nodes_visited_details': nodes_visited_details + 'nodes_visited_details': nodes_visited_details, } data = { @@ -168,7 +172,7 @@ def message(self, 'alternate_intents': alternate_intents, 'context': context, 'output': output, - 'user_id': user_id + 'user_id': user_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -176,17 +180,20 @@ def message(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/message'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -195,11 +202,13 @@ def message(self, # Bulk classify ######################### - def bulk_classify(self, - workspace_id: str, - *, - input: List['BulkClassifyUtterance'] = None, - **kwargs) -> DetailedResponse: + def bulk_classify( + self, + workspace_id: str, + *, + input: Optional[List['BulkClassifyUtterance']] = None, + **kwargs, + ) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -216,25 +225,32 @@ def bulk_classify(self, :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if input is not None: input = [convert_model(x) for x in input] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='bulk_classify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='bulk_classify', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input} + data = { + 'input': input, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -242,11 +258,13 @@ def bulk_classify(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/bulk_classify'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -255,14 +273,16 @@ def bulk_classify(self, # Workspaces ######################### - def list_workspaces(self, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_workspaces( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List workspaces. @@ -287,9 +307,11 @@ def list_workspaces(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_workspaces') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_workspaces', + ) headers.update(sdk_headers) params = { @@ -298,42 +320,49 @@ def list_workspaces(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/workspaces' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_workspace(self, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_workspace( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create workspace. Create a workspace based on component objects. You must provide workspace components defining the content of the new workspace. + **Note:** The new workspace data cannot be larger than 1.5 MB. For larger + requests, use the **Create workspace asynchronously** method. :param str name: (optional) The name of the workspace. This string cannot contain carriage return, newline, or tab characters. @@ -376,12 +405,17 @@ def create_workspace(self, if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'name': name, @@ -394,7 +428,7 @@ def create_workspace(self, 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -402,25 +436,30 @@ def create_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/workspaces' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_workspace(self, - workspace_id: str, - *, - export: bool = None, - include_audit: bool = None, - sort: str = None, - **kwargs) -> DetailedResponse: + def get_workspace( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + sort: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get information about a workspace. @@ -442,59 +481,68 @@ def get_workspace(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_workspace', + ) headers.update(sdk_headers) params = { 'version': self.version, 'export': export, 'include_audit': include_audit, - 'sort': sort + 'sort': sort, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_workspace(self, - workspace_id: str, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_workspace( + self, + workspace_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update workspace. Update an existing workspace with new or modified data. You must provide component objects defining the content of the updated workspace. + **Note:** The new workspace data cannot be larger than 1.5 MB. For larger + requests, use the **Update workspace asynchronously** method. :param str workspace_id: Unique identifier of the workspace. :param str name: (optional) The name of the workspace. This string cannot @@ -534,7 +582,7 @@ def update_workspace(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_nodes is not None: dialog_nodes = [convert_model(x) for x in dialog_nodes] @@ -549,15 +597,17 @@ def update_workspace(self, if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace', + ) headers.update(sdk_headers) params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -571,7 +621,7 @@ def update_workspace(self, 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -579,22 +629,29 @@ def update_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: + def delete_workspace( + self, + workspace_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete workspace. @@ -606,28 +663,344 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_workspace', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def create_workspace_async( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create workspace asynchronously. + + Create a workspace asynchronously based on component objects. You must provide + workspace components defining the content of the new workspace. + A successful call to this method only initiates asynchronous creation of the + workspace. The new workspace is not available until processing completes. To check + the status of the asynchronous operation, use the **Get information about a + workspace** method. + + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param List[Webhook] webhooks: (optional) + :param List[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param List[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if dialog_nodes is not None: + dialog_nodes = [convert_model(x) for x in dialog_nodes] + if counterexamples is not None: + counterexamples = [convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = convert_model(system_settings) + if webhooks is not None: + webhooks = [convert_model(x) for x in webhooks] + if intents is not None: + intents = [convert_model(x) for x in intents] + if entities is not None: + entities = [convert_model(x) for x in entities] + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace_async', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, + 'metadata': metadata, + 'learning_opt_out': learning_opt_out, + 'system_settings': system_settings, + 'webhooks': webhooks, + 'intents': intents, + 'entities': entities, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v1/workspaces_async' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def update_workspace_async( + self, + workspace_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + append: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Update workspace asynchronously. + + Update an existing workspace asynchronously with new or modified data. You must + provide component objects defining the content of the updated workspace. + A successful call to this method only initiates an asynchronous update of the + workspace. The updated workspace is not available until processing completes. To + check the status of the asynchronous operation, use the **Get information about a + workspace** method. + + :param str workspace_id: Unique identifier of the workspace. + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param List[Webhook] webhooks: (optional) + :param List[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param List[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param bool append: (optional) Whether the new data is to be appended to + the existing data in the object. If **append**=`false`, elements included + in the new data completely replace the corresponding existing elements, + including all subelements. For example, if the new data for a workspace + includes **entities** and **append**=`false`, all existing entities in the + workspace are discarded and replaced with the new entities. + If **append**=`true`, existing elements are preserved, and the new elements + are added. If any elements in the new data collide with existing elements, + the update request fails. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if not workspace_id: + raise ValueError('workspace_id must be provided') + if dialog_nodes is not None: + dialog_nodes = [convert_model(x) for x in dialog_nodes] + if counterexamples is not None: + counterexamples = [convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = convert_model(system_settings) + if webhooks is not None: + webhooks = [convert_model(x) for x in webhooks] + if intents is not None: + intents = [convert_model(x) for x in intents] + if entities is not None: + entities = [convert_model(x) for x in entities] + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace_async', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'append': append, + } + + data = { + 'name': name, + 'description': description, + 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, + 'metadata': metadata, + 'learning_opt_out': learning_opt_out, + 'system_settings': system_settings, + 'webhooks': webhooks, + 'intents': intents, + 'entities': entities, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces_async/{workspace_id}'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def export_workspace_async( + self, + workspace_id: str, + *, + include_audit: Optional[bool] = None, + sort: Optional[str] = None, + verbose: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Export workspace asynchronously. + + Export the entire workspace asynchronously, including all workspace content. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. After the initial + request is submitted, you can continue to poll by calling the same request again + and checking the value of the **status** property. When processing has completed, + the request returns the exported JSON data. Remember that the usual rate limits + apply. + + :param str workspace_id: Unique identifier of the workspace. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param str sort: (optional) Indicates how the returned workspace data will + be sorted. Specify `sort=stable` to sort all workspace objects by unique + identifier, in ascending alphabetical order. + :param bool verbose: (optional) Whether the response should include the + `counts` property, which indicates how many of each component (such as + intents and entities) the workspace contains. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if not workspace_id: + raise ValueError('workspace_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='export_workspace_async', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + 'sort': sort, + 'verbose': verbose, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces_async/{workspace_id}/export'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -636,16 +1009,18 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: # Intents ######################### - def list_intents(self, - workspace_id: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_intents( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List intents. @@ -674,12 +1049,14 @@ def list_intents(self, :rtype: DetailedResponse with `dict` result representing a `IntentCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_intents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_intents', + ) headers.update(sdk_headers) params = { @@ -689,33 +1066,38 @@ def list_intents(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_intent(self, - workspace_id: str, - intent: str, - *, - description: str = None, - examples: List['Example'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_intent( + self, + workspace_id: str, + intent: str, + *, + description: Optional[str] = None, + examples: Optional[List['Example']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create intent. @@ -740,24 +1122,29 @@ def create_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if examples is not None: examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_intent', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'intent': intent, 'description': description, - 'examples': examples + 'examples': examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -765,28 +1152,33 @@ def create_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_intent(self, - workspace_id: str, - intent: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_intent( + self, + workspace_id: str, + intent: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get intent. @@ -805,24 +1197,27 @@ def get_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_intent', + ) headers.update(sdk_headers) params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -830,24 +1225,28 @@ def get_intent(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_intent(self, - workspace_id: str, - intent: str, - *, - new_intent: str = None, - new_description: str = None, - new_examples: List['Example'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_intent( + self, + workspace_id: str, + intent: str, + *, + new_intent: Optional[str] = None, + new_description: Optional[str] = None, + new_examples: Optional[List['Example']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update intent. @@ -883,28 +1282,30 @@ def update_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') if new_examples is not None: new_examples = [convert_model(x) for x in new_examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_intent', + ) headers.update(sdk_headers) params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { 'intent': new_intent, 'description': new_description, - 'examples': new_examples + 'examples': new_examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -912,6 +1313,7 @@ def update_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -919,17 +1321,23 @@ def update_intent(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_intent(self, workspace_id: str, intent: str, - **kwargs) -> DetailedResponse: + def delete_intent( + self, + workspace_id: str, + intent: str, + **kwargs, + ) -> DetailedResponse: """ Delete intent. @@ -942,20 +1350,25 @@ def delete_intent(self, workspace_id: str, intent: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_intent', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -963,10 +1376,12 @@ def delete_intent(self, workspace_id: str, intent: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -975,16 +1390,18 @@ def delete_intent(self, workspace_id: str, intent: str, # Examples ######################### - def list_examples(self, - workspace_id: str, - intent: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_examples( + self, + workspace_id: str, + intent: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List user input examples. @@ -1011,14 +1428,16 @@ def list_examples(self, :rtype: DetailedResponse with `dict` result representing a `ExampleCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_examples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_examples', + ) headers.update(sdk_headers) params = { @@ -1027,11 +1446,12 @@ def list_examples(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1039,22 +1459,26 @@ def list_examples(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_example(self, - workspace_id: str, - intent: str, - text: str, - *, - mentions: List['Mention'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + mentions: Optional[List['Mention']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create user input example. @@ -1077,29 +1501,38 @@ def create_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') if mentions is not None: mentions = [convert_model(x) for x in mentions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_example', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': text, 'mentions': mentions} + data = { + 'text': text, + 'mentions': mentions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1107,22 +1540,26 @@ def create_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_example(self, - workspace_id: str, - intent: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get user input example. @@ -1138,22 +1575,28 @@ def get_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_example', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1161,23 +1604,27 @@ def get_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_example(self, - workspace_id: str, - intent: str, - text: str, - *, - new_text: str = None, - new_mentions: List['Mention'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + new_text: Optional[str] = None, + new_mentions: Optional[List['Mention']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update user input example. @@ -1201,29 +1648,38 @@ def update_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') if new_mentions is not None: new_mentions = [convert_model(x) for x in new_mentions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_example', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': new_text, 'mentions': new_mentions} + data = { + 'text': new_text, + 'mentions': new_mentions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1231,17 +1687,24 @@ def update_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_example(self, workspace_id: str, intent: str, text: str, - **kwargs) -> DetailedResponse: + def delete_example( + self, + workspace_id: str, + intent: str, + text: str, + **kwargs, + ) -> DetailedResponse: """ Delete user input example. @@ -1255,22 +1718,27 @@ def delete_example(self, workspace_id: str, intent: str, text: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_example', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1278,10 +1746,12 @@ def delete_example(self, workspace_id: str, intent: str, text: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1290,15 +1760,17 @@ def delete_example(self, workspace_id: str, intent: str, text: str, # Counterexamples ######################### - def list_counterexamples(self, - workspace_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_counterexamples( + self, + workspace_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List counterexamples. @@ -1324,12 +1796,14 @@ def list_counterexamples(self, :rtype: DetailedResponse with `dict` result representing a `CounterexampleCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_counterexamples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_counterexamples', + ) headers.update(sdk_headers) params = { @@ -1338,11 +1812,12 @@ def list_counterexamples(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1350,20 +1825,24 @@ def list_counterexamples(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_counterexample(self, - workspace_id: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_counterexample( + self, + workspace_id: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create counterexample. @@ -1384,25 +1863,33 @@ def create_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_counterexample', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': text} + data = { + 'text': text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1410,21 +1897,25 @@ def create_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_counterexample(self, - workspace_id: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_counterexample( + self, + workspace_id: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get counterexample. @@ -1441,20 +1932,26 @@ def get_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_counterexample', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1462,21 +1959,25 @@ def get_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_counterexample(self, - workspace_id: str, - text: str, - *, - new_text: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_counterexample( + self, + workspace_id: str, + text: str, + *, + new_text: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update counterexample. @@ -1497,25 +1998,33 @@ def update_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_counterexample', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': new_text} + data = { + 'text': new_text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1523,17 +2032,23 @@ def update_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_counterexample(self, workspace_id: str, text: str, - **kwargs) -> DetailedResponse: + def delete_counterexample( + self, + workspace_id: str, + text: str, + **kwargs, + ) -> DetailedResponse: """ Delete counterexample. @@ -1548,20 +2063,25 @@ def delete_counterexample(self, workspace_id: str, text: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_counterexample', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1569,10 +2089,12 @@ def delete_counterexample(self, workspace_id: str, text: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1581,16 +2103,18 @@ def delete_counterexample(self, workspace_id: str, text: str, # Entities ######################### - def list_entities(self, - workspace_id: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_entities( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entities. @@ -1619,12 +2143,14 @@ def list_entities(self, :rtype: DetailedResponse with `dict` result representing a `EntityCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_entities') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_entities', + ) headers.update(sdk_headers) params = { @@ -1634,35 +2160,40 @@ def list_entities(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_entity(self, - workspace_id: str, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - values: List['CreateValue'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_entity( + self, + workspace_id: str, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + values: Optional[List['CreateValue']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity. @@ -1692,26 +2223,31 @@ def create_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if values is not None: values = [convert_model(x) for x in values] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_entity', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'entity': entity, 'description': description, 'metadata': metadata, 'fuzzy_match': fuzzy_match, - 'values': values + 'values': values, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1719,28 +2255,33 @@ def create_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_entity(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_entity( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity. @@ -1759,24 +2300,27 @@ def get_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_entity', + ) headers.update(sdk_headers) params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1784,26 +2328,30 @@ def get_entity(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_entity(self, - workspace_id: str, - entity: str, - *, - new_entity: str = None, - new_description: str = None, - new_metadata: dict = None, - new_fuzzy_match: bool = None, - new_values: List['CreateValue'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_entity( + self, + workspace_id: str, + entity: str, + *, + new_entity: Optional[str] = None, + new_description: Optional[str] = None, + new_metadata: Optional[dict] = None, + new_fuzzy_match: Optional[bool] = None, + new_values: Optional[List['CreateValue']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity. @@ -1842,22 +2390,24 @@ def update_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') if new_values is not None: new_values = [convert_model(x) for x in new_values] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_entity', + ) headers.update(sdk_headers) params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -1865,7 +2415,7 @@ def update_entity(self, 'description': new_description, 'metadata': new_metadata, 'fuzzy_match': new_fuzzy_match, - 'values': new_values + 'values': new_values, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1873,6 +2423,7 @@ def update_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1880,17 +2431,23 @@ def update_entity(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_entity(self, workspace_id: str, entity: str, - **kwargs) -> DetailedResponse: + def delete_entity( + self, + workspace_id: str, + entity: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity. @@ -1903,20 +2460,25 @@ def delete_entity(self, workspace_id: str, entity: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_entity', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1924,10 +2486,12 @@ def delete_entity(self, workspace_id: str, entity: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1936,13 +2500,15 @@ def delete_entity(self, workspace_id: str, entity: str, # Mentions ######################### - def list_mentions(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_mentions( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity mentions. @@ -1962,24 +2528,27 @@ def list_mentions(self, :rtype: DetailedResponse with `dict` result representing a `EntityMentionCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_mentions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_mentions', + ) headers.update(sdk_headers) params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1987,10 +2556,12 @@ def list_mentions(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/mentions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1999,17 +2570,19 @@ def list_mentions(self, # Values ######################### - def list_values(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_values( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity values. @@ -2039,14 +2612,16 @@ def list_values(self, :rtype: DetailedResponse with `dict` result representing a `ValueCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_values') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_values', + ) headers.update(sdk_headers) params = { @@ -2056,11 +2631,12 @@ def list_values(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2068,25 +2644,29 @@ def list_values(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_value(self, - workspace_id: str, - entity: str, - value: str, - *, - metadata: dict = None, - type: str = None, - synonyms: List[str] = None, - patterns: List[str] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + metadata: Optional[dict] = None, + type: Optional[str] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity value. @@ -2120,26 +2700,31 @@ def create_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_value', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'value': value, 'metadata': metadata, 'type': type, 'synonyms': synonyms, - 'patterns': patterns + 'patterns': patterns, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2147,6 +2732,7 @@ def create_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2154,23 +2740,27 @@ def create_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_value(self, - workspace_id: str, - entity: str, - value: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity value. @@ -2190,26 +2780,29 @@ def get_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_value', + ) headers.update(sdk_headers) params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2217,27 +2810,31 @@ def get_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_value(self, - workspace_id: str, - entity: str, - value: str, - *, - new_value: str = None, - new_metadata: dict = None, - new_type: str = None, - new_synonyms: List[str] = None, - new_patterns: List[str] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + new_value: Optional[str] = None, + new_metadata: Optional[dict] = None, + new_type: Optional[str] = None, + new_synonyms: Optional[List[str]] = None, + new_patterns: Optional[List[str]] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity value. @@ -2284,22 +2881,24 @@ def update_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_value', + ) headers.update(sdk_headers) params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -2307,7 +2906,7 @@ def update_value(self, 'metadata': new_metadata, 'type': new_type, 'synonyms': new_synonyms, - 'patterns': new_patterns + 'patterns': new_patterns, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2315,6 +2914,7 @@ def update_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2322,17 +2922,24 @@ def update_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_value(self, workspace_id: str, entity: str, value: str, - **kwargs) -> DetailedResponse: + def delete_value( + self, + workspace_id: str, + entity: str, + value: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity value. @@ -2346,22 +2953,27 @@ def delete_value(self, workspace_id: str, entity: str, value: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_value', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2369,10 +2981,12 @@ def delete_value(self, workspace_id: str, entity: str, value: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2381,17 +2995,19 @@ def delete_value(self, workspace_id: str, entity: str, value: str, # Synonyms ######################### - def list_synonyms(self, - workspace_id: str, - entity: str, - value: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_synonyms( + self, + workspace_id: str, + entity: str, + value: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity value synonyms. @@ -2418,16 +3034,18 @@ def list_synonyms(self, :rtype: DetailedResponse with `dict` result representing a `SynonymCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_synonyms') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_synonyms', + ) headers.update(sdk_headers) params = { @@ -2436,11 +3054,12 @@ def list_synonyms(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2448,22 +3067,26 @@ def list_synonyms(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity value synonym. @@ -2486,29 +3109,37 @@ def create_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_synonym', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'synonym': synonym} + data = { + 'synonym': synonym, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2516,23 +3147,27 @@ def create_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity value synonym. @@ -2549,24 +3184,30 @@ def get_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_synonym', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2575,23 +3216,27 @@ def get_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - new_synonym: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + new_synonym: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity value synonym. @@ -2615,29 +3260,37 @@ def update_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_synonym', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'synonym': new_synonym} + data = { + 'synonym': new_synonym, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2646,17 +3299,25 @@ def update_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_synonym(self, workspace_id: str, entity: str, value: str, - synonym: str, **kwargs) -> DetailedResponse: + def delete_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity value synonym. @@ -2671,24 +3332,29 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_synonym', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2697,10 +3363,12 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2709,15 +3377,17 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, # Dialog nodes ######################### - def list_dialog_nodes(self, - workspace_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_dialog_nodes( + self, + workspace_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List dialog nodes. @@ -2742,12 +3412,14 @@ def list_dialog_nodes(self, :rtype: DetailedResponse with `dict` result representing a `DialogNodeCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_dialog_nodes') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_dialog_nodes', + ) headers.update(sdk_headers) params = { @@ -2756,11 +3428,12 @@ def list_dialog_nodes(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -2768,38 +3441,42 @@ def list_dialog_nodes(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - description: str = None, - conditions: str = None, - parent: str = None, - previous_sibling: str = None, - output: 'DialogNodeOutput' = None, - context: 'DialogNodeContext' = None, - metadata: dict = None, - next_step: 'DialogNodeNextStep' = None, - title: str = None, - type: str = None, - event_name: str = None, - variable: str = None, - actions: List['DialogNodeAction'] = None, - digress_in: str = None, - digress_out: str = None, - digress_out_slots: str = None, - user_label: str = None, - disambiguation_opt_out: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + description: Optional[str] = None, + conditions: Optional[str] = None, + parent: Optional[str] = None, + previous_sibling: Optional[str] = None, + output: Optional['DialogNodeOutput'] = None, + context: Optional['DialogNodeContext'] = None, + metadata: Optional[dict] = None, + next_step: Optional['DialogNodeNextStep'] = None, + title: Optional[str] = None, + type: Optional[str] = None, + event_name: Optional[str] = None, + variable: Optional[str] = None, + actions: Optional[List['DialogNodeAction']] = None, + digress_in: Optional[str] = None, + digress_out: Optional[str] = None, + digress_out_slots: Optional[str] = None, + user_label: Optional[str] = None, + disambiguation_opt_out: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create dialog node. @@ -2865,7 +3542,7 @@ def create_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') @@ -2878,12 +3555,17 @@ def create_dialog_node(self, if actions is not None: actions = [convert_model(x) for x in actions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_dialog_node', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'dialog_node': dialog_node, @@ -2904,7 +3586,7 @@ def create_dialog_node(self, 'digress_out': digress_out, 'digress_out_slots': digress_out_slots, 'user_label': user_label, - 'disambiguation_opt_out': disambiguation_opt_out + 'disambiguation_opt_out': disambiguation_opt_out, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2912,6 +3594,7 @@ def create_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -2919,21 +3602,25 @@ def create_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get dialog node. @@ -2949,20 +3636,26 @@ def get_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_dialog_node', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -2970,39 +3663,43 @@ def get_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - new_dialog_node: str = None, - new_description: str = None, - new_conditions: str = None, - new_parent: str = None, - new_previous_sibling: str = None, - new_output: 'DialogNodeOutput' = None, - new_context: 'DialogNodeContext' = None, - new_metadata: dict = None, - new_next_step: 'DialogNodeNextStep' = None, - new_title: str = None, - new_type: str = None, - new_event_name: str = None, - new_variable: str = None, - new_actions: List['DialogNodeAction'] = None, - new_digress_in: str = None, - new_digress_out: str = None, - new_digress_out_slots: str = None, - new_user_label: str = None, - new_disambiguation_opt_out: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + new_dialog_node: Optional[str] = None, + new_description: Optional[str] = None, + new_conditions: Optional[str] = None, + new_parent: Optional[str] = None, + new_previous_sibling: Optional[str] = None, + new_output: Optional['DialogNodeOutput'] = None, + new_context: Optional['DialogNodeContext'] = None, + new_metadata: Optional[dict] = None, + new_next_step: Optional['DialogNodeNextStep'] = None, + new_title: Optional[str] = None, + new_type: Optional[str] = None, + new_event_name: Optional[str] = None, + new_variable: Optional[str] = None, + new_actions: Optional[List['DialogNodeAction']] = None, + new_digress_in: Optional[str] = None, + new_digress_out: Optional[str] = None, + new_digress_out_slots: Optional[str] = None, + new_user_label: Optional[str] = None, + new_disambiguation_opt_out: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update dialog node. @@ -3072,9 +3769,9 @@ def update_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') if new_output is not None: new_output = convert_model(new_output) @@ -3085,12 +3782,17 @@ def update_dialog_node(self, if new_actions is not None: new_actions = [convert_model(x) for x in new_actions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_dialog_node', + ) headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'dialog_node': new_dialog_node, @@ -3111,7 +3813,7 @@ def update_dialog_node(self, 'digress_out': new_digress_out, 'digress_out_slots': new_digress_out_slots, 'user_label': new_user_label, - 'disambiguation_opt_out': new_disambiguation_opt_out + 'disambiguation_opt_out': new_disambiguation_opt_out, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3119,6 +3821,7 @@ def update_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3126,17 +3829,23 @@ def update_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_dialog_node(self, workspace_id: str, dialog_node: str, - **kwargs) -> DetailedResponse: + def delete_dialog_node( + self, + workspace_id: str, + dialog_node: str, + **kwargs, + ) -> DetailedResponse: """ Delete dialog node. @@ -3150,20 +3859,25 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_dialog_node', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3171,10 +3885,12 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3183,19 +3899,25 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, # Logs ######################### - def list_logs(self, - workspace_id: str, - *, - sort: str = None, - filter: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_logs( + self, + workspace_id: str, + *, + sort: Optional[str] = None, + filter: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events in a workspace. List the events from the log of a specific workspace. This method requires Manager access. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str workspace_id: Unique identifier of the workspace. :param str sort: (optional) How to sort the returned log events. You can @@ -3206,6 +3928,8 @@ def list_logs(self, [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). :param int page_limit: (optional) The number of records to return in each page of results. + **Note:** If the API is not returning your data, try lowering the + page_limit value. :param str cursor: (optional) A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers @@ -3213,12 +3937,14 @@ def list_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_logs', + ) headers.update(sdk_headers) params = { @@ -3226,36 +3952,45 @@ def list_logs(self, 'sort': sort, 'filter': filter, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/logs'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_all_logs(self, - filter: str, - *, - sort: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_all_logs( + self, + filter: str, + *, + sort: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events in all workspaces. List the events from the logs of all workspaces in the service instance. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that @@ -3277,12 +4012,14 @@ def list_all_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if filter is None: + if not filter: raise ValueError('filter must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_all_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_all_logs', + ) headers.update(sdk_headers) params = { @@ -3290,18 +4027,21 @@ def list_all_logs(self, 'filter': filter, 'sort': sort, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/logs' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3310,7 +4050,11 @@ def list_all_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3333,25 +4077,33 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3367,6 +4119,7 @@ class Sort(str, Enum): The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -3382,6 +4135,21 @@ class Sort(str, Enum): only if **export**=`true`. Specify `sort=stable` to sort all workspace objects by unique identifier, in ascending alphabetical order. """ + + STABLE = 'stable' + + +class ExportWorkspaceAsyncEnums: + """ + Enums for export_workspace_async parameters. + """ + + class Sort(str, Enum): + """ + Indicates how the returned workspace data will be sorted. Specify `sort=stable` to + sort all workspace objects by unique identifier, in ascending alphabetical order. + """ + STABLE = 'stable' @@ -3395,6 +4163,7 @@ class Sort(str, Enum): The attribute by which returned intents will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + INTENT = 'intent' UPDATED = 'updated' @@ -3409,6 +4178,7 @@ class Sort(str, Enum): The attribute by which returned examples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + TEXT = 'text' UPDATED = 'updated' @@ -3423,6 +4193,7 @@ class Sort(str, Enum): The attribute by which returned counterexamples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + TEXT = 'text' UPDATED = 'updated' @@ -3437,6 +4208,7 @@ class Sort(str, Enum): The attribute by which returned entities will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + ENTITY = 'entity' UPDATED = 'updated' @@ -3451,6 +4223,7 @@ class Sort(str, Enum): The attribute by which returned entity values will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + VALUE = 'value' UPDATED = 'updated' @@ -3465,6 +4238,7 @@ class Sort(str, Enum): The attribute by which returned entity value synonyms will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + SYNONYM = 'synonym' UPDATED = 'updated' @@ -3479,6 +4253,7 @@ class Sort(str, Enum): The attribute by which returned dialog nodes will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + DIALOG_NODE = 'dialog_node' UPDATED = 'updated' @@ -3488,14 +4263,18 @@ class Sort(str, Enum): ############################################################################## -class AgentAvailabilityMessage(): +class AgentAvailabilityMessage: """ AgentAvailabilityMessage. - :attr str message: (optional) The text of the message. + :param str message: (optional) The text of the message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a AgentAvailabilityMessage object. @@ -3507,8 +4286,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -3542,23 +4321,25 @@ def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: return not self == other -class BulkClassifyOutput(): +class BulkClassifyOutput: """ BulkClassifyOutput. - :attr BulkClassifyUtterance input: (optional) The user input utterance to + :param BulkClassifyUtterance input: (optional) The user input utterance to classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the utterance. """ - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: + def __init__( + self, + *, + input: Optional['BulkClassifyUtterance'] = None, + entities: Optional[List['RuntimeEntity']] = None, + intents: Optional[List['RuntimeIntent']] = None, + ) -> None: """ Initialize a BulkClassifyOutput object. @@ -3577,16 +4358,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] + if (input := _dict.get('input')) is not None: + args['input'] = BulkClassifyUtterance.from_dict(input) + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] return cls(**args) @classmethod @@ -3598,11 +4375,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list return _dict def _to_dict(self): @@ -3624,15 +4416,19 @@ def __ne__(self, other: 'BulkClassifyOutput') -> bool: return not self == other -class BulkClassifyResponse(): +class BulkClassifyResponse: """ BulkClassifyResponse. - :attr List[BulkClassifyOutput] output: (optional) An array of objects that + :param List[BulkClassifyOutput] output: (optional) An array of objects that contain classification information for the submitted input utterances. """ - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def __init__( + self, + *, + output: Optional[List['BulkClassifyOutput']] = None, + ) -> None: """ Initialize a BulkClassifyResponse object. @@ -3645,10 +4441,8 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(x) for x in _dict.get('output') - ] + if (output := _dict.get('output')) is not None: + args['output'] = [BulkClassifyOutput.from_dict(v) for v in output] return cls(**args) @classmethod @@ -3660,7 +4454,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x.to_dict() for x in self.output] + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list return _dict def _to_dict(self): @@ -3682,14 +4482,17 @@ def __ne__(self, other: 'BulkClassifyResponse') -> bool: return not self == other -class BulkClassifyUtterance(): +class BulkClassifyUtterance: """ The user input utterance to classify. - :attr str text: The text of the input utterance. + :param str text: The text of the input utterance. """ - def __init__(self, text: str) -> None: + def __init__( + self, + text: str, + ) -> None: """ Initialize a BulkClassifyUtterance object. @@ -3701,8 +4504,8 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in BulkClassifyUtterance JSON' @@ -3740,16 +4543,21 @@ def __ne__(self, other: 'BulkClassifyUtterance') -> bool: return not self == other -class CaptureGroup(): +class CaptureGroup: """ A recognized capture group for a pattern-based entity. - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + group: str, + *, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a CaptureGroup object. @@ -3764,13 +4572,13 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') + if (group := _dict.get('group')) is not None: + args['group'] = group else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -3806,18 +4614,21 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other -class ChannelTransferInfo(): +class ChannelTransferInfo: """ Information used by an integration to transfer the conversation to a different channel. - :attr ChannelTransferTarget target: An object specifying target channels + :param ChannelTransferTarget target: An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__( + self, + target: 'ChannelTransferTarget', + ) -> None: """ Initialize a ChannelTransferInfo object. @@ -3832,9 +4643,8 @@ def __init__(self, target: 'ChannelTransferTarget') -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) + if (target := _dict.get('target')) is not None: + args['target'] = ChannelTransferTarget.from_dict(target) else: raise ValueError( 'Required property \'target\' not present in ChannelTransferInfo JSON' @@ -3850,7 +4660,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() + if isinstance(self.target, dict): + _dict['target'] = self.target + else: + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -3872,17 +4685,21 @@ def __ne__(self, other: 'ChannelTransferInfo') -> bool: return not self == other -class ChannelTransferTarget(): +class ChannelTransferTarget: """ An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :param ChannelTransferTargetChat chat: (optional) Information for transferring + to the web chat integration. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__( + self, + *, + chat: Optional['ChannelTransferTargetChat'] = None, + ) -> None: """ Initialize a ChannelTransferTarget object. @@ -3895,9 +4712,8 @@ def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if (chat := _dict.get('chat')) is not None: + args['chat'] = ChannelTransferTargetChat.from_dict(chat) return cls(**args) @classmethod @@ -3909,7 +4725,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'chat') and self.chat is not None: - _dict['chat'] = self.chat.to_dict() + if isinstance(self.chat, dict): + _dict['chat'] = self.chat + else: + _dict['chat'] = self.chat.to_dict() return _dict def _to_dict(self): @@ -3931,14 +4750,18 @@ def __ne__(self, other: 'ChannelTransferTarget') -> bool: return not self == other -class ChannelTransferTargetChat(): +class ChannelTransferTargetChat: """ Information for transferring to the web chat integration. - :attr str url: (optional) The URL of the target web chat. + :param str url: (optional) The URL of the target web chat. """ - def __init__(self, *, url: str = None) -> None: + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: """ Initialize a ChannelTransferTargetChat object. @@ -3950,8 +4773,8 @@ def __init__(self, *, url: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url return cls(**args) @classmethod @@ -3985,55 +4808,77 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class Context(): +class Context: """ State information for the conversation. To maintain state, include the context from the previous response. - :attr str conversation_id: (optional) The unique identifier of the conversation. - :attr dict system: (optional) For internal use only. - :attr MessageContextMetadata metadata: (optional) Metadata related to the + :param str conversation_id: (optional) The unique identifier of the + conversation. The conversation ID cannot contain any of the following + characters: `+` `=` `&&` `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` + `*` `?` `:` `\` `/`. + :param dict system: (optional) For internal use only. + :param MessageContextMetadata metadata: (optional) Metadata related to the message. + + This type supports additional properties of type object. Any context variable. """ # The set of defined properties for the class _properties = frozenset(['conversation_id', 'system', 'metadata']) - def __init__(self, - *, - conversation_id: str = None, - system: dict = None, - metadata: 'MessageContextMetadata' = None, - **kwargs) -> None: + def __init__( + self, + *, + conversation_id: Optional[str] = None, + system: Optional[dict] = None, + metadata: Optional['MessageContextMetadata'] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a Context object. :param str conversation_id: (optional) The unique identifier of the - conversation. + conversation. The conversation ID cannot contain any of the following + characters: `+` `=` `&&` `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` + `~` `*` `?` `:` `\` `/`. :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any context variable. """ self.conversation_id = conversation_id self.system = system self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in Context._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'Context': """Initialize a Context object from a json dictionary.""" args = {} - if 'conversation_id' in _dict: - args['conversation_id'] = _dict.get('conversation_id') - if 'system' in _dict: - args['system'] = _dict.get('system') - if 'metadata' in _dict: - args['metadata'] = MessageContextMetadata.from_dict( - _dict.get('metadata')) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (conversation_id := _dict.get('conversation_id')) is not None: + args['conversation_id'] = conversation_id + if (system := _dict.get('system')) is not None: + args['system'] = system + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = MessageContextMetadata.from_dict(metadata) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -4050,12 +4895,14 @@ def to_dict(self) -> Dict: if hasattr(self, 'system') and self.system is not None: _dict['system'] = self.system if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + if isinstance(self.metadata, dict): + _dict['metadata'] = self.metadata + else: + _dict['metadata'] = self.metadata.to_dict() + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -4063,25 +4910,31 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of Context""" + """Return the additional properties from this instance of Context in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of Context""" - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + """Set a dictionary of additional properties in this instance of Context""" + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in Context._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in Context._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this Context object.""" @@ -4098,24 +4951,26 @@ def __ne__(self, other: 'Context') -> bool: return not self == other -class Counterexample(): +class Counterexample: """ Counterexample. - :attr str text: The text of a user input marked as irrelevant input. This string - must conform to the following restrictions: + :param str text: The text of a user input marked as irrelevant input. This + string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - text: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + text: str, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Counterexample object. @@ -4132,15 +4987,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Counterexample': """Initialize a Counterexample object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in Counterexample JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -4178,23 +5033,28 @@ def __ne__(self, other: 'Counterexample') -> bool: return not self == other -class CounterexampleCollection(): +class CounterexampleCollection: """ CounterexampleCollection. - :attr List[Counterexample] counterexamples: An array of objects describing the + :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. - :attr Pagination pagination: The pagination data for the returned objects. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, counterexamples: List['Counterexample'], - pagination: 'Pagination') -> None: + def __init__( + self, + counterexamples: List['Counterexample'], + pagination: 'Pagination', + ) -> None: """ Initialize a CounterexampleCollection object. :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.counterexamples = counterexamples self.pagination = pagination @@ -4203,17 +5063,16 @@ def __init__(self, counterexamples: List['Counterexample'], def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} - if 'counterexamples' in _dict: + if (counterexamples := _dict.get('counterexamples')) is not None: args['counterexamples'] = [ - Counterexample.from_dict(x) - for x in _dict.get('counterexamples') + Counterexample.from_dict(v) for v in counterexamples ] else: raise ValueError( 'Required property \'counterexamples\' not present in CounterexampleCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in CounterexampleCollection JSON' @@ -4230,11 +5089,18 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x.to_dict() for x in self.counterexamples - ] + counterexamples_list = [] + for v in self.counterexamples: + if isinstance(v, dict): + counterexamples_list.append(v) + else: + counterexamples_list.append(v.to_dict()) + _dict['counterexamples'] = counterexamples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -4256,36 +5122,39 @@ def __ne__(self, other: 'CounterexampleCollection') -> bool: return not self == other -class CreateEntity(): +class CreateEntity: """ CreateEntity. - :attr str entity: The name of the entity. This string must conform to the + :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string + :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[CreateValue] values: (optional) An array of objects describing the + :param List[CreateValue] values: (optional) An array of objects describing the entity values. """ - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['CreateValue'] = None) -> None: + def __init__( + self, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + values: Optional[List['CreateValue']] = None, + ) -> None: """ Initialize a CreateEntity object. @@ -4316,25 +5185,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEntity': """Initialize a CreateEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in CreateEntity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [ - CreateValue.from_dict(x) for x in _dict.get('values') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (fuzzy_match := _dict.get('fuzzy_match')) is not None: + args['fuzzy_match'] = fuzzy_match + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (values := _dict.get('values')) is not None: + args['values'] = [CreateValue.from_dict(v) for v in values] return cls(**args) @classmethod @@ -4358,7 +5225,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list return _dict def _to_dict(self): @@ -4380,31 +5253,33 @@ def __ne__(self, other: 'CreateEntity') -> bool: return not self == other -class CreateIntent(): +class CreateIntent: """ CreateIntent. - :attr str intent: The name of the intent. This string must conform to the + :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string + :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Example] examples: (optional) An array of user input examples for the - intent. + :param List[Example] examples: (optional) An array of user input examples for + the intent. """ - def __init__(self, - intent: str, - *, - description: str = None, - created: datetime = None, - updated: datetime = None, - examples: List['Example'] = None) -> None: + def __init__( + self, + intent: str, + *, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + examples: Optional[List['Example']] = None, + ) -> None: """ Initialize a CreateIntent object. @@ -4428,21 +5303,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateIntent': """Initialize a CreateIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in CreateIntent JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -4462,7 +5335,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -4484,40 +5363,42 @@ def __ne__(self, other: 'CreateIntent') -> bool: return not self == other -class CreateValue(): +class CreateValue: """ CreateValue. - :attr str value: The text of the entity value. This string must conform to the + :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: (optional) Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param str type: (optional) Specifies the type of entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the entity value. + :param List[str] patterns: (optional) An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - value: str, - *, - metadata: dict = None, - type: str = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + value: str, + *, + metadata: Optional[dict] = None, + type: Optional[str] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a CreateValue object. @@ -4551,23 +5432,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateValue': """Initialize a CreateValue object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in CreateValue JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (type := _dict.get('type')) is not None: + args['type'] = type + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = synonyms + if (patterns := _dict.get('patterns')) is not None: + args['patterns'] = patterns + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -4616,91 +5497,94 @@ class TypeEnum(str, Enum): """ Specifies the type of entity value. """ + SYNONYMS = 'synonyms' PATTERNS = 'patterns' -class DialogNode(): +class DialogNode: """ DialogNode. - :attr str dialog_node: The unique ID of the dialog node. This is an internal + :param str dialog_node: The unique ID of the dialog node. This is an internal identifier used to refer to the dialog node from other dialog nodes and in the diagnostic information included with message responses. This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - :attr str description: (optional) The description of the dialog node. This + :param str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str conditions: (optional) The condition that will trigger the dialog + :param str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str parent: (optional) The unique ID of the parent dialog node. This + :param str parent: (optional) The unique ID of the parent dialog node. This property is omitted if the dialog node has no parent. - :attr str previous_sibling: (optional) The unique ID of the previous sibling + :param str previous_sibling: (optional) The unique ID of the previous sibling dialog node. This property is omitted if the dialog node has no previous sibling. - :attr DialogNodeOutput output: (optional) The output of the dialog node. For + :param DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr DialogNodeContext context: (optional) The context for the dialog node. - :attr dict metadata: (optional) The metadata for the dialog node. - :attr DialogNodeNextStep next_step: (optional) The next step to execute + :param DialogNodeContext context: (optional) The context for the dialog node. + :param dict metadata: (optional) The metadata for the dialog node. + :param DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. - :attr str title: (optional) A human-readable name for the dialog node. If the + :param str title: (optional) A human-readable name for the dialog node. If the node is included in disambiguation, this title is used to populate the **label** property of the corresponding suggestion in the `suggestion` response type (unless it is overridden by the **user_label** property). The title is also used to populate the **topic** property in the `connect_to_agent` response type. This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - :attr str type: (optional) How the dialog node is processed. - :attr str event_name: (optional) How an `event_handler` node is processed. - :attr str variable: (optional) The location in the dialog context where output + :param str type: (optional) How the dialog node is processed. + :param str event_name: (optional) How an `event_handler` node is processed. + :param str variable: (optional) The location in the dialog context where output is stored. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. - :attr str digress_in: (optional) Whether this top-level dialog node can be + :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. - :attr str digress_out: (optional) Whether this dialog node can be returned to + :param str digress_out: (optional) Whether this dialog node can be returned to after a digression. - :attr str digress_out_slots: (optional) Whether the user can digress to + :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. - :attr str user_label: (optional) A label that can be displayed externally to + :param str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. If set, this label is used to identify the node in disambiguation responses (overriding the value of the **title** property). - :attr bool disambiguation_opt_out: (optional) Whether the dialog node should be + :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. - :attr bool disabled: (optional) For internal use only. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param bool disabled: (optional) For internal use only. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - dialog_node: str, - *, - description: str = None, - conditions: str = None, - parent: str = None, - previous_sibling: str = None, - output: 'DialogNodeOutput' = None, - context: 'DialogNodeContext' = None, - metadata: dict = None, - next_step: 'DialogNodeNextStep' = None, - title: str = None, - type: str = None, - event_name: str = None, - variable: str = None, - actions: List['DialogNodeAction'] = None, - digress_in: str = None, - digress_out: str = None, - digress_out_slots: str = None, - user_label: str = None, - disambiguation_opt_out: bool = None, - disabled: bool = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + dialog_node: str, + *, + description: Optional[str] = None, + conditions: Optional[str] = None, + parent: Optional[str] = None, + previous_sibling: Optional[str] = None, + output: Optional['DialogNodeOutput'] = None, + context: Optional['DialogNodeContext'] = None, + metadata: Optional[dict] = None, + next_step: Optional['DialogNodeNextStep'] = None, + title: Optional[str] = None, + type: Optional[str] = None, + event_name: Optional[str] = None, + variable: Optional[str] = None, + actions: Optional[List['DialogNodeAction']] = None, + digress_in: Optional[str] = None, + digress_out: Optional[str] = None, + digress_out_slots: Optional[str] = None, + user_label: Optional[str] = None, + disambiguation_opt_out: Optional[bool] = None, + disabled: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a DialogNode object. @@ -4782,57 +5666,55 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNode': """Initialize a DialogNode object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node else: raise ValueError( 'Required property \'dialog_node\' not present in DialogNode JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') - if 'parent' in _dict: - args['parent'] = _dict.get('parent') - if 'previous_sibling' in _dict: - args['previous_sibling'] = _dict.get('previous_sibling') - if 'output' in _dict: - args['output'] = DialogNodeOutput.from_dict(_dict.get('output')) - if 'context' in _dict: - args['context'] = DialogNodeContext.from_dict(_dict.get('context')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'next_step' in _dict: - args['next_step'] = DialogNodeNextStep.from_dict( - _dict.get('next_step')) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'event_name' in _dict: - args['event_name'] = _dict.get('event_name') - if 'variable' in _dict: - args['variable'] = _dict.get('variable') - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') - ] - if 'digress_in' in _dict: - args['digress_in'] = _dict.get('digress_in') - if 'digress_out' in _dict: - args['digress_out'] = _dict.get('digress_out') - if 'digress_out_slots' in _dict: - args['digress_out_slots'] = _dict.get('digress_out_slots') - if 'user_label' in _dict: - args['user_label'] = _dict.get('user_label') - if 'disambiguation_opt_out' in _dict: - args['disambiguation_opt_out'] = _dict.get('disambiguation_opt_out') - if 'disabled' in _dict: - args['disabled'] = _dict.get('disabled') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions + if (parent := _dict.get('parent')) is not None: + args['parent'] = parent + if (previous_sibling := _dict.get('previous_sibling')) is not None: + args['previous_sibling'] = previous_sibling + if (output := _dict.get('output')) is not None: + args['output'] = DialogNodeOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = DialogNodeContext.from_dict(context) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (next_step := _dict.get('next_step')) is not None: + args['next_step'] = DialogNodeNextStep.from_dict(next_step) + if (title := _dict.get('title')) is not None: + args['title'] = title + if (type := _dict.get('type')) is not None: + args['type'] = type + if (event_name := _dict.get('event_name')) is not None: + args['event_name'] = event_name + if (variable := _dict.get('variable')) is not None: + args['variable'] = variable + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (digress_in := _dict.get('digress_in')) is not None: + args['digress_in'] = digress_in + if (digress_out := _dict.get('digress_out')) is not None: + args['digress_out'] = digress_out + if (digress_out_slots := _dict.get('digress_out_slots')) is not None: + args['digress_out_slots'] = digress_out_slots + if (user_label := _dict.get('user_label')) is not None: + args['user_label'] = user_label + if (disambiguation_opt_out := + _dict.get('disambiguation_opt_out')) is not None: + args['disambiguation_opt_out'] = disambiguation_opt_out + if (disabled := _dict.get('disabled')) is not None: + args['disabled'] = disabled + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -4855,13 +5737,22 @@ def to_dict(self) -> Dict: 'previous_sibling') and self.previous_sibling is not None: _dict['previous_sibling'] = self.previous_sibling if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: - _dict['next_step'] = self.next_step.to_dict() + if isinstance(self.next_step, dict): + _dict['next_step'] = self.next_step + else: + _dict['next_step'] = self.next_step.to_dict() if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'type') and self.type is not None: @@ -4871,7 +5762,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'variable') and self.variable is not None: _dict['variable'] = self.variable if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'digress_in') and self.digress_in is not None: _dict['digress_in'] = self.digress_in if hasattr(self, 'digress_out') and self.digress_out is not None: @@ -4914,6 +5811,7 @@ class TypeEnum(str, Enum): """ How the dialog node is processed. """ + STANDARD = 'standard' EVENT_HANDLER = 'event_handler' FRAME = 'frame' @@ -4925,6 +5823,7 @@ class EventNameEnum(str, Enum): """ How an `event_handler` node is processed. """ + FOCUS = 'focus' INPUT = 'input' FILLED = 'filled' @@ -4939,6 +5838,7 @@ class DigressInEnum(str, Enum): """ Whether this top-level dialog node can be digressed into. """ + NOT_AVAILABLE = 'not_available' RETURNS = 'returns' DOES_NOT_RETURN = 'does_not_return' @@ -4947,6 +5847,7 @@ class DigressOutEnum(str, Enum): """ Whether this dialog node can be returned to after a digression. """ + ALLOW_RETURNING = 'allow_returning' ALLOW_ALL = 'allow_all' ALLOW_ALL_NEVER_RETURN = 'allow_all_never_return' @@ -4955,32 +5856,35 @@ class DigressOutSlotsEnum(str, Enum): """ Whether the user can digress to top-level nodes while filling out slots. """ + NOT_ALLOWED = 'not_allowed' ALLOW_RETURNING = 'allow_returning' ALLOW_ALL = 'allow_all' -class DialogNodeAction(): +class DialogNodeAction: """ DialogNodeAction. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result + :param str name: The name of the action. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided to + the action. + :param str result_variable: The location in the dialog context where the result of the action is stored. - :attr str credentials: (optional) The name of the context variable that the + :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__( + self, + name: str, + result_variable: str, + *, + type: Optional[str] = None, + parameters: Optional[dict] = None, + credentials: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeAction object. @@ -5003,24 +5907,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if (credentials := _dict.get('credentials')) is not None: + args['credentials'] = credentials return cls(**args) @classmethod @@ -5066,6 +5970,7 @@ class TypeEnum(str, Enum): """ The type of action to invoke. """ + CLIENT = 'client' SERVER = 'server' CLOUD_FUNCTION = 'cloud_function' @@ -5073,23 +5978,28 @@ class TypeEnum(str, Enum): WEBHOOK = 'webhook' -class DialogNodeCollection(): +class DialogNodeCollection: """ An array of dialog nodes. - :attr List[DialogNode] dialog_nodes: An array of objects describing the dialog + :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, dialog_nodes: List['DialogNode'], - pagination: 'Pagination') -> None: + def __init__( + self, + dialog_nodes: List['DialogNode'], + pagination: 'Pagination', + ) -> None: """ Initialize a DialogNodeCollection object. :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.dialog_nodes = dialog_nodes self.pagination = pagination @@ -5098,16 +6008,16 @@ def __init__(self, dialog_nodes: List['DialogNode'], def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} - if 'dialog_nodes' in _dict: + if (dialog_nodes := _dict.get('dialog_nodes')) is not None: args['dialog_nodes'] = [ - DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in dialog_nodes ] else: raise ValueError( 'Required property \'dialog_nodes\' not present in DialogNodeCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in DialogNodeCollection JSON' @@ -5123,9 +6033,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] + dialog_nodes_list = [] + for v in self.dialog_nodes: + if isinstance(v, dict): + dialog_nodes_list.append(v) + else: + dialog_nodes_list.append(v.to_dict()) + _dict['dialog_nodes'] = dialog_nodes_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -5147,37 +6066,58 @@ def __ne__(self, other: 'DialogNodeCollection') -> bool: return not self == other -class DialogNodeContext(): +class DialogNodeContext: """ The context for the dialog node. - :attr dict integrations: (optional) Context data intended for specific + :param dict integrations: (optional) Context data intended for specific integrations. + + This type supports additional properties of type object. Any context variable. """ # The set of defined properties for the class _properties = frozenset(['integrations']) - def __init__(self, *, integrations: dict = None, **kwargs) -> None: + def __init__( + self, + *, + integrations: Optional[dict] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a DialogNodeContext object. :param dict integrations: (optional) Context data intended for specific integrations. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any context variable. """ self.integrations = integrations - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in DialogNodeContext._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': """Initialize a DialogNodeContext object from a json dictionary.""" args = {} - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -5190,12 +6130,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -5203,27 +6142,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of DialogNodeContext""" + """Return the additional properties from this instance of DialogNodeContext in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of DialogNodeContext""" - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + """Set a dictionary of additional properties in this instance of DialogNodeContext""" + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in DialogNodeContext._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in DialogNodeContext._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this DialogNodeContext object.""" @@ -5240,11 +6185,11 @@ def __ne__(self, other: 'DialogNodeContext') -> bool: return not self == other -class DialogNodeNextStep(): +class DialogNodeNextStep: """ The next step to execute following this dialog node. - :attr str behavior: What happens after the dialog node completes. The valid + :param str behavior: What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` @@ -5265,16 +6210,18 @@ class DialogNodeNextStep(): - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. - :attr str dialog_node: (optional) The unique ID of the dialog node to process + :param str dialog_node: (optional) The unique ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`. - :attr str selector: (optional) Which part of the dialog node to process next. + :param str selector: (optional) Which part of the dialog node to process next. """ - def __init__(self, - behavior: str, - *, - dialog_node: str = None, - selector: str = None) -> None: + def __init__( + self, + behavior: str, + *, + dialog_node: Optional[str] = None, + selector: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeNextStep object. @@ -5312,16 +6259,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeNextStep': """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} - if 'behavior' in _dict: - args['behavior'] = _dict.get('behavior') + if (behavior := _dict.get('behavior')) is not None: + args['behavior'] = behavior else: raise ValueError( 'Required property \'behavior\' not present in DialogNodeNextStep JSON' ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'selector' in _dict: - args['selector'] = _dict.get('selector') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (selector := _dict.get('selector')) is not None: + args['selector'] = selector return cls(**args) @classmethod @@ -5382,6 +6329,7 @@ class BehaviorEnum(str, Enum): If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. """ + GET_USER_INPUT = 'get_user_input' SKIP_USER_INPUT = 'skip_user_input' JUMP_TO = 'jump_to' @@ -5393,36 +6341,42 @@ class SelectorEnum(str, Enum): """ Which part of the dialog node to process next. """ + CONDITION = 'condition' CLIENT = 'client' USER_INPUT = 'user_input' BODY = 'body' -class DialogNodeOutput(): +class DialogNodeOutput: """ The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects + :param List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. - :attr dict integrations: (optional) Output intended for specific integrations. + :param dict integrations: (optional) Output intended for specific integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). - :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how + :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. + + This type supports additional properties of type object. Any additional data included + in the dialog node output. """ # The set of defined properties for the class _properties = frozenset(['generic', 'integrations', 'modifiers']) - def __init__(self, - *, - generic: List['DialogNodeOutputGeneric'] = None, - integrations: dict = None, - modifiers: 'DialogNodeOutputModifiers' = None, - **kwargs) -> None: + def __init__( + self, + *, + generic: Optional[List['DialogNodeOutputGeneric']] = None, + integrations: Optional[dict] = None, + modifiers: Optional['DialogNodeOutputModifiers'] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a DialogNodeOutput object. @@ -5433,30 +6387,43 @@ def __init__(self, [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included in the + dialog node output. """ self.generic = generic self.integrations = integrations self.modifiers = modifiers - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in DialogNodeOutput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - DialogNodeOutputGeneric.from_dict(x) - for x in _dict.get('generic') + DialogNodeOutputGeneric.from_dict(v) for v in generic ] - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') - if 'modifiers' in _dict: - args['modifiers'] = DialogNodeOutputModifiers.from_dict( - _dict.get('modifiers')) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + if (modifiers := _dict.get('modifiers')) is not None: + args['modifiers'] = DialogNodeOutputModifiers.from_dict(modifiers) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -5468,17 +6435,25 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations if hasattr(self, 'modifiers') and self.modifiers is not None: - _dict['modifiers'] = self.modifiers.to_dict() - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + if isinstance(self.modifiers, dict): + _dict['modifiers'] = self.modifiers + else: + _dict['modifiers'] = self.modifiers.to_dict() + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -5486,27 +6461,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of DialogNodeOutput""" + """Return the additional properties from this instance of DialogNodeOutput in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of DialogNodeOutput""" - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + """Set a dictionary of additional properties in this instance of DialogNodeOutput""" + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in DialogNodeOutput._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in DialogNodeOutput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" @@ -5523,14 +6504,18 @@ def __ne__(self, other: 'DialogNodeOutput') -> bool: return not self == other -class DialogNodeOutputConnectToAgentTransferInfo(): +class DialogNodeOutputConnectToAgentTransferInfo: """ Routing or other contextual information to be used by target service desk systems. - :attr dict target: (optional) + :param dict target: (optional) """ - def __init__(self, *, target: dict = None) -> None: + def __init__( + self, + *, + target: Optional[dict] = None, + ) -> None: """ Initialize a DialogNodeOutputConnectToAgentTransferInfo object. @@ -5543,8 +6528,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if (target := _dict.get('target')) is not None: + args['target'] = target return cls(**args) @classmethod @@ -5580,13 +6565,13 @@ def __ne__(self, return not self == other -class DialogNodeOutputGeneric(): +class DialogNodeOutputGeneric: """ DialogNodeOutputGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a DialogNodeOutputGeneric object. @@ -5613,22 +6598,20 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' - ])) + msg = "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' + ])) raise Exception(msg) @classmethod @@ -5676,17 +6659,21 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class DialogNodeOutputModifiers(): +class DialogNodeOutputModifiers: """ Options that modify how specified output is handled. - :attr bool overwrite: (optional) Whether values in the output will overwrite + :param bool overwrite: (optional) Whether values in the output will overwrite output values in an array specified by previously executed dialog nodes. If this option is set to `false`, new values will be appended to previously specified values. """ - def __init__(self, *, overwrite: bool = None) -> None: + def __init__( + self, + *, + overwrite: Optional[bool] = None, + ) -> None: """ Initialize a DialogNodeOutputModifiers object. @@ -5701,8 +6688,8 @@ def __init__(self, *, overwrite: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputModifiers': """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} - if 'overwrite' in _dict: - args['overwrite'] = _dict.get('overwrite') + if (overwrite := _dict.get('overwrite')) is not None: + args['overwrite'] = overwrite return cls(**args) @classmethod @@ -5736,18 +6723,21 @@ def __ne__(self, other: 'DialogNodeOutputModifiers') -> bool: return not self == other -class DialogNodeOutputOptionsElement(): +class DialogNodeOutputOptionsElement: """ DialogNodeOutputOptionsElement. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__( + self, + label: str, + value: 'DialogNodeOutputOptionsElementValue', + ) -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -5763,15 +6753,14 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' @@ -5789,7 +6778,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -5811,28 +6803,30 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: return not self == other -class DialogNodeOutputOptionsElementValue(): +class DialogNodeOutputOptionsElementValue: """ An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be used + :param List[RuntimeIntent] intents: (optional) An array of intents to be used while processing the input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be used + :param List[RuntimeEntity] entities: (optional) An array of entities to be used while processing the user input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + ) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -5855,16 +6849,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] return cls(**args) @classmethod @@ -5876,11 +6866,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list return _dict def _to_dict(self): @@ -5902,16 +6907,20 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: return not self == other -class DialogNodeOutputTextValuesElement(): +class DialogNodeOutputTextValuesElement: """ DialogNodeOutputTextValuesElement. - :attr str text: (optional) The text of a response. This string can include + :param str text: (optional) The text of a response. This string can include newline characters (`\n`), Markdown tagging, or other special characters, if supported by the channel. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputTextValuesElement object. @@ -5925,8 +6934,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputTextValuesElement': """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -5960,21 +6969,23 @@ def __ne__(self, other: 'DialogNodeOutputTextValuesElement') -> bool: return not self == other -class DialogNodeVisitedDetails(): +class DialogNodeVisitedDetails: """ DialogNodeVisitedDetails. - :attr str dialog_node: (optional) The unique ID of a dialog node that was + :param str dialog_node: (optional) The unique ID of a dialog node that was triggered during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__( + self, + *, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + conditions: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeVisitedDetails object. @@ -5992,12 +7003,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeVisitedDetails': """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions return cls(**args) @classmethod @@ -6035,29 +7046,34 @@ def __ne__(self, other: 'DialogNodeVisitedDetails') -> bool: return not self == other -class DialogSuggestion(): +class DialogSuggestion: """ DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **title** or **user_label** property of the corresponding - dialog node. - :attr DialogSuggestionValue value: An object defining the message input, + :param str label: The user-facing label for the disambiguation option. This + label is taken from the **title** or **user_label** property of the + corresponding dialog node. + :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. - :attr dict output: (optional) The dialog output that will be returned from the + **Note:** These properties must be included in the request body of the next + message sent to the assistant. Do not modify or remove any of the included + properties. + :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :attr str dialog_node: (optional) The unique ID of the dialog node that the + :param str dialog_node: (optional) The unique ID of the dialog node that the **label** property is taken from. The **label** property is populated using the value of the dialog node's **title** or **user_label** property. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None, - dialog_node: str = None) -> None: + def __init__( + self, + label: str, + value: 'DialogSuggestionValue', + *, + output: Optional[dict] = None, + dialog_node: Optional[str] = None, + ) -> None: """ Initialize a DialogSuggestion object. @@ -6067,6 +7083,9 @@ def __init__(self, :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the + next message sent to the assistant. Do not modify or remove any of the + included properties. :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. :param str dialog_node: (optional) The unique ID of the dialog node that @@ -6082,22 +7101,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogSuggestionValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (output := _dict.get('output')) is not None: + args['output'] = output + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node return cls(**args) @classmethod @@ -6111,7 +7130,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output if hasattr(self, 'dialog_node') and self.dialog_node is not None: @@ -6137,24 +7159,28 @@ def __ne__(self, other: 'DialogSuggestion') -> bool: return not self == other -class DialogSuggestionValue(): +class DialogSuggestionValue: """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the next message + sent to the assistant. Do not modify or remove any of the included properties. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be sent + :param List[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent + :param List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + ) -> None: """ Initialize a DialogSuggestionValue object. @@ -6173,16 +7199,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] return cls(**args) @classmethod @@ -6194,11 +7216,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list return _dict def _to_dict(self): @@ -6220,36 +7257,39 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other -class Entity(): +class Entity: """ Entity. - :attr str entity: The name of the entity. This string must conform to the + :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string + :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Value] values: (optional) An array of objects describing the entity + :param List[Value] values: (optional) An array of objects describing the entity values. """ - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['Value'] = None) -> None: + def __init__( + self, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + values: Optional[List['Value']] = None, + ) -> None: """ Initialize a Entity object. @@ -6280,23 +7320,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Entity': """Initialize a Entity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in Entity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [Value.from_dict(x) for x in _dict.get('values')] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (fuzzy_match := _dict.get('fuzzy_match')) is not None: + args['fuzzy_match'] = fuzzy_match + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (values := _dict.get('values')) is not None: + args['values'] = [Value.from_dict(v) for v in values] return cls(**args) @classmethod @@ -6320,7 +7360,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list return _dict def _to_dict(self): @@ -6342,23 +7388,28 @@ def __ne__(self, other: 'Entity') -> bool: return not self == other -class EntityCollection(): +class EntityCollection: """ An array of objects describing the entities for the workspace. - :attr List[Entity] entities: An array of objects describing the entities defined - for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :param List[Entity] entities: An array of objects describing the entities + defined for the workspace. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, entities: List['Entity'], - pagination: 'Pagination') -> None: + def __init__( + self, + entities: List['Entity'], + pagination: 'Pagination', + ) -> None: """ Initialize a EntityCollection object. :param List[Entity] entities: An array of objects describing the entities defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.entities = entities self.pagination = pagination @@ -6367,16 +7418,14 @@ def __init__(self, entities: List['Entity'], def from_dict(cls, _dict: Dict) -> 'EntityCollection': """Initialize a EntityCollection object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = [ - Entity.from_dict(x) for x in _dict.get('entities') - ] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [Entity.from_dict(v) for v in entities] else: raise ValueError( 'Required property \'entities\' not present in EntityCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EntityCollection JSON' @@ -6392,9 +7441,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6416,17 +7474,22 @@ def __ne__(self, other: 'EntityCollection') -> bool: return not self == other -class EntityMention(): +class EntityMention: """ An object describing a contextual entity mention. - :attr str text: The text of the user input example. - :attr str intent: The name of the intent. - :attr List[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param str text: The text of the user input example. + :param str intent: The name of the intent. + :param List[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ - def __init__(self, text: str, intent: str, location: List[int]) -> None: + def __init__( + self, + text: str, + intent: str, + location: List[int], + ) -> None: """ Initialize a EntityMention object. @@ -6443,19 +7506,19 @@ def __init__(self, text: str, intent: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in EntityMention JSON') - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in EntityMention JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location else: raise ValueError( 'Required property \'location\' not present in EntityMention JSON' @@ -6497,23 +7560,28 @@ def __ne__(self, other: 'EntityMention') -> bool: return not self == other -class EntityMentionCollection(): +class EntityMentionCollection: """ EntityMentionCollection. - :attr List[EntityMention] examples: An array of objects describing the entity + :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. - :attr Pagination pagination: The pagination data for the returned objects. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, examples: List['EntityMention'], - pagination: 'Pagination') -> None: + def __init__( + self, + examples: List['EntityMention'], + pagination: 'Pagination', + ) -> None: """ Initialize a EntityMentionCollection object. :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.examples = examples self.pagination = pagination @@ -6522,16 +7590,14 @@ def __init__(self, examples: List['EntityMention'], def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - EntityMention.from_dict(x) for x in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [EntityMention.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in EntityMentionCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EntityMentionCollection JSON' @@ -6547,9 +7613,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6571,26 +7646,29 @@ def __ne__(self, other: 'EntityMentionCollection') -> bool: return not self == other -class Example(): +class Example: """ Example. - :attr str text: The text of a user input example. This string must conform to + :param str text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[Mention] mentions: (optional) An array of contextual entity mentions. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param List[Mention] mentions: (optional) An array of contextual entity + mentions. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - text: str, - *, - mentions: List['Mention'] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + text: str, + *, + mentions: Optional[List['Mention']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Example object. @@ -6610,19 +7688,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Example': """Initialize a Example object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in Example JSON') - if 'mentions' in _dict: - args['mentions'] = [ - Mention.from_dict(x) for x in _dict.get('mentions') - ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = [Mention.from_dict(v) for v in mentions] + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -6636,7 +7712,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] + mentions_list = [] + for v in self.mentions: + if isinstance(v, dict): + mentions_list.append(v) + else: + mentions_list.append(v.to_dict()) + _dict['mentions'] = mentions_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -6662,23 +7744,28 @@ def __ne__(self, other: 'Example') -> bool: return not self == other -class ExampleCollection(): +class ExampleCollection: """ ExampleCollection. - :attr List[Example] examples: An array of objects describing the examples + :param List[Example] examples: An array of objects describing the examples defined for the intent. - :attr Pagination pagination: The pagination data for the returned objects. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, examples: List['Example'], - pagination: 'Pagination') -> None: + def __init__( + self, + examples: List['Example'], + pagination: 'Pagination', + ) -> None: """ Initialize a ExampleCollection object. :param List[Example] examples: An array of objects describing the examples defined for the intent. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.examples = examples self.pagination = pagination @@ -6687,16 +7774,14 @@ def __init__(self, examples: List['Example'], def from_dict(cls, _dict: Dict) -> 'ExampleCollection': """Initialize a ExampleCollection object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in ExampleCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ExampleCollection JSON' @@ -6712,9 +7797,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6736,31 +7830,33 @@ def __ne__(self, other: 'ExampleCollection') -> bool: return not self == other -class Intent(): +class Intent: """ Intent. - :attr str intent: The name of the intent. This string must conform to the + :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string + :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Example] examples: (optional) An array of user input examples for the - intent. + :param List[Example] examples: (optional) An array of user input examples for + the intent. """ - def __init__(self, - intent: str, - *, - description: str = None, - created: datetime = None, - updated: datetime = None, - examples: List['Example'] = None) -> None: + def __init__( + self, + intent: str, + *, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + examples: Optional[List['Example']] = None, + ) -> None: """ Initialize a Intent object. @@ -6784,21 +7880,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Intent': """Initialize a Intent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in Intent JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -6818,7 +7912,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -6840,23 +7940,28 @@ def __ne__(self, other: 'Intent') -> bool: return not self == other -class IntentCollection(): +class IntentCollection: """ IntentCollection. - :attr List[Intent] intents: An array of objects describing the intents defined + :param List[Intent] intents: An array of objects describing the intents defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, intents: List['Intent'], - pagination: 'Pagination') -> None: + def __init__( + self, + intents: List['Intent'], + pagination: 'Pagination', + ) -> None: """ Initialize a IntentCollection object. :param List[Intent] intents: An array of objects describing the intents defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.intents = intents self.pagination = pagination @@ -6865,16 +7970,14 @@ def __init__(self, intents: List['Intent'], def from_dict(cls, _dict: Dict) -> 'IntentCollection': """Initialize a IntentCollection object from a json dictionary.""" args = {} - if 'intents' in _dict: - args['intents'] = [ - Intent.from_dict(x) for x in _dict.get('intents') - ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [Intent.from_dict(v) for v in intents] else: raise ValueError( 'Required property \'intents\' not present in IntentCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in IntentCollection JSON' @@ -6890,9 +7993,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6914,27 +8026,34 @@ def __ne__(self, other: 'IntentCollection') -> bool: return not self == other -class Log(): +class Log: """ Log. - :attr MessageRequest request: A request sent to the workspace, including the + :param MessageRequest request: A request sent to the workspace, including the user input and context. - :attr MessageResponse response: The response sent by the workspace, including + :param MessageResponse response: The response sent by the workspace, including the output text, detected intents and entities, and context. - :attr str log_id: A unique identifier for the logged event. - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the + :param str log_id: A unique identifier for the logged event. + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the message. - :attr str workspace_id: The unique identifier of the workspace where the request - was made. - :attr str language: The language of the workspace where the message request was + :param str workspace_id: The unique identifier of the workspace where the + request was made. + :param str language: The language of the workspace where the message request was made. """ - def __init__(self, request: 'MessageRequest', response: 'MessageResponse', - log_id: str, request_timestamp: str, response_timestamp: str, - workspace_id: str, language: str) -> None: + def __init__( + self, + request: 'MessageRequest', + response: 'MessageResponse', + log_id: str, + request_timestamp: str, + response_timestamp: str, + workspace_id: str, + language: str, + ) -> None: """ Initialize a Log object. @@ -6963,40 +8082,40 @@ def __init__(self, request: 'MessageRequest', response: 'MessageResponse', def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) + if (request := _dict.get('request')) is not None: + args['request'] = MessageRequest.from_dict(request) else: raise ValueError( 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) + if (response := _dict.get('response')) is not None: + args['response'] = MessageResponse.from_dict(response) else: raise ValueError( 'Required property \'response\' not present in Log JSON') - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id else: raise ValueError( 'Required property \'log_id\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp else: raise ValueError( 'Required property \'request_timestamp\' not present in Log JSON' ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp else: raise ValueError( 'Required property \'response_timestamp\' not present in Log JSON' ) - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id else: raise ValueError( 'Required property \'workspace_id\' not present in Log JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Log JSON') @@ -7011,9 +8130,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, @@ -7048,21 +8173,27 @@ def __ne__(self, other: 'Log') -> bool: return not self == other -class LogCollection(): +class LogCollection: """ LogCollection. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__( + self, + logs: List['Log'], + pagination: 'LogPagination', + ) -> None: """ Initialize a LogCollection object. :param List[Log] logs: An array of objects describing log events. :param LogPagination pagination: The pagination data for the returned - objects. + objects. For more information about using pagination, see + [Pagination](#pagination). """ self.logs = logs self.pagination = pagination @@ -7071,14 +8202,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in LogCollection JSON' @@ -7094,9 +8224,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x.to_dict() for x in self.logs] + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7118,24 +8257,26 @@ def __ne__(self, other: 'LogCollection') -> bool: return not self == other -class LogMessage(): +class LogMessage: """ Log message details. - :attr str level: The severity of the log message. - :attr str msg: The text of the log message. - :attr str code: A code that indicates the category to which the error message + :param str level: The severity of the log message. + :param str msg: The text of the log message. + :param str code: A code that indicates the category to which the error message belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog + :param LogMessageSource source: (optional) An object that identifies the dialog element that generated the error message. """ - def __init__(self, - level: str, - msg: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + level: str, + msg: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: """ Initialize a LogMessage object. @@ -7155,23 +8296,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogMessage': """Initialize a LogMessage object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') + if (level := _dict.get('level')) is not None: + args['level'] = level else: raise ValueError( 'Required property \'level\' not present in LogMessage JSON') - if 'msg' in _dict: - args['msg'] = _dict.get('msg') + if (msg := _dict.get('msg')) is not None: + args['msg'] = msg else: raise ValueError( 'Required property \'msg\' not present in LogMessage JSON') - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in LogMessage JSON') - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = LogMessageSource.from_dict(source) return cls(**args) @classmethod @@ -7189,7 +8330,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -7214,22 +8358,28 @@ class LevelEnum(str, Enum): """ The severity of the log message. """ + INFO = 'info' ERROR = 'error' WARN = 'warn' -class LogMessageSource(): +class LogMessageSource: """ An object that identifies the dialog element that generated the error message. - :attr str type: (optional) A string that indicates the type of dialog element + :param str type: (optional) A string that indicates the type of dialog element that generated the error message. - :attr str dialog_node: (optional) The unique identifier of the dialog node that + :param str dialog_node: (optional) The unique identifier of the dialog node that generated the error message. """ - def __init__(self, *, type: str = None, dialog_node: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + ) -> None: """ Initialize a LogMessageSource object. @@ -7245,10 +8395,10 @@ def __init__(self, *, type: str = None, dialog_node: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSource': """Initialize a LogMessageSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node return cls(**args) @classmethod @@ -7288,24 +8438,28 @@ class TypeEnum(str, Enum): A string that indicates the type of dialog element that generated the error message. """ + DIALOG_NODE = 'dialog_node' -class LogPagination(): +class LogPagination: """ - The pagination data for the returned objects. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :attr str next_url: (optional) The URL that will return the next page of + :param str next_url: (optional) The URL that will return the next page of results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__( + self, + *, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a LogPagination object. @@ -7323,12 +8477,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -7366,16 +8520,20 @@ def __ne__(self, other: 'LogPagination') -> bool: return not self == other -class Mention(): +class Mention: """ A mention of a contextual entity. - :attr str entity: The name of the entity. - :attr List[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param str entity: The name of the entity. + :param List[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ - def __init__(self, entity: str, location: List[int]) -> None: + def __init__( + self, + entity: str, + location: List[int], + ) -> None: """ Initialize a Mention object. @@ -7390,13 +8548,13 @@ def __init__(self, entity: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in Mention JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location else: raise ValueError( 'Required property \'location\' not present in Mention JSON') @@ -7435,14 +8593,14 @@ def __ne__(self, other: 'Mention') -> bool: return not self == other -class MessageContextMetadata(): +class MessageContextMetadata: """ Metadata related to the message. - :attr str deployment: (optional) A label identifying the deployment environment, - used for filtering log data. This string cannot contain carriage return, - newline, or tab characters. - :attr str user_id: (optional) A string value that identifies the user who is + :param str deployment: (optional) A label identifying the deployment + environment, used for filtering log data. This string cannot contain carriage + return, newline, or tab characters. + :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -7454,7 +8612,12 @@ class MessageContextMetadata(): request, the value specified at the root is used. """ - def __init__(self, *, deployment: str = None, user_id: str = None) -> None: + def __init__( + self, + *, + deployment: Optional[str] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageContextMetadata object. @@ -7479,10 +8642,10 @@ def __init__(self, *, deployment: str = None, user_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'MessageContextMetadata': """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} - if 'deployment' in _dict: - args['deployment'] = _dict.get('deployment') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (deployment := _dict.get('deployment')) is not None: + args['deployment'] = deployment + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -7518,16 +8681,16 @@ def __ne__(self, other: 'MessageContextMetadata') -> bool: return not self == other -class MessageInput(): +class MessageInput: """ An input object that includes the input text. - :attr str text: (optional) The text of the user input. This string cannot + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr bool spelling_suggestions: (optional) Whether to use spelling correction + :param bool spelling_suggestions: (optional) Whether to use spelling correction when processing the input. This property overrides the value of the **spelling_suggestions** property in the workspace settings. - :attr bool spelling_auto_correct: (optional) Whether to use autocorrection when + :param bool spelling_auto_correct: (optional) Whether to use autocorrection when processing the input. If spelling correction is used and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections @@ -7535,11 +8698,14 @@ class MessageInput(): in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :attr str suggested_text: (optional) Any suggested corrections of the input + :param str suggested_text: (optional) Any suggested corrections of the input text. This property is returned only if spelling correction is enabled and autocorrection is disabled. - :attr str original_text: (optional) The original user input text. This property + :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. + + This type supports additional properties of type object. Any additional data included + with the message input. """ # The set of defined properties for the class @@ -7548,14 +8714,16 @@ class MessageInput(): 'suggested_text', 'original_text' ]) - def __init__(self, - *, - text: str = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - suggested_text: str = None, - original_text: str = None, - **kwargs) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + spelling_suggestions: Optional[bool] = None, + spelling_auto_correct: Optional[bool] = None, + suggested_text: Optional[str] = None, + original_text: Optional[str] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a MessageInput object. @@ -7572,32 +8740,49 @@ def __init__(self, the original text is returned in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included with the + message input. """ self.text = text self.spelling_suggestions = spelling_suggestions self.spelling_auto_correct = spelling_auto_correct self.suggested_text = suggested_text self.original_text = original_text - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in MessageInput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (spelling_auto_correct := + _dict.get('spelling_auto_correct')) is not None: + args['spelling_auto_correct'] = spelling_auto_correct + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -7622,12 +8807,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'original_text') and getattr( self, 'original_text') is not None: _dict['original_text'] = getattr(self, 'original_text') - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -7635,27 +8819,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageInput""" + """Return the additional properties from this instance of MessageInput in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageInput""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + """Set a dictionary of additional properties in this instance of MessageInput""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageInput._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageInput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" @@ -7672,27 +8862,27 @@ def __ne__(self, other: 'MessageInput') -> bool: return not self == other -class MessageRequest(): +class MessageRequest: """ A request sent to the workspace, including the user input and context. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :attr Context context: (optional) State information for the conversation. To + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: (optional) State information for the conversation. To maintain state, include the context from the previous response. - :attr OutputData output: (optional) An output object that includes the response + :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr str user_id: (optional) A string value that identifies the user who is + :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -7704,16 +8894,18 @@ class MessageRequest(): the value specified at the root is used. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - alternate_intents: bool = None, - context: 'Context' = None, - output: 'OutputData' = None, - actions: List['DialogNodeAction'] = None, - user_id: str = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + alternate_intents: Optional[bool] = None, + context: Optional['Context'] = None, + output: Optional['OutputData'] = None, + actions: Optional[List['DialogNodeAction']] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageRequest object. @@ -7758,28 +8950,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'context' in _dict: - args['context'] = Context.from_dict(_dict.get('context')) - if 'output' in _dict: - args['output'] = OutputData.from_dict(_dict.get('output')) - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') - ] - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (context := _dict.get('context')) is not None: + args['context'] = Context.from_dict(context) + if (output := _dict.get('output')) is not None: + args['output'] = OutputData.from_dict(output) + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -7791,20 +8977,47 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: - _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + actions_list = [] + for v in getattr(self, 'actions'): + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -7828,25 +9041,25 @@ def __ne__(self, other: 'MessageRequest') -> bool: return not self == other -class MessageResponse(): +class MessageResponse: """ The response sent by the workspace, including the output text, detected intents and entities, and context. - :attr MessageInput input: An input object that includes the input text. - :attr List[RuntimeIntent] intents: An array of intents recognized in the user + :param MessageInput input: An input object that includes the input text. + :param List[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: An array of entities identified in the user + :param List[RuntimeEntity] entities: An array of entities identified in the user input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :attr Context context: State information for the conversation. To maintain + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: State information for the conversation. To maintain state, include the context from the previous response. - :attr OutputData output: An output object that includes the response to the + :param OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr str user_id: A string value that identifies the user who is interacting + :param str user_id: A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -7858,16 +9071,18 @@ class MessageResponse(): the value specified at the root is used. """ - def __init__(self, - input: 'MessageInput', - intents: List['RuntimeIntent'], - entities: List['RuntimeEntity'], - context: 'Context', - output: 'OutputData', - user_id: str, - *, - alternate_intents: bool = None, - actions: List['DialogNodeAction'] = None) -> None: + def __init__( + self, + input: 'MessageInput', + intents: List['RuntimeIntent'], + entities: List['RuntimeEntity'], + context: 'Context', + output: 'OutputData', + user_id: str, + *, + alternate_intents: Optional[bool] = None, + actions: Optional[List['DialogNodeAction']] = None, + ) -> None: """ Initialize a MessageResponse object. @@ -7906,48 +9121,42 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) else: raise ValueError( 'Required property \'input\' not present in MessageResponse JSON' ) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] else: raise ValueError( 'Required property \'intents\' not present in MessageResponse JSON' ) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] else: raise ValueError( 'Required property \'entities\' not present in MessageResponse JSON' ) - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'context' in _dict: - args['context'] = Context.from_dict(_dict.get('context')) + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (context := _dict.get('context')) is not None: + args['context'] = Context.from_dict(context) else: raise ValueError( 'Required property \'context\' not present in MessageResponse JSON' ) - if 'output' in _dict: - args['output'] = OutputData.from_dict(_dict.get('output')) + if (output := _dict.get('output')) is not None: + args['output'] = OutputData.from_dict(output) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') - ] - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( 'Required property \'user_id\' not present in MessageResponse JSON' @@ -7963,20 +9172,47 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: - _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + actions_list = [] + for v in getattr(self, 'actions'): + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -8000,37 +9236,43 @@ def __ne__(self, other: 'MessageResponse') -> bool: return not self == other -class OutputData(): +class OutputData: """ An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :attr List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + :param List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :attr List[LogMessage] log_messages: An array of up to 50 messages logged with + :param List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. + + This type supports additional properties of type object. Any additional data included + with the output. """ # The set of defined properties for the class _properties = frozenset( ['nodes_visited', 'nodes_visited_details', 'log_messages', 'generic']) - def __init__(self, - log_messages: List['LogMessage'], - *, - nodes_visited: List[str] = None, - nodes_visited_details: List['DialogNodeVisitedDetails'] = None, - generic: List['RuntimeResponseGeneric'] = None, - **kwargs) -> None: + def __init__( + self, + log_messages: List['LogMessage'], + *, + nodes_visited: Optional[List[str]] = None, + nodes_visited_details: Optional[ + List['DialogNodeVisitedDetails']] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a OutputData object. @@ -8047,41 +9289,56 @@ def __init__(self, :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included with the + output. """ self.nodes_visited = nodes_visited self.nodes_visited_details = nodes_visited_details self.log_messages = log_messages self.generic = generic - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in OutputData._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'OutputData': """Initialize a OutputData object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = _dict.get('nodes_visited') - if 'nodes_visited_details' in _dict: + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = nodes_visited + if (nodes_visited_details := + _dict.get('nodes_visited_details')) is not None: args['nodes_visited_details'] = [ - DialogNodeVisitedDetails.from_dict(x) - for x in _dict.get('nodes_visited_details') + DialogNodeVisitedDetails.from_dict(v) + for v in nodes_visited_details ] - if 'log_messages' in _dict: + if (log_messages := _dict.get('log_messages')) is not None: args['log_messages'] = [ - LogMessage.from_dict(x) for x in _dict.get('log_messages') + LogMessage.from_dict(v) for v in log_messages ] else: raise ValueError( 'Required property \'log_messages\' not present in OutputData JSON' ) - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') + RuntimeResponseGeneric.from_dict(v) for v in generic ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -8096,18 +9353,34 @@ def to_dict(self) -> Dict: _dict['nodes_visited'] = self.nodes_visited if hasattr(self, 'nodes_visited_details' ) and self.nodes_visited_details is not None: - _dict['nodes_visited_details'] = [ - x.to_dict() for x in self.nodes_visited_details - ] + nodes_visited_details_list = [] + for v in self.nodes_visited_details: + if isinstance(v, dict): + nodes_visited_details_list.append(v) + else: + nodes_visited_details_list.append(v.to_dict()) + _dict['nodes_visited_details'] = nodes_visited_details_list if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -8115,25 +9388,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of OutputData""" + """Return the additional properties from this instance of OutputData in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of OutputData""" - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + """Set a dictionary of additional properties in this instance of OutputData""" + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in OutputData._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in OutputData._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this OutputData object.""" @@ -8150,30 +9431,33 @@ def __ne__(self, other: 'OutputData') -> bool: return not self == other -class Pagination(): +class Pagination: """ - The pagination data for the returned objects. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of results. - :attr int total: (optional) The total number of objects that satisfy the + :param int total: (optional) The total number of objects that satisfy the request. This total includes all results, not just those included in the current page. - :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of results. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - refresh_url: str, - *, - next_url: str = None, - total: int = None, - matched: int = None, - refresh_cursor: str = None, - next_cursor: str = None) -> None: + def __init__( + self, + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a Pagination object. @@ -8200,22 +9484,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url else: raise ValueError( 'Required property \'refresh_url\' not present in Pagination JSON' ) - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -8259,19 +9543,25 @@ def __ne__(self, other: 'Pagination') -> bool: return not self == other -class ResponseGenericChannel(): +class ResponseGenericChannel: """ ResponseGenericChannel. - :attr str channel: (optional) A channel for which the response is intended. + :param str channel: (optional) A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: """ Initialize a ResponseGenericChannel object. :param str channel: (optional) A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ self.channel = channel @@ -8279,8 +9569,8 @@ def __init__(self, *, channel: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': """Initialize a ResponseGenericChannel object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel return cls(**args) @classmethod @@ -8316,7 +9606,9 @@ def __ne__(self, other: 'ResponseGenericChannel') -> bool: class ChannelEnum(str, Enum): """ A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ + CHAT = 'chat' FACEBOOK = 'facebook' INTERCOM = 'intercom' @@ -8326,44 +9618,46 @@ class ChannelEnum(str, Enum): WHATSAPP = 'whatsapp' -class RuntimeEntity(): +class RuntimeEntity: """ A term from the request that was identified as an entity. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. - :attr str value: The entity value that was recognized in the user input. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param str value: The entity value that was recognized in the user input. + :param float confidence: (optional) A decimal percentage that represents confidence in the recognized entity. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object + :param RuntimeEntityInterpretation interpretation: (optional) An object containing detailed information about the entity recognized in the user input. For more information about how system entities are interpreted, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-system-entities). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of possible alternative values that the user might have intended instead of the value returned in the **value** property. This property is returned only for `@sys-time` and `@sys-date` entities when the user's input is ambiguous. This property is included only if the new system entities are enabled for the workspace. - :attr RuntimeEntityRole role: (optional) An object describing the role played by - a system entity that is specifies the beginning or end of a range recognized in - the user input. This property is included only if the new system entities are + :param RuntimeEntityRole role: (optional) An object describing the role played + by a system entity that is specifies the beginning or end of a range recognized + in the user input. This property is included only if the new system entities are enabled for the workspace. """ - def __init__(self, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None) -> None: + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + ) -> None: """ Initialize a RuntimeEntity object. @@ -8373,7 +9667,7 @@ def __init__(self, offsets that indicate where the detected entity values begin and end in the input text. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized entity. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -8406,35 +9700,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(x) for x in _dict.get('groups') - ] - if 'interpretation' in _dict: + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(x) - for x in _dict.get('alternatives') + RuntimeEntityAlternative.from_dict(v) for v in alternatives ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) return cls(**args) @classmethod @@ -8454,13 +9745,31 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x.to_dict() for x in self.groups] + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role.to_dict() + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() return _dict def _to_dict(self): @@ -8482,24 +9791,29 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other -class RuntimeEntityAlternative(): +class RuntimeEntityAlternative: """ An alternative value for the recognized entity. - :attr str value: (optional) The entity value that was recognized in the user + :param str value: (optional) The entity value that was recognized in the user input. - :attr float confidence: (optional) A decimal percentage that represents Watson's + :param float confidence: (optional) A decimal percentage that represents confidence in the recognized entity. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeEntityAlternative object. :param str value: (optional) The entity value that was recognized in the user input. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized entity. """ self.value = value self.confidence = confidence @@ -8508,10 +9822,10 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': """Initialize a RuntimeEntityAlternative object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -8547,108 +9861,110 @@ def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: return not self == other -class RuntimeEntityInterpretation(): +class RuntimeEntityInterpretation: """ RuntimeEntityInterpretation. - :attr str calendar_type: (optional) The calendar used to represent a recognized + :param str calendar_type: (optional) The calendar used to represent a recognized date (for example, `Gregorian`). - :attr str datetime_link: (optional) A unique identifier used to associate a + :param str datetime_link: (optional) A unique identifier used to associate a recognized time and date. If the user input contains a date and time that are mentioned together (for example, `Today at 5`, the same **datetime_link** value is returned for both the `@sys-date` and `@sys-time` entities). - :attr str festival: (optional) A locale-specific holiday name (such as + :param str festival: (optional) A locale-specific holiday name (such as `thanksgiving` or `christmas`). This property is included when a `@sys-date` entity is recognized based on a holiday name in the user input. - :attr str granularity: (optional) The precision or duration of a time range + :param str granularity: (optional) The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - :attr str range_link: (optional) A unique identifier used to associate multiple + :param str range_link: (optional) A unique identifier used to associate multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are recognized as a range of values in the user's input (for example, `from July 4 until July 14` or `from 20 to 25`). - :attr str range_modifier: (optional) The word in the user input that indicates + :param str range_modifier: (optional) The word in the user input that indicates that a `sys-date` or `sys-time` entity is part of an implied range where only one date or time is specified (for example, `since` or `until`). - :attr float relative_day: (optional) A recognized mention of a relative day, + :param float relative_day: (optional) A recognized mention of a relative day, represented numerically as an offset from the current date (for example, `-1` for `yesterday` or `10` for `in ten days`). - :attr float relative_month: (optional) A recognized mention of a relative month, - represented numerically as an offset from the current month (for example, `1` - for `next month` or `-3` for `three months ago`). - :attr float relative_week: (optional) A recognized mention of a relative week, + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for example, + `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative week, represented numerically as an offset from the current week (for example, `2` for `in two weeks` or `-1` for `last week). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current + :param float relative_weekend: (optional) A recognized mention of a relative + date range for a weekend, represented numerically as an offset from the current weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). - :attr float relative_year: (optional) A recognized mention of a relative year, + :param float relative_year: (optional) A recognized mention of a relative year, represented numerically as an offset from the current year (for example, `1` for `next year` or `-5` for `five years ago`). - :attr float specific_day: (optional) A recognized mention of a specific date, + :param float specific_day: (optional) A recognized mention of a specific date, represented numerically as the date within the month (for example, `30` for `June 30`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific + :param str specific_day_of_week: (optional) A recognized mention of a specific day of the week as a lowercase string (for example, `monday`). - :attr float specific_month: (optional) A recognized mention of a specific month, - represented numerically (for example, `7` for `July`). - :attr float specific_quarter: (optional) A recognized mention of a specific + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a specific quarter, represented numerically (for example, `3` for `the third quarter`). - :attr float specific_year: (optional) A recognized mention of a specific year + :param float specific_year: (optional) A recognized mention of a specific year (for example, `2016`). - :attr float numeric_value: (optional) A recognized numeric value, represented as - an integer or double. - :attr str subtype: (optional) The type of numeric value recognized in the user + :param float numeric_value: (optional) A recognized numeric value, represented + as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the user input (`integer` or `rational`). - :attr str part_of_day: (optional) A recognized term for a time that was + :param str part_of_day: (optional) A recognized term for a time that was mentioned as a part of the day in the user's input (for example, `morning` or `afternoon`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, + :param float relative_hour: (optional) A recognized mention of a relative hour, represented numerically as an offset from the current hour (for example, `3` for `in three hours` or `-1` for `an hour ago`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time (for example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as + :param float specific_hour: (optional) A recognized specific hour mentioned as part of a time value (for example, `10` for `10:15 AM`.). - :attr float specific_minute: (optional) A recognized specific minute mentioned + :param float specific_minute: (optional) A recognized specific minute mentioned as part of a time value (for example, `15` for `10:15 AM`.). - :attr float specific_second: (optional) A recognized specific second mentioned + :param float specific_second: (optional) A recognized specific second mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - :attr str timezone: (optional) A recognized time zone mentioned as part of a + :param str timezone: (optional) A recognized time zone mentioned as part of a time value (for example, `EST`). """ - def __init__(self, - *, - calendar_type: str = None, - datetime_link: str = None, - festival: str = None, - granularity: str = None, - range_link: str = None, - range_modifier: str = None, - relative_day: float = None, - relative_month: float = None, - relative_week: float = None, - relative_weekend: float = None, - relative_year: float = None, - specific_day: float = None, - specific_day_of_week: str = None, - specific_month: float = None, - specific_quarter: float = None, - specific_year: float = None, - numeric_value: float = None, - subtype: str = None, - part_of_day: str = None, - relative_hour: float = None, - relative_minute: float = None, - relative_second: float = None, - specific_hour: float = None, - specific_minute: float = None, - specific_second: float = None, - timezone: str = None) -> None: + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityInterpretation object. @@ -8757,58 +10073,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" args = {} - if 'calendar_type' in _dict: - args['calendar_type'] = _dict.get('calendar_type') - if 'datetime_link' in _dict: - args['datetime_link'] = _dict.get('datetime_link') - if 'festival' in _dict: - args['festival'] = _dict.get('festival') - if 'granularity' in _dict: - args['granularity'] = _dict.get('granularity') - if 'range_link' in _dict: - args['range_link'] = _dict.get('range_link') - if 'range_modifier' in _dict: - args['range_modifier'] = _dict.get('range_modifier') - if 'relative_day' in _dict: - args['relative_day'] = _dict.get('relative_day') - if 'relative_month' in _dict: - args['relative_month'] = _dict.get('relative_month') - if 'relative_week' in _dict: - args['relative_week'] = _dict.get('relative_week') - if 'relative_weekend' in _dict: - args['relative_weekend'] = _dict.get('relative_weekend') - if 'relative_year' in _dict: - args['relative_year'] = _dict.get('relative_year') - if 'specific_day' in _dict: - args['specific_day'] = _dict.get('specific_day') - if 'specific_day_of_week' in _dict: - args['specific_day_of_week'] = _dict.get('specific_day_of_week') - if 'specific_month' in _dict: - args['specific_month'] = _dict.get('specific_month') - if 'specific_quarter' in _dict: - args['specific_quarter'] = _dict.get('specific_quarter') - if 'specific_year' in _dict: - args['specific_year'] = _dict.get('specific_year') - if 'numeric_value' in _dict: - args['numeric_value'] = _dict.get('numeric_value') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') - if 'part_of_day' in _dict: - args['part_of_day'] = _dict.get('part_of_day') - if 'relative_hour' in _dict: - args['relative_hour'] = _dict.get('relative_hour') - if 'relative_minute' in _dict: - args['relative_minute'] = _dict.get('relative_minute') - if 'relative_second' in _dict: - args['relative_second'] = _dict.get('relative_second') - if 'specific_hour' in _dict: - args['specific_hour'] = _dict.get('specific_hour') - if 'specific_minute' in _dict: - args['specific_minute'] = _dict.get('specific_minute') - if 'specific_second' in _dict: - args['specific_second'] = _dict.get('specific_second') - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone return cls(**args) @classmethod @@ -8903,6 +10220,7 @@ class GranularityEnum(str, Enum): The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. """ + DAY = 'day' FORTNIGHT = 'fortnight' HOUR = 'hour' @@ -8916,16 +10234,20 @@ class GranularityEnum(str, Enum): YEAR = 'year' -class RuntimeEntityRole(): +class RuntimeEntityRole: """ An object describing the role played by a system entity that is specifies the beginning or end of a range recognized in the user input. This property is included only if the new system entities are enabled for the workspace. - :attr str type: (optional) The relationship of the entity to the range. + :param str type: (optional) The relationship of the entity to the range. """ - def __init__(self, *, type: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityRole object. @@ -8937,8 +10259,8 @@ def __init__(self, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': """Initialize a RuntimeEntityRole object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -8975,6 +10297,7 @@ class TypeEnum(str, Enum): """ The relationship of the entity to the range. """ + DATE_FROM = 'date_from' DATE_TO = 'date_to' NUMBER_FROM = 'number_from' @@ -8983,22 +10306,29 @@ class TypeEnum(str, Enum): TIME_TO = 'time_to' -class RuntimeIntent(): +class RuntimeIntent: """ An intent identified in the user input. - :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. """ self.intent = intent self.confidence = confidence @@ -9007,18 +10337,14 @@ def __init__(self, intent: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' - ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9054,13 +10380,13 @@ def __ne__(self, other: 'RuntimeIntent') -> bool: return not self == other -class RuntimeResponseGeneric(): +class RuntimeResponseGeneric: """ RuntimeResponseGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -9087,80 +10413,139 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' + ])) raise Exception(msg) - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class StatusError: + """ + An object describing an error that occurred during processing of an asynchronous + operation. + + :param str message: (optional) The text of the error message. + """ + + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: + """ + Initialize a StatusError object. + + :param str message: (optional) The text of the error message. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" + args = {} + if (message := _dict.get('message')) is not None: + args['message'] = message + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatusError object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatusError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatusError') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) + def __ne__(self, other: 'StatusError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other -class Synonym(): +class Synonym: """ Synonym. - :attr str synonym: The text of the synonym. This string must conform to the + :param str synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - synonym: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + synonym: str, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Synonym object. @@ -9177,15 +10562,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Synonym': """Initialize a Synonym object from a json dictionary.""" args = {} - if 'synonym' in _dict: - args['synonym'] = _dict.get('synonym') + if (synonym := _dict.get('synonym')) is not None: + args['synonym'] = synonym else: raise ValueError( 'Required property \'synonym\' not present in Synonym JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -9223,21 +10608,26 @@ def __ne__(self, other: 'Synonym') -> bool: return not self == other -class SynonymCollection(): +class SynonymCollection: """ SynonymCollection. - :attr List[Synonym] synonyms: An array of synonyms. - :attr Pagination pagination: The pagination data for the returned objects. + :param List[Synonym] synonyms: An array of synonyms. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, synonyms: List['Synonym'], - pagination: 'Pagination') -> None: + def __init__( + self, + synonyms: List['Synonym'], + pagination: 'Pagination', + ) -> None: """ Initialize a SynonymCollection object. :param List[Synonym] synonyms: An array of synonyms. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.synonyms = synonyms self.pagination = pagination @@ -9246,16 +10636,14 @@ def __init__(self, synonyms: List['Synonym'], def from_dict(cls, _dict: Dict) -> 'SynonymCollection': """Initialize a SynonymCollection object from a json dictionary.""" args = {} - if 'synonyms' in _dict: - args['synonyms'] = [ - Synonym.from_dict(x) for x in _dict.get('synonyms') - ] + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = [Synonym.from_dict(v) for v in synonyms] else: raise ValueError( 'Required property \'synonyms\' not present in SynonymCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in SynonymCollection JSON' @@ -9271,9 +10659,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonyms') and self.synonyms is not None: - _dict['synonyms'] = [x.to_dict() for x in self.synonyms] + synonyms_list = [] + for v in self.synonyms: + if isinstance(v, dict): + synonyms_list.append(v) + else: + synonyms_list.append(v.to_dict()) + _dict['synonyms'] = synonyms_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9295,40 +10692,42 @@ def __ne__(self, other: 'SynonymCollection') -> bool: return not self == other -class Value(): +class Value: """ Value. - :attr str value: The text of the entity value. This string must conform to the + :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param str type: Specifies the type of entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the entity value. + :param List[str] patterns: (optional) An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A pattern is a regular expression; for more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-entities#entities-create-dictionary-based). - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - value: str, - type: str, - *, - metadata: dict = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + value: str, + type: str, + *, + metadata: Optional[dict] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Value object. @@ -9362,26 +10761,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in Value JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in Value JSON') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = synonyms + if (patterns := _dict.get('patterns')) is not None: + args['patterns'] = patterns + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -9430,24 +10829,31 @@ class TypeEnum(str, Enum): """ Specifies the type of entity value. """ + SYNONYMS = 'synonyms' PATTERNS = 'patterns' -class ValueCollection(): +class ValueCollection: """ ValueCollection. - :attr List[Value] values: An array of entity values. - :attr Pagination pagination: The pagination data for the returned objects. + :param List[Value] values: An array of entity values. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: + def __init__( + self, + values: List['Value'], + pagination: 'Pagination', + ) -> None: """ Initialize a ValueCollection object. :param List[Value] values: An array of entity values. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.values = values self.pagination = pagination @@ -9456,14 +10862,14 @@ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} - if 'values' in _dict: - args['values'] = [Value.from_dict(x) for x in _dict.get('values')] + if (values := _dict.get('values')) is not None: + args['values'] = [Value.from_dict(v) for v in values] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ValueCollection JSON' @@ -9479,9 +10885,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9503,25 +10918,27 @@ def __ne__(self, other: 'ValueCollection') -> bool: return not self == other -class Webhook(): +class Webhook: """ A webhook that can be used by dialog nodes to make programmatic calls to an external function. **Note:** Currently, only a single webhook named `main_webhook` is supported. - :attr str url: The URL for the external service or application to which you want - to send HTTP POST requests. - :attr str name: The name of the webhook. Currently, `main_webhook` is the only + :param str url: The URL for the external service or application to which you + want to send HTTP POST requests. + :param str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :attr List[WebhookHeader] headers_: (optional) An optional array of HTTP headers - to pass with the HTTP request. + :param List[WebhookHeader] headers_: (optional) An optional array of HTTP + headers to pass with the HTTP request. """ - def __init__(self, - url: str, - name: str, - *, - headers_: List['WebhookHeader'] = None) -> None: + def __init__( + self, + url: str, + name: str, + *, + headers_: Optional[List['WebhookHeader']] = None, + ) -> None: """ Initialize a Webhook object. @@ -9540,20 +10957,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Webhook': """Initialize a Webhook object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in Webhook JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Webhook JSON') - if 'headers' in _dict: - args['headers_'] = [ - WebhookHeader.from_dict(x) for x in _dict.get('headers') - ] + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = [WebhookHeader.from_dict(v) for v in headers_] return cls(**args) @classmethod @@ -9569,7 +10984,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'headers_') and self.headers_ is not None: - _dict['headers'] = [x.to_dict() for x in self.headers_] + headers_list = [] + for v in self.headers_: + if isinstance(v, dict): + headers_list.append(v) + else: + headers_list.append(v.to_dict()) + _dict['headers'] = headers_list return _dict def _to_dict(self): @@ -9591,15 +11012,19 @@ def __ne__(self, other: 'Webhook') -> bool: return not self == other -class WebhookHeader(): +class WebhookHeader: """ A key/value pair defining an HTTP header and a value. - :attr str name: The name of an HTTP header (for example, `Authorization`). - :attr str value: The value of an HTTP header. + :param str name: The name of an HTTP header (for example, `Authorization`). + :param str value: The value of an HTTP header. """ - def __init__(self, name: str, value: str) -> None: + def __init__( + self, + name: str, + value: str, + ) -> None: """ Initialize a WebhookHeader object. @@ -9613,13 +11038,13 @@ def __init__(self, name: str, value: str) -> None: def from_dict(cls, _dict: Dict) -> 'WebhookHeader': """Initialize a WebhookHeader object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in WebhookHeader JSON') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in WebhookHeader JSON') @@ -9658,53 +11083,72 @@ def __ne__(self, other: 'WebhookHeader') -> bool: return not self == other -class Workspace(): +class Workspace: """ Workspace. - :attr str name: The name of the workspace. This string cannot contain carriage + :param str name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the workspace. This string + :param str description: (optional) The description of the workspace. This string cannot contain carriage return, newline, or tab characters. - :attr str language: The language of the workspace. - :attr str workspace_id: (optional) The workspace ID of the workspace. - :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing + :param str language: The language of the workspace. + :param str workspace_id: (optional) The workspace ID of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :attr List[Counterexample] counterexamples: (optional) An array of objects + :param List[Counterexample] counterexamples: (optional) An array of objects defining input examples that have been marked as irrelevant input. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr dict metadata: (optional) Any metadata related to the workspace. - :attr bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :attr WorkspaceSystemSettings system_settings: (optional) Global settings for + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: Whether training data from the workspace + (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data is + not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :attr str status: (optional) The current status of the workspace. - :attr List[Webhook] webhooks: (optional) - :attr List[Intent] intents: (optional) An array of intents. - :attr List[Entity] entities: (optional) An array of objects describing the + :param str status: (optional) The current status of the workspace: + - **Available**: The workspace is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The workspace does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The workspace is training based on new data such as intents or + examples. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. + :param List[Webhook] webhooks: (optional) + :param List[Intent] intents: (optional) An array of intents. + :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. + :param WorkspaceCounts counts: (optional) An object containing properties that + indicate how many intents, entities, and dialog nodes are defined in the + workspace. This property is included only in responses from the **Export + workspace asynchronously** method, and only when the **verbose** query parameter + is set to `true`. """ - def __init__(self, - name: str, - language: str, - learning_opt_out: bool, - *, - description: str = None, - workspace_id: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - created: datetime = None, - updated: datetime = None, - metadata: dict = None, - system_settings: 'WorkspaceSystemSettings' = None, - status: str = None, - webhooks: List['Webhook'] = None, - intents: List['Intent'] = None, - entities: List['Entity'] = None) -> None: + def __init__( + self, + name: str, + language: str, + learning_opt_out: bool, + *, + description: Optional[str] = None, + workspace_id: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + metadata: Optional[dict] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['Intent']] = None, + entities: Optional[List['Entity']] = None, + counts: Optional['WorkspaceCounts'] = None, + ) -> None: """ Initialize a Workspace object. @@ -9741,66 +11185,67 @@ def __init__(self, self.learning_opt_out = learning_opt_out self.system_settings = system_settings self.status = status + self.status_errors = status_errors self.webhooks = webhooks self.intents = intents self.entities = entities + self.counts = counts @classmethod def from_dict(cls, _dict: Dict) -> 'Workspace': """Initialize a Workspace object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Workspace JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Workspace JSON') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'dialog_nodes' in _dict: + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (dialog_nodes := _dict.get('dialog_nodes')) is not None: args['dialog_nodes'] = [ - DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in dialog_nodes ] - if 'counterexamples' in _dict: + if (counterexamples := _dict.get('counterexamples')) is not None: args['counterexamples'] = [ - Counterexample.from_dict(x) - for x in _dict.get('counterexamples') + Counterexample.from_dict(v) for v in counterexamples ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'learning_opt_out' in _dict: - args['learning_opt_out'] = _dict.get('learning_opt_out') + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (learning_opt_out := _dict.get('learning_opt_out')) is not None: + args['learning_opt_out'] = learning_opt_out else: raise ValueError( 'Required property \'learning_opt_out\' not present in Workspace JSON' ) - if 'system_settings' in _dict: + if (system_settings := _dict.get('system_settings')) is not None: args['system_settings'] = WorkspaceSystemSettings.from_dict( - _dict.get('system_settings')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'webhooks' in _dict: - args['webhooks'] = [ - Webhook.from_dict(x) for x in _dict.get('webhooks') - ] - if 'intents' in _dict: - args['intents'] = [ - Intent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - Entity.from_dict(x) for x in _dict.get('entities') + system_settings) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors ] + if (webhooks := _dict.get('webhooks')) is not None: + args['webhooks'] = [Webhook.from_dict(v) for v in webhooks] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [Intent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [Entity.from_dict(v) for v in entities] + if (counts := _dict.get('counts')) is not None: + args['counts'] = WorkspaceCounts.from_dict(counts) return cls(**args) @classmethod @@ -9821,12 +11266,22 @@ def to_dict(self) -> Dict: self, 'workspace_id') is not None: _dict['workspace_id'] = getattr(self, 'workspace_id') if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] + dialog_nodes_list = [] + for v in self.dialog_nodes: + if isinstance(v, dict): + dialog_nodes_list.append(v) + else: + dialog_nodes_list.append(v.to_dict()) + _dict['dialog_nodes'] = dialog_nodes_list if hasattr(self, 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x.to_dict() for x in self.counterexamples - ] + counterexamples_list = [] + for v in self.counterexamples: + if isinstance(v, dict): + counterexamples_list.append(v) + else: + counterexamples_list.append(v.to_dict()) + _dict['counterexamples'] = counterexamples_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -9838,15 +11293,50 @@ def to_dict(self) -> Dict: _dict['learning_opt_out'] = self.learning_opt_out if hasattr(self, 'system_settings') and self.system_settings is not None: - _dict['system_settings'] = self.system_settings.to_dict() + if isinstance(self.system_settings, dict): + _dict['system_settings'] = self.system_settings + else: + _dict['system_settings'] = self.system_settings.to_dict() if hasattr(self, 'status') and getattr(self, 'status') is not None: _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list if hasattr(self, 'webhooks') and self.webhooks is not None: - _dict['webhooks'] = [x.to_dict() for x in self.webhooks] + webhooks_list = [] + for v in self.webhooks: + if isinstance(v, dict): + webhooks_list.append(v) + else: + webhooks_list.append(v.to_dict()) + _dict['webhooks'] = webhooks_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'counts') and getattr(self, 'counts') is not None: + if isinstance(getattr(self, 'counts'), dict): + _dict['counts'] = getattr(self, 'counts') + else: + _dict['counts'] = getattr(self, 'counts').to_dict() return _dict def _to_dict(self): @@ -9869,32 +11359,46 @@ def __ne__(self, other: 'Workspace') -> bool: class StatusEnum(str, Enum): """ - The current status of the workspace. + The current status of the workspace: + - **Available**: The workspace is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The workspace does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The workspace is training based on new data such as intents or + examples. """ + + AVAILABLE = 'Available' + FAILED = 'Failed' NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' TRAINING = 'Training' - FAILED = 'Failed' - AVAILABLE = 'Available' UNAVAILABLE = 'Unavailable' -class WorkspaceCollection(): +class WorkspaceCollection: """ WorkspaceCollection. - :attr List[Workspace] workspaces: An array of objects describing the workspaces + :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. - :attr Pagination pagination: The pagination data for the returned objects. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, workspaces: List['Workspace'], - pagination: 'Pagination') -> None: + def __init__( + self, + workspaces: List['Workspace'], + pagination: 'Pagination', + ) -> None: """ Initialize a WorkspaceCollection object. :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.workspaces = workspaces self.pagination = pagination @@ -9903,16 +11407,14 @@ def __init__(self, workspaces: List['Workspace'], def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} - if 'workspaces' in _dict: - args['workspaces'] = [ - Workspace.from_dict(x) for x in _dict.get('workspaces') - ] + if (workspaces := _dict.get('workspaces')) is not None: + args['workspaces'] = [Workspace.from_dict(v) for v in workspaces] else: raise ValueError( 'Required property \'workspaces\' not present in WorkspaceCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in WorkspaceCollection JSON' @@ -9928,9 +11430,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'workspaces') and self.workspaces is not None: - _dict['workspaces'] = [x.to_dict() for x in self.workspaces] + workspaces_list = [] + for v in self.workspaces: + if isinstance(v, dict): + workspaces_list.append(v) + else: + workspaces_list.append(v.to_dict()) + _dict['workspaces'] = workspaces_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9952,47 +11463,134 @@ def __ne__(self, other: 'WorkspaceCollection') -> bool: return not self == other -class WorkspaceSystemSettings(): +class WorkspaceCounts: + """ + An object containing properties that indicate how many intents, entities, and dialog + nodes are defined in the workspace. This property is included only in responses from + the **Export workspace asynchronously** method, and only when the **verbose** query + parameter is set to `true`. + + :param int intent: (optional) The number of intents defined in the workspace. + :param int entity: (optional) The number of entities defined in the workspace. + :param int node: (optional) The number of nodes defined in the workspace. + """ + + def __init__( + self, + *, + intent: Optional[int] = None, + entity: Optional[int] = None, + node: Optional[int] = None, + ) -> None: + """ + Initialize a WorkspaceCounts object. + + :param int intent: (optional) The number of intents defined in the + workspace. + :param int entity: (optional) The number of entities defined in the + workspace. + :param int node: (optional) The number of nodes defined in the workspace. + """ + self.intent = intent + self.entity = entity + self.node = node + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceCounts': + """Initialize a WorkspaceCounts object from a json dictionary.""" + args = {} + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + if (node := _dict.get('node')) is not None: + args['node'] = node + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceCounts object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'node') and self.node is not None: + _dict['node'] = self.node + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this WorkspaceCounts object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceCounts') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'WorkspaceCounts') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class WorkspaceSystemSettings: """ Global settings for the workspace. - :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings + :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings related to the Watson Assistant user interface. - :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace - settings related to the disambiguation feature. - :attr dict human_agent_assist: (optional) For internal use only. - :attr bool spelling_suggestions: (optional) Whether spelling correction is + :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) + Workspace settings related to the disambiguation feature. + :param dict human_agent_assist: (optional) For internal use only. + :param bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. - :attr bool spelling_auto_correct: (optional) Whether autocorrection is enabled + :param bool spelling_auto_correct: (optional) Whether autocorrection is enabled for the workspace. If spelling correction is enabled and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **original_text** property of the message response. - :attr WorkspaceSystemSettingsSystemEntities system_entities: (optional) + :param WorkspaceSystemSettingsSystemEntities system_entities: (optional) Workspace settings related to the behavior of system entities. - :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings + :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. + :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to + the version of the training algorithms currently used by the skill. + + This type supports additional properties of type object. For internal use only. """ # The set of defined properties for the class _properties = frozenset([ 'tooling', 'disambiguation', 'human_agent_assist', 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', - 'off_topic' + 'off_topic', 'nlp' ]) def __init__( - self, - *, - tooling: 'WorkspaceSystemSettingsTooling' = None, - disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, - human_agent_assist: dict = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, - off_topic: 'WorkspaceSystemSettingsOffTopic' = None, - **kwargs) -> None: + self, + *, + tooling: Optional['WorkspaceSystemSettingsTooling'] = None, + disambiguation: Optional[ + 'WorkspaceSystemSettingsDisambiguation'] = None, + human_agent_assist: Optional[dict] = None, + spelling_suggestions: Optional[bool] = None, + spelling_auto_correct: Optional[bool] = None, + system_entities: Optional[ + 'WorkspaceSystemSettingsSystemEntities'] = None, + off_topic: Optional['WorkspaceSystemSettingsOffTopic'] = None, + nlp: Optional['WorkspaceSystemSettingsNlp'] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -10014,7 +11612,10 @@ def __init__( Workspace settings related to the behavior of system entities. :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. - :param **kwargs: (optional) Any additional properties. + :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings + related to the version of the training algorithms currently used by the + skill. + :param object **kwargs: (optional) For internal use only. """ self.tooling = tooling self.disambiguation = disambiguation @@ -10023,35 +11624,53 @@ def __init__( self.spelling_auto_correct = spelling_auto_correct self.system_entities = system_entities self.off_topic = off_topic - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.nlp = nlp + for k, v in kwargs.items(): + if k not in WorkspaceSystemSettings._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} - if 'tooling' in _dict: - args['tooling'] = WorkspaceSystemSettingsTooling.from_dict( - _dict.get('tooling')) - if 'disambiguation' in _dict: + if (tooling := _dict.get('tooling')) is not None: + args['tooling'] = WorkspaceSystemSettingsTooling.from_dict(tooling) + if (disambiguation := _dict.get('disambiguation')) is not None: args[ 'disambiguation'] = WorkspaceSystemSettingsDisambiguation.from_dict( - _dict.get('disambiguation')) - if 'human_agent_assist' in _dict: - args['human_agent_assist'] = _dict.get('human_agent_assist') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - if 'system_entities' in _dict: + disambiguation) + if (human_agent_assist := _dict.get('human_agent_assist')) is not None: + args['human_agent_assist'] = human_agent_assist + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (spelling_auto_correct := + _dict.get('spelling_auto_correct')) is not None: + args['spelling_auto_correct'] = spelling_auto_correct + if (system_entities := _dict.get('system_entities')) is not None: args[ 'system_entities'] = WorkspaceSystemSettingsSystemEntities.from_dict( - _dict.get('system_entities')) - if 'off_topic' in _dict: + system_entities) + if (off_topic := _dict.get('off_topic')) is not None: args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( - _dict.get('off_topic')) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + off_topic) + if (nlp := _dict.get('nlp')) is not None: + args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(nlp) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -10063,9 +11682,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tooling') and self.tooling is not None: - _dict['tooling'] = self.tooling.to_dict() + if isinstance(self.tooling, dict): + _dict['tooling'] = self.tooling + else: + _dict['tooling'] = self.tooling.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation.to_dict() + if isinstance(self.disambiguation, dict): + _dict['disambiguation'] = self.disambiguation + else: + _dict['disambiguation'] = self.disambiguation.to_dict() if hasattr( self, 'human_agent_assist') and self.human_agent_assist is not None: @@ -10078,15 +11703,25 @@ def to_dict(self) -> Dict: _dict['spelling_auto_correct'] = self.spelling_auto_correct if hasattr(self, 'system_entities') and self.system_entities is not None: - _dict['system_entities'] = self.system_entities.to_dict() + if isinstance(self.system_entities, dict): + _dict['system_entities'] = self.system_entities + else: + _dict['system_entities'] = self.system_entities.to_dict() if hasattr(self, 'off_topic') and self.off_topic is not None: - _dict['off_topic'] = self.off_topic.to_dict() - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + if isinstance(self.off_topic, dict): + _dict['off_topic'] = self.off_topic + else: + _dict['off_topic'] = self.off_topic.to_dict() + if hasattr(self, 'nlp') and self.nlp is not None: + if isinstance(self.nlp, dict): + _dict['nlp'] = self.nlp + else: + _dict['nlp'] = self.nlp.to_dict() + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -10094,27 +11729,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of WorkspaceSystemSettings""" + """Return the additional properties from this instance of WorkspaceSystemSettings in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of WorkspaceSystemSettings""" - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + """Set a dictionary of additional properties in this instance of WorkspaceSystemSettings""" + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in WorkspaceSystemSettings._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in WorkspaceSystemSettings._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettings object.""" @@ -10131,37 +11772,39 @@ def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: return not self == other -class WorkspaceSystemSettingsDisambiguation(): +class WorkspaceSystemSettingsDisambiguation: """ Workspace settings related to the disambiguation feature. - :attr str prompt: (optional) The text of the introductory prompt that + :param str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. - :attr str none_of_the_above_prompt: (optional) The user-facing label for the + :param str none_of_the_above_prompt: (optional) The user-facing label for the option users can select if none of the suggested options is correct. If no value is specified for this property, this option does not appear. - :attr bool enabled: (optional) Whether the disambiguation feature is enabled for - the workspace. - :attr str sensitivity: (optional) The sensitivity of the disambiguation feature + :param bool enabled: (optional) Whether the disambiguation feature is enabled + for the workspace. + :param str sensitivity: (optional) The sensitivity of the disambiguation feature to intent detection uncertainty. Higher sensitivity means that the disambiguation feature is triggered more often and includes more choices. - :attr bool randomize: (optional) Whether the order in which disambiguation + :param bool randomize: (optional) Whether the order in which disambiguation suggestions are presented should be randomized (but still influenced by relative confidence). - :attr int max_suggestions: (optional) The maximum number of disambigation + :param int max_suggestions: (optional) The maximum number of disambigation suggestions that can be included in a `suggestion` response. - :attr str suggestion_text_policy: (optional) For internal use only. + :param str suggestion_text_policy: (optional) For internal use only. """ - def __init__(self, - *, - prompt: str = None, - none_of_the_above_prompt: str = None, - enabled: bool = None, - sensitivity: str = None, - randomize: bool = None, - max_suggestions: int = None, - suggestion_text_policy: str = None) -> None: + def __init__( + self, + *, + prompt: Optional[str] = None, + none_of_the_above_prompt: Optional[str] = None, + enabled: Optional[bool] = None, + sensitivity: Optional[str] = None, + randomize: Optional[bool] = None, + max_suggestions: Optional[int] = None, + suggestion_text_policy: Optional[str] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsDisambiguation object. @@ -10194,21 +11837,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') - if 'none_of_the_above_prompt' in _dict: - args['none_of_the_above_prompt'] = _dict.get( - 'none_of_the_above_prompt') - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'sensitivity' in _dict: - args['sensitivity'] = _dict.get('sensitivity') - if 'randomize' in _dict: - args['randomize'] = _dict.get('randomize') - if 'max_suggestions' in _dict: - args['max_suggestions'] = _dict.get('max_suggestions') - if 'suggestion_text_policy' in _dict: - args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt + if (none_of_the_above_prompt := + _dict.get('none_of_the_above_prompt')) is not None: + args['none_of_the_above_prompt'] = none_of_the_above_prompt + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (sensitivity := _dict.get('sensitivity')) is not None: + args['sensitivity'] = sensitivity + if (randomize := _dict.get('randomize')) is not None: + args['randomize'] = randomize + if (max_suggestions := _dict.get('max_suggestions')) is not None: + args['max_suggestions'] = max_suggestions + if (suggestion_text_policy := + _dict.get('suggestion_text_policy')) is not None: + args['suggestion_text_policy'] = suggestion_text_policy return cls(**args) @classmethod @@ -10262,6 +11906,7 @@ class SensitivityEnum(str, Enum): Higher sensitivity means that the disambiguation feature is triggered more often and includes more choices. """ + AUTO = 'auto' HIGH = 'high' MEDIUM_HIGH = 'medium_high' @@ -10270,15 +11915,88 @@ class SensitivityEnum(str, Enum): LOW = 'low' -class WorkspaceSystemSettingsOffTopic(): +class WorkspaceSystemSettingsNlp: + """ + Workspace settings related to the version of the training algorithms currently used by + the skill. + + :param str model: (optional) The policy the skill follows for selecting the + algorithm version to use. For more information, see the + [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). + On IBM Cloud, you can specify `latest`, `previous`, or `beta`. + On IBM Cloud Pak for Data, you can specify either `beta` or the date of the + version you want to use, in `YYYY-MM-DD` format. + """ + + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: + """ + Initialize a WorkspaceSystemSettingsNlp object. + + :param str model: (optional) The policy the skill follows for selecting the + algorithm version to use. For more information, see the + [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). + On IBM Cloud, you can specify `latest`, `previous`, or `beta`. + On IBM Cloud Pak for Data, you can specify either `beta` or the date of + the version you want to use, in `YYYY-MM-DD` format. + """ + self.model = model + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsNlp': + """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" + args = {} + if (model := _dict.get('model')) is not None: + args['model'] = model + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this WorkspaceSystemSettingsNlp object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class WorkspaceSystemSettingsOffTopic: """ Workspace settings related to detection of irrelevant input. - :attr bool enabled: (optional) Whether enhanced irrelevance detection is enabled - for the workspace. + :param bool enabled: (optional) Whether enhanced irrelevance detection is + enabled for the workspace. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsOffTopic object. @@ -10291,8 +12009,8 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled return cls(**args) @classmethod @@ -10326,15 +12044,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: return not self == other -class WorkspaceSystemSettingsSystemEntities(): +class WorkspaceSystemSettingsSystemEntities: """ Workspace settings related to the behavior of system entities. - :attr bool enabled: (optional) Whether the new system entities are enabled for + :param bool enabled: (optional) Whether the new system entities are enabled for the workspace. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsSystemEntities object. @@ -10347,8 +12069,8 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsSystemEntities': """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled return cls(**args) @classmethod @@ -10382,15 +12104,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: return not self == other -class WorkspaceSystemSettingsTooling(): +class WorkspaceSystemSettingsTooling: """ Workspace settings related to the Watson Assistant user interface. - :attr bool store_generic_responses: (optional) Whether the dialog JSON editor + :param bool store_generic_responses: (optional) Whether the dialog JSON editor displays text responses within the `output.generic` object. """ - def __init__(self, *, store_generic_responses: bool = None) -> None: + def __init__( + self, + *, + store_generic_responses: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsTooling object. @@ -10403,9 +12129,9 @@ def __init__(self, *, store_generic_responses: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} - if 'store_generic_responses' in _dict: - args['store_generic_responses'] = _dict.get( - 'store_generic_responses') + if (store_generic_responses := + _dict.get('store_generic_responses')) is not None: + args['store_generic_responses'] = store_generic_responses return cls(**args) @classmethod @@ -10445,30 +12171,32 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object. @@ -10483,7 +12211,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -10502,31 +12230,30 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -10546,7 +12273,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -10582,28 +12315,34 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_user: The message to display to the user when initiating a + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an @@ -10623,29 +12362,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -10663,9 +12400,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -10698,32 +12444,34 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) An optional message to be sent to + :param str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object. @@ -10758,28 +12506,28 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'channels' in _dict: + transfer_info) + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -10798,14 +12546,29 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -10838,28 +12601,30 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object. @@ -10891,28 +12656,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -10935,7 +12699,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -10966,26 +12736,28 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the image. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. @@ -11015,29 +12787,28 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11057,7 +12828,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -11090,28 +12867,30 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str title: An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr str preference: (optional) The preferred type of control to display, if + :param str preference: (optional) The preferred type of control to display, if supported by the channel. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. You can include up to 20 options. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. @@ -11143,35 +12922,33 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11192,9 +12969,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11223,6 +13012,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display, if supported by the channel. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -11232,22 +13022,24 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( """ DialogNodeOutputGenericDialogNodeOutputResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. The valid values are from 0 + :param int time: How long to pause, in milliseconds. The valid values are from 0 to 10000. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object. @@ -11273,24 +13065,23 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11309,7 +13100,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11340,33 +13137,35 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **search_skill** response type is used only by the v2 runtime API. - :attr str query: The text of the search query. This can be either a + :param str query: The text of the search query. This can be either a natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). - :attr str query_type: The type of the search query. - :attr str filter: (optional) An optional filter that narrows the set of + :param str query_type: The type of the search query. + :param str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). - :attr str discovery_version: (optional) The version of the Discovery service API - to use for the query. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str discovery_version: (optional) The version of the Discovery service + API to use for the query. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - query: str, - query_type: str, - *, - filter: str = None, - discovery_version: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + query: str, + query_type: str, + *, + filter: Optional[str] = None, + discovery_version: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object. @@ -11404,32 +13203,31 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'query' in _dict: - args['query'] = _dict.get('query') + if (query := _dict.get('query')) is not None: + args['query'] = query else: raise ValueError( 'Required property \'query\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'query_type' in _dict: - args['query_type'] = _dict.get('query_type') + if (query_type := _dict.get('query_type')) is not None: + args['query_type'] = query_type else: raise ValueError( 'Required property \'query_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'discovery_version' in _dict: - args['discovery_version'] = _dict.get('discovery_version') - if 'channels' in _dict: + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (discovery_version := _dict.get('discovery_version')) is not None: + args['discovery_version'] = discovery_version + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11453,7 +13251,13 @@ def to_dict(self) -> Dict: 'discovery_version') and self.discovery_version is not None: _dict['discovery_version'] = self.discovery_version if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11484,6 +13288,7 @@ class QueryTypeEnum(str, Enum): """ The type of the search query. """ + NATURAL_LANGUAGE = 'natural_language' DISCOVERY_QUERY_LANGUAGE = 'discovery_query_language' @@ -11493,25 +13298,27 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr List[DialogNodeOutputTextValuesElement] values: A list of one or more + :param List[DialogNodeOutputTextValuesElement] values: A list of one or more objects defining text responses. - :attr str selection_policy: (optional) How a response is selected from the list, - if more than one response is specified. - :attr str delimiter: (optional) The delimiter to use as a separator between + :param str selection_policy: (optional) How a response is selected from the + list, if more than one response is specified. + :param str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - values: List['DialogNodeOutputTextValuesElement'], - *, - selection_policy: str = None, - delimiter: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + values: List['DialogNodeOutputTextValuesElement'], + *, + selection_policy: Optional[str] = None, + delimiter: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object. @@ -11540,29 +13347,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'values' in _dict: + if (values := _dict.get('values')) is not None: args['values'] = [ - DialogNodeOutputTextValuesElement.from_dict(x) - for x in _dict.get('values') + DialogNodeOutputTextValuesElement.from_dict(v) for v in values ] else: raise ValueError( 'Required property \'values\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'selection_policy' in _dict: - args['selection_policy'] = _dict.get('selection_policy') - if 'delimiter' in _dict: - args['delimiter'] = _dict.get('delimiter') - if 'channels' in _dict: + if (selection_policy := _dict.get('selection_policy')) is not None: + args['selection_policy'] = selection_policy + if (delimiter := _dict.get('delimiter')) is not None: + args['delimiter'] = delimiter + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11577,14 +13382,26 @@ def to_dict(self) -> Dict: if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list if hasattr(self, 'selection_policy') and self.selection_policy is not None: _dict['selection_policy'] = self.selection_policy if hasattr(self, 'delimiter') and self.delimiter is not None: _dict['delimiter'] = self.delimiter if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11613,6 +13430,7 @@ class SelectionPolicyEnum(str, Enum): """ How a response is selected from the list, if more than one response is specified. """ + SEQUENTIAL = 'sequential' RANDOM = 'random' MULTILINE = 'multiline' @@ -11623,20 +13441,22 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. The total size of this object cannot exceed 5000 bytes. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object. @@ -11660,22 +13480,21 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11692,7 +13511,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11725,30 +13550,32 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the video. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object. @@ -11763,7 +13590,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -11782,31 +13609,30 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11826,7 +13652,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -11861,30 +13693,32 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -11900,7 +13734,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -11919,31 +13753,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11963,7 +13796,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -11997,30 +13836,36 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( """ RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_user: The message to display to the user when initiating a + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an @@ -12042,29 +13887,27 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12082,9 +13925,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12115,42 +13967,44 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( """ RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human + :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr str topic: (optional) A label identifying the topic of the conversation, + :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :attr str dialog_node: (optional) The unique ID of the dialog node that the + :param str dialog_node: (optional) The unique ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of the dialog node's **title** property. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None, - dialog_node: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + topic: Optional[str] = None, + dialog_node: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -12195,32 +14049,32 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'channels' in _dict: + transfer_info) + if (topic := _dict.get('topic')) is not None: + args['topic'] = topic + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12239,18 +14093,33 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12280,28 +14149,30 @@ class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str description: (optional) The description to show with the response. + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. @@ -12334,28 +14205,27 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12378,7 +14248,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12408,28 +14284,30 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the image. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -12462,29 +14340,28 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -12504,7 +14381,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -12534,27 +14417,29 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param str title: The title or introductory text to show before the response. + :param str description: (optional) The description to show with the response. + :param str preference: (optional) The preferred type of control to display. + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -12587,35 +14472,33 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12636,9 +14519,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12667,6 +14562,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -12675,23 +14571,25 @@ class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -12718,24 +14616,23 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12754,7 +14651,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12783,23 +14686,25 @@ class RuntimeResponseGenericRuntimeResponseTypeSuggestion( """ RuntimeResponseGenericRuntimeResponseTypeSuggestion. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr List[DialogSuggestion] suggestions: An array of objects describing the + :param str title: The title or introductory text to show before the response. + :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - suggestions: List['DialogSuggestion'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -12827,30 +14732,29 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'suggestions' in _dict: + if (suggestions := _dict.get('suggestions')) is not None: args['suggestions'] = [ - DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in suggestions ] else: raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12867,9 +14771,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + suggestions_list = [] + for v in self.suggestions: + if isinstance(v, dict): + suggestions_list.append(v) + else: + suggestions_list.append(v.to_dict()) + _dict['suggestions'] = suggestions_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12899,20 +14815,22 @@ class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str text: The text of the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - text: str, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + text: str, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -12936,22 +14854,21 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12968,7 +14885,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12997,21 +14920,23 @@ class RuntimeResponseGenericRuntimeResponseTypeUserDefined( """ RuntimeResponseGenericRuntimeResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. @@ -13036,22 +14961,21 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13068,7 +14992,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13098,30 +15028,32 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -13137,7 +15069,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -13156,31 +15088,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13200,7 +15131,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index b9413e510..72dbd34c3 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,27 +14,29 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ -The IBM Watson™ Assistant service combines machine learning, natural language +The IBM® watsonx™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v2 API provides runtime methods your client application can use to send user input to an assistant and receive a response. +You need a paid Plus plan or higher to use the watsonx Assistant v2 API. API Version: 2.0 See: https://cloud.ibm.com/docs/assistant """ +from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import BinaryIO, Dict, List, Optional import json import sys from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model +from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime from .common import get_sdk_headers @@ -59,7 +61,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-11-27`. + Specify dates in YYYY-MM-DD format. The current version is `2024-08-25`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -76,11 +78,409 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Conversational skill providers + ######################### + + def create_provider( + self, + provider_id: str, + specification: 'ProviderSpecification', + private: 'ProviderPrivate', + **kwargs, + ) -> DetailedResponse: + """ + Create a conversational skill provider. + + Create a new conversational skill provider. + + :param str provider_id: The unique identifier of the provider. + :param ProviderSpecification specification: The specification of the + provider. + :param ProviderPrivate private: Private information of the provider. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderResponse` object + """ + + if provider_id is None: + raise ValueError('provider_id must be provided') + if specification is None: + raise ValueError('specification must be provided') + if private is None: + raise ValueError('private must be provided') + specification = convert_model(specification) + private = convert_model(private) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_provider', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'provider_id': provider_id, + 'specification': specification, + 'private': private, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/providers' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def list_providers( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + List conversational skill providers. + + List the conversational skill providers associated with a Watson Assistant service + instance. + + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned conversational + skill providers will be sorted. To reverse the sort order, prefix the value + with a minus sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderCollection` object + """ + + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_providers', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/providers' + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_provider( + self, + provider_id: str, + specification: 'ProviderSpecification', + private: 'ProviderPrivate', + **kwargs, + ) -> DetailedResponse: + """ + Update a conversational skill provider. + + Update a new conversational skill provider. + + :param str provider_id: Unique identifier of the conversational skill + provider. + :param ProviderSpecification specification: The specification of the + provider. + :param ProviderPrivate private: Private information of the provider. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderResponse` object + """ + + if not provider_id: + raise ValueError('provider_id must be provided') + if specification is None: + raise ValueError('specification must be provided') + if private is None: + raise ValueError('private must be provided') + specification = convert_model(specification) + private = convert_model(private) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_provider', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'specification': specification, + 'private': private, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['provider_id'] + path_param_values = self.encode_path_vars(provider_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/providers/{provider_id}'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Assistants + ######################### + + def create_assistant( + self, + *, + language: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create an assistant. + + Create a new assistant. + + :param str language: (optional) The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AssistantData` object + """ + + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_assistant', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'language': language, + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/assistants' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def list_assistants( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + List assistants. + + List the assistants associated with a watsonx Assistant service instance. + + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned assistants will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AssistantCollection` object + """ + + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_assistants', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/assistants' + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def delete_assistant( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Delete assistant. + + Delete an assistant. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_assistant', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}'.format(**path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + ######################### # Sessions ######################### - def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: + def create_session( + self, + assistant_id: str, + environment_id: str, + *, + analytics: Optional['RequestAnalytics'] = None, + **kwargs, + ) -> DetailedResponse: """ Create a session. @@ -88,47 +488,77 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: responses. It also maintains the state of the conversation. A session persists until it is deleted, or until it times out because of inactivity. (For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings). - - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings).). + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if analytics is not None: + analytics = convert_model(analytics) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_session') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_session', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } + + data = { + 'analytics': analytics, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/sessions'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_session(self, assistant_id: str, session_id: str, - **kwargs) -> DetailedResponse: + def delete_session( + self, + assistant_id: str, + environment_id: str, + session_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete session. @@ -136,43 +566,55 @@ def delete_session(self, assistant_id: str, session_id: str, session inactivity timeout, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings)). - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if session_id is None: + if not environment_id: + raise ValueError('environment_id must be provided') + if not session_id: raise ValueError('session_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_session') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_session', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'session_id'] - path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/sessions/{session_id}'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -181,27 +623,32 @@ def delete_session(self, assistant_id: str, session_id: str, # Message ######################### - def message(self, - assistant_id: str, - session_id: str, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None, - **kwargs) -> DetailedResponse: + def message( + self, + assistant_id: str, + environment_id: str, + session_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Send user input to assistant (stateful). Send user input to an assistant and receive a response, with conversation state - (including context data) stored by Watson Assistant for the duration of the + (including context data) stored by watsonx Assistant for the duration of the session. - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the input text. @@ -223,70 +670,89 @@ def message(self, value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object + :rtype: DetailedResponse with `dict` result representing a `StatefulMessageResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if session_id is None: + if not environment_id: + raise ValueError('environment_id must be provided') + if not session_id: raise ValueError('session_id must be provided') if input is not None: input = convert_model(input) if context is not None: context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='message') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input, 'context': context, 'user_id': user_id} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'session_id'] - path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}/message'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def message_stateless(self, - assistant_id: str, - *, - input: 'MessageInputStateless' = None, - context: 'MessageContextStateless' = None, - user_id: str = None, - **kwargs) -> DetailedResponse: + def message_stateless( + self, + assistant_id: str, + environment_id: str, + *, + input: Optional['StatelessMessageInput'] = None, + context: Optional['StatelessMessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Send user input to assistant (stateless). Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. - :param MessageInputStateless input: (optional) An input object that + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param StatelessMessageInput input: (optional) An input object that includes the input text. - :param MessageContextStateless context: (optional) Context data for the + :param StatelessMessageContext context: (optional) Context data for the conversation. You can use this property to set or modify context variables, which can also be accessed by dialog nodes. The context is not stored by the assistant. To maintain session state, include the context from the @@ -305,132 +771,376 @@ def message_stateless(self, message request, the value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object + :rtype: DetailedResponse with `dict` result representing a `StatelessMessageResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if input is not None: input = convert_model(input) if context is not None: context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='message_stateless') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stateless', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input, 'context': context, 'user_id': user_id} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/message'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response ######################### - # Bulk classify + # Message Stream ######################### - def bulk_classify(self, - skill_id: str, - *, - input: List['BulkClassifyUtterance'] = None, - **kwargs) -> DetailedResponse: + def message_stream( + self, + assistant_id: str, + environment_id: str, + session_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ - Identify intents and entities in multiple user utterances. + Send user input to assistant (stateful). - Send multiple user inputs to a dialog skill in a single request and receive - information about the intents and entities recognized in each input. This method - is useful for testing and comparing the performance of different skills or skill - versions. - This method is available only with Enterprise with Data Isolation plans. + Send user input to an assistant and receive a streamed response, with conversation + state (including context data) stored by watsonx Assistant for the duration of the + session. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click - **API Details**. - :param List[BulkClassifyUtterance] input: (optional) An array of input - utterances to classify. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param str session_id: Unique identifier of the session. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + :rtype: DetailedResponse with `BinaryIO` result """ - if skill_id is None: - raise ValueError('skill_id must be provided') + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if not session_id: + raise ValueError('session_id must be provided') if input is not None: - input = [convert_model(x) for x in input] + input = convert_model(input) + if context is not None: + context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='bulk_classify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stream', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] + headers['Accept'] = 'text/event-stream' - path_param_keys = ['skill_id'] - path_param_values = self.encode_path_vars(skill_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}/message_stream'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - ######################### - # Logs - ######################### - - def list_logs(self, - assistant_id: str, - *, - sort: str = None, - filter: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def message_stream_stateless( + self, + assistant_id: str, + environment_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Send user input to assistant (stateless). + + Send user input to an assistant and receive a response, with conversation state + (including context data) managed by your application. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `BinaryIO` result + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if input is not None: + input = convert_model(input) + if context is not None: + context = convert_model(context) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stream_stateless', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'text/event-stream' + + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/message_stream'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Bulk classify + ######################### + + def bulk_classify( + self, + skill_id: str, + input: List['BulkClassifyUtterance'], + **kwargs, + ) -> DetailedResponse: + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a dialog skill in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different skills or skill + versions. + This method is available only with Enterprise with Data Isolation plans. + + :param str skill_id: Unique identifier of the skill. To find the action or + dialog skill ID in the watsonx Assistant user interface, open the skill + settings and click **API Details**. To find the search skill ID, use the + Get environment API to retrieve the skill references for an environment and + it will include the search skill info, if available. + :param List[BulkClassifyUtterance] input: An array of input utterances to + classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + """ + + if not skill_id: + raise ValueError('skill_id must be provided') + if input is None: + raise ValueError('input must be provided') + input = [convert_model(x) for x in input] + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'input': input, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['skill_id'] + path_param_values = self.encode_path_vars(skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Logs + ######################### + + def list_logs( + self, + assistant_id: str, + *, + sort: Optional[str] = None, + filter: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events for an assistant. List the events from the log of an assistant. - This method requires Manager access, and is available only with Enterprise plans. - - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + This method requires Manager access. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str sort: (optional) How to sort the returned log events. You can sort by **request_timestamp**. To reverse the sort order, prefix the parameter value with a minus sign (`-`). @@ -439,6 +1149,8 @@ def list_logs(self, [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). :param int page_limit: (optional) The number of records to return in each page of results. + **Note:** If the API is not returning your data, try lowering the + page_limit value. :param str cursor: (optional) A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers @@ -446,12 +1158,14 @@ def list_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_logs', + ) headers.update(sdk_headers) params = { @@ -459,21 +1173,24 @@ def list_logs(self, 'sort': sort, 'filter': filter, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/logs'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -482,7 +1199,11 @@ def list_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -495,7 +1216,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: **Note:** This operation is intended only for deleting data associated with a single specific customer, not for deleting data associated with multiple customers or for any other purpose. For more information, see [Labeling and deleting data in - Watson + watsonx Assistant](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security-gdpr-wa). :param str customer_id: The customer ID for which all data is to be @@ -505,208 +1226,15145 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data', + ) headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v2/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response + ######################### + # Environments + ######################### -############################################################################## -# Models -############################################################################## - - -class AgentAvailabilityMessage(): - """ - AgentAvailabilityMessage. + def list_environments( + self, + assistant_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + List environments. - :attr str message: (optional) The text of the message. - """ + List the environments associated with an assistant. - def __init__(self, *, message: str = None) -> None: + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned environments + will be sorted. To reverse the sort order, prefix the value with a minus + sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `EnvironmentCollection` object """ - Initialize a AgentAvailabilityMessage object. - :param str message: (optional) The text of the message. - """ - self.message = message + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_environments', + ) + headers.update(sdk_headers) - @classmethod - def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') - return cls(**args) + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } - @classmethod - def _from_dict(cls, _dict): - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - return cls.from_dict(_dict) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - return _dict + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + response = self.send(request, **kwargs) + return response - def __str__(self) -> str: - """Return a `str` version of this AgentAvailabilityMessage object.""" - return json.dumps(self.to_dict(), indent=2) + def get_environment( + self, + assistant_id: str, + environment_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Get environment. + + Get information about an environment. For more information about environments, see + [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object + """ - def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_environment', + ) + headers.update(sdk_headers) - def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + params = { + 'version': self.version, + 'include_audit': include_audit, + } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class BulkClassifyOutput(): - """ - BulkClassifyOutput. + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) - :attr BulkClassifyUtterance input: (optional) The user input utterance to - classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the utterance. - """ + response = self.send(request, **kwargs) + return response - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: + def update_environment( + self, + assistant_id: str, + environment_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + orchestration: Optional['UpdateEnvironmentOrchestration'] = None, + session_timeout: Optional[int] = None, + skill_references: Optional[List['EnvironmentSkill']] = None, + **kwargs, + ) -> DetailedResponse: """ - Initialize a BulkClassifyOutput object. - - :param BulkClassifyUtterance input: (optional) The user input utterance to - classify. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the utterance. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the utterance. + Update environment. + + Update an environment with new or modified data. For more information about + environments, see + [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param UpdateEnvironmentOrchestration orchestration: (optional) The search + skill orchestration settings for the environment. + :param int session_timeout: (optional) The session inactivity timeout + setting for the environment (in seconds). + :param List[EnvironmentSkill] skill_references: (optional) An array of + objects identifying the skills (such as action and dialog) that exist in + the environment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - self.input = input - self.entities = entities - self.intents = intents - @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': - """Initialize a BulkClassifyOutput object from a json dictionary.""" - args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - return cls(**args) + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if orchestration is not None: + orchestration = convert_model(orchestration) + if skill_references is not None: + skill_references = [convert_model(x) for x in skill_references] + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_environment', + ) + headers.update(sdk_headers) - @classmethod - def _from_dict(cls, _dict): - """Initialize a BulkClassifyOutput object from a json dictionary.""" - return cls.from_dict(_dict) + params = { + 'version': self.version, + } - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - return _dict + data = { + 'name': name, + 'description': description, + 'orchestration': orchestration, + 'session_timeout': session_timeout, + 'skill_references': skill_references, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __str__(self) -> str: - """Return a `str` version of this BulkClassifyOutput object.""" - return json.dumps(self.to_dict(), indent=2) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) - def __eq__(self, other: 'BulkClassifyOutput') -> bool: - """Return `true` when self and other are equal, false otherwise.""" + response = self.send(request, **kwargs) + return response + + ######################### + # Releases + ######################### + + def create_release( + self, + assistant_id: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create release. + + Create a new release using the current content of the dialog and action skills in + the draft environment. (In the watsonx Assistant user interface, a release is + called a *version*.). + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str description: (optional) The description of the release. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Release` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def list_releases( + self, + assistant_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + List releases. + + List the releases associated with an assistant. (In the watsonx Assistant user + interface, a release is called a *version*.). + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned workspaces will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ReleaseCollection` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_releases', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def get_release( + self, + assistant_id: str, + release: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Get release. + + Get information about a release. + Release data is not available until publishing of the release completes. If + publishing is still in progress, you can continue to poll by calling the same + request again and checking the value of the **status** property. When processing + has completed, the request returns the release data. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str release: Unique identifier of the release. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Release` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_release', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def delete_release( + self, + assistant_id: str, + release: str, + **kwargs, + ) -> DetailedResponse: + """ + Delete release. + + Delete a release. (In the watsonx Assistant user interface, a release is called a + *version*.). + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str release: Unique identifier of the release. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_release', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}'.format( + **path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def deploy_release( + self, + assistant_id: str, + release: str, + environment_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Deploy release. + + Update the environment with the content of the release. All snapshots saved as + part of the release become active in the environment. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str release: Unique identifier of the release. + :param str environment_id: The environment ID of the environment where the + release is to be deployed. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + if environment_id is None: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='deploy_release', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + data = { + 'environment_id': environment_id, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def create_release_export( + self, + assistant_id: str, + release: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create release export. + + Initiate an asynchronous process which will create a downloadable Zip file + artifact (/package) for an assistant release. This artifact will contain Action + and/or Dialog skills that are part of the release. The Dialog skill will only be + included in the event that coexistence is enabled on the assistant. The expected + workflow with the use of Release Export endpoint is to first initiate the creation + of the artifact with the POST endpoint and then poll the GET endpoint to retrieve + the artifact. Once the artifact has been created, it will last for the duration + (/scope) of the release. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str release: Unique identifier of the release. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CreateReleaseExportWithStatusErrors` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release_export', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}/export'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def download_release_export( + self, + assistant_id: str, + release: str, + *, + accept: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Get release export. + + A dual function endpoint to either retrieve the Zip file artifact that is + associated with an assistant release or, retrieve the status of the artifact's + creation. It is assumed that the artifact creation was already initiated prior to + calling this endpoint. In the event that the artifact is not yet created and ready + for download, this endpoint can be used to poll the system until the creation is + completed or has failed. On the other hand, if the artifact is created, this + endpoint will return the Zip file artifact as an octet stream. Once the artifact + has been created, it will last for the duration (/scope) of the release.

When you will have downloaded the Zip file artifact, you have one of three ways + to import it into an assistant's draft environment. These are as follows.
  1. Import the zip package in Tooling via "Assistant Settings" -> + "Download/Upload files" -> "Upload" -> "Assistant only".
  2. Import the + zip package via "Create release import" endpoint using the APIs.
  3. Extract + the contents of the Zip file artifact and individually import the skill JSONs via + skill update endpoints.
. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str release: Unique identifier of the release. + :param str accept: (optional) The type of the response: application/json or + application/octet-stream. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CreateReleaseExportWithStatusErrors` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + headers = { + 'Accept': accept, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='download_release_export', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}/export'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def create_release_import( + self, + assistant_id: str, + body: BinaryIO, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create release import. + + Import a previously exported assistant release Zip file artifact (/package) into + an assistant. This endpoint creates (/initiates) an asynchronous task (/job) in + the background which will import the artifact contents into the draft environment + of the assistant on which this endpoint is called. Specifically, the asynchronous + operation will override the action and/or dialog skills in the assistant. It will + be worth noting that when the artifact that is provided to this endpoint is from + an assistant release which has coexistence enabled (i.e., it has both action and + dialog skills), the import process will automatically enable coexistence, if not + already enabled, on the assistant into which said artifact is being uploaded to. + On the other hand, if the artifact package being imported only has action skill in + it, the import asynchronous process will only override the draft environment's + action skill, regardless of whether coexistence is enabled on the assistant into + which the package is being imported. Lastly, the system will only run one + asynchronous import at a time on an assistant. As such, consecutive imports will + override previous import's updates to the skills in the draft environment. Once + created, you may poll the completion of the import via the "Get release import + Status" endpoint. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param BinaryIO body: Request body is an Octet-stream of the artifact Zip + file that is being imported. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CreateAssistantReleaseImportResponse` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if body is None: + raise ValueError('body must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release_import', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + data = body + headers['content-type'] = 'application/octet-stream' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/import'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def get_release_import_status( + self, + assistant_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Get release import Status. + + Monitor the status of an assistant release import. You may poll this endpoint + until the status of the import has either succeeded or failed. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `MonitorAssistantReleaseImportArtifactResponse` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_release_import_status', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/import'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Skills + ######################### + + def get_skill( + self, + assistant_id: str, + skill_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get skill. + + Get information about a skill. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str skill_id: Unique identifier of the skill. To find the action or + dialog skill ID in the watsonx Assistant user interface, open the skill + settings and click **API Details**. To find the search skill ID, use the + Get environment API to retrieve the skill references for an environment and + it will include the search skill info, if available. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_skill', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_skill( + self, + assistant_id: str, + skill_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + dialog_settings: Optional[dict] = None, + search_settings: Optional['SearchSettings'] = None, + **kwargs, + ) -> DetailedResponse: + """ + Update skill. + + Update a skill with new or modified data. + **Note:** The update is performed asynchronously; you can see the status of the + update by calling the **Get skill** method and checking the value of the + **status** property. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str skill_id: Unique identifier of the skill. To find the action or + dialog skill ID in the watsonx Assistant user interface, open the skill + settings and click **API Details**. To find the search skill ID, use the + Get environment API to retrieve the skill references for an environment and + it will include the search skill info, if available. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + if search_settings is not None: + search_settings = convert_model(search_settings) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + 'workspace': workspace, + 'dialog_settings': dialog_settings, + 'search_settings': search_settings, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def export_skills( + self, + assistant_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Export skills. + + Asynchronously export the action skill and dialog skill (if enabled) for the + assistant. Use this method to save all skill data from the draft environment so + that you can import it to a different assistant using the **Import skills** + method. Use `assistant_id` instead of `environment_id` to call this endpoint. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. + After the initial request is submitted, you can poll the status of the operation + by calling the same request again and checking the value of the **status** + property. If an error occurs (indicated by a **status** value of `Failed`), the + `status_description` property provides more information about the error, and the + `status_errors` property contains an array of error messages that caused the + failure. + When processing has completed, the request returns the exported JSON data. + Remember that the usual rate limits apply. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsExport` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_export'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def import_skills( + self, + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + Import skills. + + Asynchronously import skills into an existing assistant from a previously exported + file. This method only imports assistants into a draft environment. Use + `assistant_id` instead of `environment_id` to call this endpoint. + The request body for this method should contain the response data that was + received from a previous call to the **Export skills** method, without + modification. + A successful call to this method initiates an asynchronous import. The updated + skills belonging to the assistant are not available until processing completes. To + check the status of the asynchronous import operation, use the **Get status of + skills import** method. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param List[SkillImport] assistant_skills: An array of objects describing + the skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if assistant_skills is None: + raise ValueError('assistant_skills must be provided') + if assistant_state is None: + raise ValueError('assistant_state must be provided') + assistant_skills = [convert_model(x) for x in assistant_skills] + assistant_state = convert_model(assistant_state) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + data = { + 'assistant_skills': assistant_skills, + 'assistant_state': assistant_state, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def import_skills_status( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get status of skills import. + + Retrieve the status of an asynchronous import operation previously initiated by + using the **Import skills** method. + + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + +class ListProvidersEnums: + """ + Enums for list_providers parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned conversational skill providers will be sorted. To + reverse the sort order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListAssistantsEnums: + """ + Enums for list_assistants parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned assistants will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListEnvironmentsEnums: + """ + Enums for list_environments parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned environments will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListReleasesEnums: + """ + Enums for list_releases parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class DownloadReleaseExportEnums: + """ + Enums for download_release_export parameters. + """ + + class Accept(str, Enum): + """ + The type of the response: application/json or application/octet-stream. + """ + + APPLICATION_JSON = 'application/json' + APPLICATION_OCTET_STREAM = 'application/octet-stream' + + +############################################################################## +# Models +############################################################################## + + +class AgentAvailabilityMessage: + """ + AgentAvailabilityMessage. + + :param str message: (optional) The text of the message. + """ + + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: + """ + Initialize a AgentAvailabilityMessage object. + + :param str message: (optional) The text of the message. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" + args = {} + if (message := _dict.get('message')) is not None: + args['message'] = message + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AgentAvailabilityMessage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantCollection: + """ + AssistantCollection. + + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + assistants: List['AssistantData'], + pagination: 'Pagination', + ) -> None: + """ + Initialize a AssistantCollection object. + + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.assistants = assistants + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantCollection': + """Initialize a AssistantCollection object from a json dictionary.""" + args = {} + if (assistants := _dict.get('assistants')) is not None: + args['assistants'] = [ + AssistantData.from_dict(v) for v in assistants + ] + else: + raise ValueError( + 'Required property \'assistants\' not present in AssistantCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in AssistantCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistants') and self.assistants is not None: + assistants_list = [] + for v in self.assistants: + if isinstance(v, dict): + assistants_list.append(v) + else: + assistants_list.append(v.to_dict()) + _dict['assistants'] = assistants_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AssistantCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AssistantCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantData: + """ + AssistantData. + + :param str assistant_id: (optional) The unique identifier of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This string + cannot contain carriage return, newline, or tab characters. + :param str language: The language of the assistant. + :param List[AssistantSkill] assistant_skills: (optional) An array of skill + references identifying the skills associated with the assistant. + :param List[EnvironmentReference] assistant_environments: (optional) An array of + objects describing the environments defined for the assistant. + """ + + def __init__( + self, + language: str, + *, + assistant_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_skills: Optional[List['AssistantSkill']] = None, + assistant_environments: Optional[List['EnvironmentReference']] = None, + ) -> None: + """ + Initialize a AssistantData object. + + :param str language: The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. + """ + self.assistant_id = assistant_id + self.name = name + self.description = description + self.language = language + self.assistant_skills = assistant_skills + self.assistant_environments = assistant_environments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantData': + """Initialize a AssistantData object from a json dictionary.""" + args = {} + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in AssistantData JSON' + ) + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + AssistantSkill.from_dict(v) for v in assistant_skills + ] + if (assistant_environments := + _dict.get('assistant_environments')) is not None: + args['assistant_environments'] = [ + EnvironmentReference.from_dict(v) + for v in assistant_environments + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantData object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'assistant_skills') and getattr( + self, 'assistant_skills') is not None: + assistant_skills_list = [] + for v in getattr(self, 'assistant_skills'): + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, 'assistant_environments') and getattr( + self, 'assistant_environments') is not None: + assistant_environments_list = [] + for v in getattr(self, 'assistant_environments'): + if isinstance(v, dict): + assistant_environments_list.append(v) + else: + assistant_environments_list.append(v.to_dict()) + _dict['assistant_environments'] = assistant_environments_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AssistantData object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantData') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AssistantData') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantSkill: + """ + AssistantSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + ) -> None: + """ + Initialize a AssistantSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + """ + self.skill_id = skill_id + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantSkill': + """Initialize a AssistantSkill object from a json dictionary.""" + args = {} + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in AssistantSkill JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AssistantSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AssistantSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class AssistantState: + """ + Status information about the skills for the assistant. Included in responses only if + **status**=`Available`. + + :param bool action_disabled: Whether the action skill is disabled in the draft + environment. + :param bool dialog_disabled: Whether the dialog skill is disabled in the draft + environment. + """ + + def __init__( + self, + action_disabled: bool, + dialog_disabled: bool, + ) -> None: + """ + Initialize a AssistantState object. + + :param bool action_disabled: Whether the action skill is disabled in the + draft environment. + :param bool dialog_disabled: Whether the dialog skill is disabled in the + draft environment. + """ + self.action_disabled = action_disabled + self.dialog_disabled = dialog_disabled + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantState': + """Initialize a AssistantState object from a json dictionary.""" + args = {} + if (action_disabled := _dict.get('action_disabled')) is not None: + args['action_disabled'] = action_disabled + else: + raise ValueError( + 'Required property \'action_disabled\' not present in AssistantState JSON' + ) + if (dialog_disabled := _dict.get('dialog_disabled')) is not None: + args['dialog_disabled'] = dialog_disabled + else: + raise ValueError( + 'Required property \'dialog_disabled\' not present in AssistantState JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantState object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'action_disabled') and self.action_disabled is not None: + _dict['action_disabled'] = self.action_disabled + if hasattr(self, + 'dialog_disabled') and self.dialog_disabled is not None: + _dict['dialog_disabled'] = self.dialog_disabled + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AssistantState object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantState') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AssistantState') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BaseEnvironmentOrchestration: + """ + The search skill orchestration settings for the environment. + + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). + """ + + def __init__( + self, + *, + search_skill_fallback: Optional[bool] = None, + ) -> None: + """ + Initialize a BaseEnvironmentOrchestration object. + + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). + """ + self.search_skill_fallback = search_skill_fallback + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentOrchestration': + """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" + args = {} + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BaseEnvironmentOrchestration object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BaseEnvironmentOrchestration') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BaseEnvironmentOrchestration') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BaseEnvironmentReleaseReference: + """ + An object describing the release that is currently deployed in the environment. + + :param str release: (optional) The name of the deployed release. + """ + + def __init__( + self, + *, + release: Optional[str] = None, + ) -> None: + """ + Initialize a BaseEnvironmentReleaseReference object. + + :param str release: (optional) The name of the deployed release. + """ + self.release = release + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentReleaseReference': + """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" + args = {} + if (release := _dict.get('release')) is not None: + args['release'] = release + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BaseEnvironmentReleaseReference object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BaseEnvironmentReleaseReference') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BaseEnvironmentReleaseReference') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BulkClassifyOutput: + """ + BulkClassifyOutput. + + :param BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the utterance. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the utterance. + """ + + def __init__( + self, + *, + input: Optional['BulkClassifyUtterance'] = None, + entities: Optional[List['RuntimeEntity']] = None, + intents: Optional[List['RuntimeIntent']] = None, + ) -> None: + """ + Initialize a BulkClassifyOutput object. + + :param BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the utterance. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the utterance. + """ + self.input = input + self.entities = entities + self.intents = intents + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': + """Initialize a BulkClassifyOutput object from a json dictionary.""" + args = {} + if (input := _dict.get('input')) is not None: + args['input'] = BulkClassifyUtterance.from_dict(input) + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyOutput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BulkClassifyOutput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyOutput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BulkClassifyOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BulkClassifyResponse: + """ + BulkClassifyResponse. + + :param List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. + """ + + def __init__( + self, + *, + output: Optional[List['BulkClassifyOutput']] = None, + ) -> None: + """ + Initialize a BulkClassifyResponse object. + + :param List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. + """ + self.output = output + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': + """Initialize a BulkClassifyResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = [BulkClassifyOutput.from_dict(v) for v in output] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BulkClassifyResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BulkClassifyResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BulkClassifyUtterance: + """ + The user input utterance to classify. + + :param str text: The text of the input utterance. + """ + + def __init__( + self, + text: str, + ) -> None: + """ + Initialize a BulkClassifyUtterance object. + + :param str text: The text of the input utterance. + """ + self.text = text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': + """Initialize a BulkClassifyUtterance object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in BulkClassifyUtterance JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyUtterance object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BulkClassifyUtterance object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyUtterance') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BulkClassifyUtterance') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CaptureGroup: + """ + CaptureGroup. + + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that indicate + where the entity value begins and ends in the input text. + """ + + def __init__( + self, + group: str, + *, + location: Optional[List[int]] = None, + ) -> None: + """ + Initialize a CaptureGroup object. + + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that + indicate where the entity value begins and ends in the input text. + """ + self.group = group + self.location = location + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': + """Initialize a CaptureGroup object from a json dictionary.""" + args = {} + if (group := _dict.get('group')) is not None: + args['group'] = group + else: + raise ValueError( + 'Required property \'group\' not present in CaptureGroup JSON') + if (location := _dict.get('location')) is not None: + args['location'] = location + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CaptureGroup object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'group') and self.group is not None: + _dict['group'] = self.group + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CaptureGroup object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CaptureGroup') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CaptureGroup') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferInfo: + """ + Information used by an integration to transfer the conversation to a different + channel. + + :param ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an available + transfer target. Currently, the only supported property is **chat**, + representing the web chat integration. + """ + + def __init__( + self, + target: 'ChannelTransferTarget', + ) -> None: + """ + Initialize a ChannelTransferInfo object. + + :param ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an + available transfer target. Currently, the only supported property is + **chat**, representing the web chat integration. + """ + self.target = target + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': + """Initialize a ChannelTransferInfo object from a json dictionary.""" + args = {} + if (target := _dict.get('target')) is not None: + args['target'] = ChannelTransferTarget.from_dict(target) + else: + raise ValueError( + 'Required property \'target\' not present in ChannelTransferInfo JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferInfo object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'target') and self.target is not None: + if isinstance(self.target, dict): + _dict['target'] = self.target + else: + _dict['target'] = self.target.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ChannelTransferInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferInfo') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ChannelTransferInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferTarget: + """ + An object specifying target channels available for the transfer. Each property of this + object represents an available transfer target. Currently, the only supported property + is **chat**, representing the web chat integration. + + :param ChannelTransferTargetChat chat: (optional) Information for transferring + to the web chat integration. + """ + + def __init__( + self, + *, + chat: Optional['ChannelTransferTargetChat'] = None, + ) -> None: + """ + Initialize a ChannelTransferTarget object. + + :param ChannelTransferTargetChat chat: (optional) Information for + transferring to the web chat integration. + """ + self.chat = chat + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': + """Initialize a ChannelTransferTarget object from a json dictionary.""" + args = {} + if (chat := _dict.get('chat')) is not None: + args['chat'] = ChannelTransferTargetChat.from_dict(chat) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferTarget object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'chat') and self.chat is not None: + if isinstance(self.chat, dict): + _dict['chat'] = self.chat + else: + _dict['chat'] = self.chat.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ChannelTransferTarget object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferTarget') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ChannelTransferTarget') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferTargetChat: + """ + Information for transferring to the web chat integration. + + :param str url: (optional) The URL of the target web chat. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ChannelTransferTargetChat object. + + :param str url: (optional) The URL of the target web chat. + """ + self.url = url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ChannelTransferTargetChat object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferTargetChat') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClientAction: + """ + ClientAction. + + :param str name: (optional) The name of the client action. + :param str result_variable: (optional) The name of the variable that the results + are stored in. + :param str type: (optional) The type of turn event. + :param str skill: (optional) The skill that is requesting the action. Included + only if **type**=`client`. + :param dict parameters: (optional) An object containing arbitrary variables that + are included in the turn event. + """ + + def __init__( + self, + *, + name: Optional[str] = None, + result_variable: Optional[str] = None, + type: Optional[str] = None, + skill: Optional[str] = None, + parameters: Optional[dict] = None, + ) -> None: + """ + Initialize a ClientAction object. + + :param str name: (optional) The name of the client action. + :param str result_variable: (optional) The name of the variable that the + results are stored in. + :param str type: (optional) The type of turn event. + :param str skill: (optional) The skill that is requesting the action. + Included only if **type**=`client`. + :param dict parameters: (optional) An object containing arbitrary variables + that are included in the turn event. + """ + self.name = name + self.result_variable = result_variable + self.type = type + self.skill = skill + self.parameters = parameters + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClientAction': + """Initialize a ClientAction object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + if (type := _dict.get('type')) is not None: + args['type'] = type + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClientAction object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClientAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClientAction') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClientAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class SkillEnum(str, Enum): + """ + The skill that is requesting the action. Included only if **type**=`client`. + """ + + MAIN_SKILL = 'main skill' + ACTIONS_SKILL = 'actions skill' + + +class CreateAssistantReleaseImportResponse: + """ + CreateAssistantReleaseImportResponse. + + :param str status: (optional) The current status of the artifact import process: + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import artifact is underway and + not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__( + self, + *, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: + """ + Initialize a CreateAssistantReleaseImportResponse object. + + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. + """ + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.skill_impact_in_draft = skill_impact_in_draft + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateAssistantReleaseImportResponse': + """Initialize a CreateAssistantReleaseImportResponse object from a json dictionary.""" + args = {} + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateAssistantReleaseImportResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateAssistantReleaseImportResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateAssistantReleaseImportResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateAssistantReleaseImportResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the artifact import process: + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import artifact is underway and + not yet completed. + """ + + FAILED = 'Failed' + PROCESSING = 'Processing' + + class SkillImpactInDraftEnum(str, Enum): + """ + The type of the skill in the draft environment. + """ + + ACTION = 'action' + DIALOG = 'dialog' + + +class CreateReleaseExportWithStatusErrors: + """ + CreateReleaseExportWithStatusErrors. + + :param str status: (optional) The current status of the release export creation + process: + - **Available**: The release export package is available for download. + - **Failed**: The asynchronous release export package creation process has + failed. + - **Processing**: An asynchronous operation to create the release export + package is underway and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + """ + + def __init__( + self, + *, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + release: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + ) -> None: + """ + Initialize a CreateReleaseExportWithStatusErrors object. + + """ + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.release = release + self.created = created + self.updated = updated + self.status_errors = status_errors + self.status_description = status_description + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateReleaseExportWithStatusErrors': + """Initialize a CreateReleaseExportWithStatusErrors object from a json dictionary.""" + args = {} + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (release := _dict.get('release')) is not None: + args['release'] = release + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateReleaseExportWithStatusErrors object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateReleaseExportWithStatusErrors object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateReleaseExportWithStatusErrors') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateReleaseExportWithStatusErrors') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release export creation process: + - **Available**: The release export package is available for download. + - **Failed**: The asynchronous release export package creation process has + failed. + - **Processing**: An asynchronous operation to create the release export package + is underway and not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class DialogLogMessage: + """ + Dialog log message details. + + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error message + belongs. + :param LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. + """ + + def __init__( + self, + level: str, + message: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: + """ + Initialize a DialogLogMessage object. + + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. + """ + self.level = level + self.message = message + self.code = code + self.source = source + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': + """Initialize a DialogLogMessage object from a json dictionary.""" + args = {} + if (level := _dict.get('level')) is not None: + args['level'] = level + else: + raise ValueError( + 'Required property \'level\' not present in DialogLogMessage JSON' + ) + if (message := _dict.get('message')) is not None: + args['message'] = message + else: + raise ValueError( + 'Required property \'message\' not present in DialogLogMessage JSON' + ) + if (code := _dict.get('code')) is not None: + args['code'] = code + else: + raise ValueError( + 'Required property \'code\' not present in DialogLogMessage JSON' + ) + if (source := _dict.get('source')) is not None: + args['source'] = LogMessageSource.from_dict(source) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogLogMessage object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'level') and self.level is not None: + _dict['level'] = self.level + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogLogMessage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogLogMessage') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogLogMessage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class LevelEnum(str, Enum): + """ + The severity of the log message. + """ + + INFO = 'info' + ERROR = 'error' + WARN = 'warn' + + +class DialogNodeAction: + """ + DialogNodeAction. + + :param str name: The name of the action. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided to + the action. + :param str result_variable: The location in the dialog context where the result + of the action is stored. + :param str credentials: (optional) The name of the context variable that the + client application will use to pass in credentials for the action. + """ + + def __init__( + self, + name: str, + result_variable: str, + *, + type: Optional[str] = None, + parameters: Optional[dict] = None, + credentials: Optional[str] = None, + ) -> None: + """ + Initialize a DialogNodeAction object. + + :param str name: The name of the action. + :param str result_variable: The location in the dialog context where the + result of the action is stored. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided + to the action. + :param str credentials: (optional) The name of the context variable that + the client application will use to pass in credentials for the action. + """ + self.name = name + self.type = type + self.parameters = parameters + self.result_variable = result_variable + self.credentials = credentials + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': + """Initialize a DialogNodeAction object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in DialogNodeAction JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + else: + raise ValueError( + 'Required property \'result_variable\' not present in DialogNodeAction JSON' + ) + if (credentials := _dict.get('credentials')) is not None: + args['credentials'] = credentials + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeAction object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'credentials') and self.credentials is not None: + _dict['credentials'] = self.credentials + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogNodeAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogNodeAction') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogNodeAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of action to invoke. + """ + + CLIENT = 'client' + SERVER = 'server' + WEB_ACTION = 'web-action' + CLOUD_FUNCTION = 'cloud-function' + + +class DialogNodeOutputConnectToAgentTransferInfo: + """ + Routing or other contextual information to be used by target service desk systems. + + :param dict target: (optional) + """ + + def __init__( + self, + *, + target: Optional[dict] = None, + ) -> None: + """ + Initialize a DialogNodeOutputConnectToAgentTransferInfo object. + + :param dict target: (optional) + """ + self.target = target + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + args = {} + if (target := _dict.get('target')) is not None: + args['target'] = target + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogNodeOutputOptionsElement: + """ + DialogNodeOutputOptionsElement. + + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the message + input to be sent to the assistant if the user selects the corresponding option. + """ + + def __init__( + self, + label: str, + value: 'DialogNodeOutputOptionsElementValue', + ) -> None: + """ + Initialize a DialogNodeOutputOptionsElement object. + + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the + message input to be sent to the assistant if the user selects the + corresponding option. + """ + self.label = label + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': + """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + args = {} + if (label := _dict.get('label')) is not None: + args['label'] = label + else: + raise ValueError( + 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' + ) + if (value := _dict.get('value')) is not None: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict(value) + else: + raise ValueError( + 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogNodeOutputOptionsElement object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogNodeOutputOptionsElementValue: + """ + An object defining the message input to be sent to the assistant if the user selects + the corresponding option. + + :param MessageInput input: (optional) An input object that includes the input + text. + """ + + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + ) -> None: + """ + Initialize a DialogNodeOutputOptionsElementValue object. + + :param MessageInput input: (optional) An input object that includes the + input text. + """ + self.input = input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': + """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + args = {} + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogNodeVisited: + """ + An objects containing detailed diagnostic information about a dialog node that was + visited during processing of the input message. + + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog node. + """ + + def __init__( + self, + *, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + conditions: Optional[str] = None, + ) -> None: + """ + Initialize a DialogNodeVisited object. + + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog + node. + """ + self.dialog_node = dialog_node + self.title = title + self.conditions = conditions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': + """Initialize a DialogNodeVisited object from a json dictionary.""" + args = {} + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeVisited object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'conditions') and self.conditions is not None: + _dict['conditions'] = self.conditions + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogNodeVisited object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogNodeVisited') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogNodeVisited') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogSuggestion: + """ + DialogSuggestion. + + :param str label: The user-facing label for the suggestion. This label is taken + from the **title** or **user_label** property of the corresponding dialog node, + depending on the disambiguation options. + :param DialogSuggestionValue value: An object defining the message input to be + sent to the assistant if the user selects the corresponding disambiguation + option. + **Note:** This entire message input object must be included in the request body + of the next message sent to the assistant. Do not modify or remove any of the + included properties. + :param dict output: (optional) The dialog output that will be returned from the + watsonx Assistant service if the user selects the corresponding option. + """ + + def __init__( + self, + label: str, + value: 'DialogSuggestionValue', + *, + output: Optional[dict] = None, + ) -> None: + """ + Initialize a DialogSuggestion object. + + :param str label: The user-facing label for the suggestion. This label is + taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. + :param DialogSuggestionValue value: An object defining the message input to + be sent to the assistant if the user selects the corresponding + disambiguation option. + **Note:** This entire message input object must be included in the request + body of the next message sent to the assistant. Do not modify or remove any + of the included properties. + :param dict output: (optional) The dialog output that will be returned from + the watsonx Assistant service if the user selects the corresponding option. + """ + self.label = label + self.value = value + self.output = output + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': + """Initialize a DialogSuggestion object from a json dictionary.""" + args = {} + if (label := _dict.get('label')) is not None: + args['label'] = label + else: + raise ValueError( + 'Required property \'label\' not present in DialogSuggestion JSON' + ) + if (value := _dict.get('value')) is not None: + args['value'] = DialogSuggestionValue.from_dict(value) + else: + raise ValueError( + 'Required property \'value\' not present in DialogSuggestion JSON' + ) + if (output := _dict.get('output')) is not None: + args['output'] = output + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestion object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() + if hasattr(self, 'output') and self.output is not None: + _dict['output'] = self.output + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogSuggestion object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogSuggestion') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogSuggestion') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogSuggestionValue: + """ + An object defining the message input to be sent to the assistant if the user selects + the corresponding disambiguation option. + **Note:** This entire message input object must be included in the request body of + the next message sent to the assistant. Do not modify or remove any of the included + properties. + + :param MessageInput input: (optional) An input object that includes the input + text. + """ + + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + ) -> None: + """ + Initialize a DialogSuggestionValue object. + + :param MessageInput input: (optional) An input object that includes the + input text. + """ + self.input = input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': + """Initialize a DialogSuggestionValue object from a json dictionary.""" + args = {} + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionValue object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DialogSuggestionValue object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DialogSuggestionValue') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DialogSuggestionValue') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DtmfCommandInfo: + """ + DtmfCommandInfo. + + :param str type: Specifies the type of DTMF command for the phone integration. + :param dict parameters: (optional) Parameters specified by the command type. + """ + + def __init__( + self, + type: str, + *, + parameters: Optional[dict] = None, + ) -> None: + """ + Initialize a DtmfCommandInfo object. + + :param str type: Specifies the type of DTMF command for the phone + integration. + :param dict parameters: (optional) Parameters specified by the command + type. + """ + self.type = type + self.parameters = parameters + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DtmfCommandInfo': + """Initialize a DtmfCommandInfo object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in DtmfCommandInfo JSON' + ) + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DtmfCommandInfo object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DtmfCommandInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DtmfCommandInfo') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DtmfCommandInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + Specifies the type of DTMF command for the phone integration. + """ + + COLLECT = 'collect' + DISABLE_BARGE_IN = 'disable_barge_in' + ENABLE_BARGE_IN = 'enable_barge_in' + SEND = 'send' + + +class Environment: + """ + Environment. + + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param str assistant_id: (optional) The assistant ID of the assistant the + environment is associated with. + :param str environment_id: (optional) The environment ID of the environment. + :param str environment: (optional) The type of the environment. All environments + other than the `draft` and `live` environments have the type `staging`. + :param BaseEnvironmentReleaseReference release_reference: (optional) An object + describing the release that is currently deployed in the environment. + :param BaseEnvironmentOrchestration orchestration: The search skill + orchestration settings for the environment. + :param int session_timeout: The session inactivity timeout setting for the + environment (in seconds). + :param List[IntegrationReference] integration_references: (optional) An array of + objects describing the integrations that exist in the environment. + :param List[EnvironmentSkill] skill_references: An array of objects identifying + the skills (such as action and dialog) that exist in the environment. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__( + self, + orchestration: 'BaseEnvironmentOrchestration', + session_timeout: int, + skill_references: List['EnvironmentSkill'], + *, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_id: Optional[str] = None, + environment_id: Optional[str] = None, + environment: Optional[str] = None, + release_reference: Optional['BaseEnvironmentReleaseReference'] = None, + integration_references: Optional[List['IntegrationReference']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: + """ + Initialize a Environment object. + + :param BaseEnvironmentOrchestration orchestration: The search skill + orchestration settings for the environment. + :param int session_timeout: The session inactivity timeout setting for the + environment (in seconds). + :param List[EnvironmentSkill] skill_references: An array of objects + identifying the skills (such as action and dialog) that exist in the + environment. + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + """ + self.name = name + self.description = description + self.assistant_id = assistant_id + self.environment_id = environment_id + self.environment = environment + self.release_reference = release_reference + self.orchestration = orchestration + self.session_timeout = session_timeout + self.integration_references = integration_references + self.skill_references = skill_references + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Environment': + """Initialize a Environment object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (environment := _dict.get('environment')) is not None: + args['environment'] = environment + if (release_reference := _dict.get('release_reference')) is not None: + args[ + 'release_reference'] = BaseEnvironmentReleaseReference.from_dict( + release_reference) + if (orchestration := _dict.get('orchestration')) is not None: + args['orchestration'] = BaseEnvironmentOrchestration.from_dict( + orchestration) + else: + raise ValueError( + 'Required property \'orchestration\' not present in Environment JSON' + ) + if (session_timeout := _dict.get('session_timeout')) is not None: + args['session_timeout'] = session_timeout + else: + raise ValueError( + 'Required property \'session_timeout\' not present in Environment JSON' + ) + if (integration_references := + _dict.get('integration_references')) is not None: + args['integration_references'] = [ + IntegrationReference.from_dict(v) + for v in integration_references + ] + if (skill_references := _dict.get('skill_references')) is not None: + args['skill_references'] = [ + EnvironmentSkill.from_dict(v) for v in skill_references + ] + else: + raise ValueError( + 'Required property \'skill_references\' not present in Environment JSON' + ) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Environment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') + if hasattr(self, 'release_reference') and getattr( + self, 'release_reference') is not None: + if isinstance(getattr(self, 'release_reference'), dict): + _dict['release_reference'] = getattr(self, 'release_reference') + else: + _dict['release_reference'] = getattr( + self, 'release_reference').to_dict() + if hasattr(self, 'orchestration') and self.orchestration is not None: + if isinstance(self.orchestration, dict): + _dict['orchestration'] = self.orchestration + else: + _dict['orchestration'] = self.orchestration.to_dict() + if hasattr(self, + 'session_timeout') and self.session_timeout is not None: + _dict['session_timeout'] = self.session_timeout + if hasattr(self, 'integration_references') and getattr( + self, 'integration_references') is not None: + integration_references_list = [] + for v in getattr(self, 'integration_references'): + if isinstance(v, dict): + integration_references_list.append(v) + else: + integration_references_list.append(v.to_dict()) + _dict['integration_references'] = integration_references_list + if hasattr(self, + 'skill_references') and self.skill_references is not None: + skill_references_list = [] + for v in self.skill_references: + if isinstance(v, dict): + skill_references_list.append(v) + else: + skill_references_list.append(v.to_dict()) + _dict['skill_references'] = skill_references_list + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Environment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Environment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Environment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnvironmentCollection: + """ + EnvironmentCollection. + + :param List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + environments: List['Environment'], + pagination: 'Pagination', + ) -> None: + """ + Initialize a EnvironmentCollection object. + + :param List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.environments = environments + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': + """Initialize a EnvironmentCollection object from a json dictionary.""" + args = {} + if (environments := _dict.get('environments')) is not None: + args['environments'] = [ + Environment.from_dict(v) for v in environments + ] + else: + raise ValueError( + 'Required property \'environments\' not present in EnvironmentCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in EnvironmentCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnvironmentCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'environments') and self.environments is not None: + environments_list = [] + for v in self.environments: + if isinstance(v, dict): + environments_list.append(v) + else: + environments_list.append(v.to_dict()) + _dict['environments'] = environments_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnvironmentCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnvironmentCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnvironmentCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnvironmentReference: + """ + EnvironmentReference. + + :param str name: (optional) The name of the environment. + :param str environment_id: (optional) The unique identifier of the environment. + :param str environment: (optional) The type of the environment. All environments + other than the draft and live environments have the type `staging`. + """ + + def __init__( + self, + *, + name: Optional[str] = None, + environment_id: Optional[str] = None, + environment: Optional[str] = None, + ) -> None: + """ + Initialize a EnvironmentReference object. + + :param str name: (optional) The name of the environment. + """ + self.name = name + self.environment_id = environment_id + self.environment = environment + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': + """Initialize a EnvironmentReference object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (environment := _dict.get('environment')) is not None: + args['environment'] = environment + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnvironmentReference object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnvironmentReference object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnvironmentReference') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnvironmentReference') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class EnvironmentEnum(str, Enum): + """ + The type of the environment. All environments other than the draft and live + environments have the type `staging`. + """ + + DRAFT = 'draft' + LIVE = 'live' + STAGING = 'staging' + + +class EnvironmentSkill: + """ + EnvironmentSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled skill + in the draft environment does not handle any messages at run time, and it is not + included in saved releases. + :param str snapshot: (optional) The name of the skill snapshot that is deployed + to the environment (for example, `draft` or `1`). + :param str skill_reference: (optional) The type of skill identified by the skill + reference. The possible values are `main skill` (for a dialog skill), `actions + skill`, and `search skill`. + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + disabled: Optional[bool] = None, + snapshot: Optional[str] = None, + skill_reference: Optional[str] = None, + ) -> None: + """ + Initialize a EnvironmentSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled + skill in the draft environment does not handle any messages at run time, + and it is not included in saved releases. + :param str snapshot: (optional) The name of the skill snapshot that is + deployed to the environment (for example, `draft` or `1`). + :param str skill_reference: (optional) The type of skill identified by the + skill reference. The possible values are `main skill` (for a dialog skill), + `actions skill`, and `search skill`. + """ + self.skill_id = skill_id + self.type = type + self.disabled = disabled + self.snapshot = snapshot + self.skill_reference = skill_reference + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnvironmentSkill': + """Initialize a EnvironmentSkill object from a json dictionary.""" + args = {} + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in EnvironmentSkill JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (disabled := _dict.get('disabled')) is not None: + args['disabled'] = disabled + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + if (skill_reference := _dict.get('skill_reference')) is not None: + args['skill_reference'] = skill_reference + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnvironmentSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'disabled') and self.disabled is not None: + _dict['disabled'] = self.disabled + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'skill_reference') and self.skill_reference is not None: + _dict['skill_reference'] = self.skill_reference + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnvironmentSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnvironmentSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnvironmentSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class FinalResponse: + """ + Message final response content. + + :param FinalResponseOutput output: (optional) Assistant output to be rendered or + processed by the client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + """ + + def __init__( + self, + *, + output: Optional['FinalResponseOutput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + ) -> None: + """ + Initialize a FinalResponse object. + + :param FinalResponseOutput output: (optional) Assistant output to be + rendered or processed by the client. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + """ + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'FinalResponse': + """Initialize a FinalResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = FinalResponseOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a FinalResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this FinalResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'FinalResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'FinalResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class FinalResponseOutput: + """ + Assistant output to be rendered or processed by the client. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + :param MessageStreamMetadata streaming_metadata: Contains meta-information about + the item(s) being streamed. + """ + + def __init__( + self, + streaming_metadata: 'MessageStreamMetadata', + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, + ) -> None: + """ + Initialize a FinalResponseOutput object. + + :param MessageStreamMetadata streaming_metadata: Contains meta-information + about the item(s) being streamed. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata + self.streaming_metadata = streaming_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'FinalResponseOutput': + """Initialize a FinalResponseOutput object from a json dictionary.""" + args = {} + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = MessageStreamMetadata.from_dict( + streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in FinalResponseOutput JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a FinalResponseOutput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this FinalResponseOutput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'FinalResponseOutput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'FinalResponseOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class GenerativeAITask: + """ + GenerativeAITask. + + """ + + def __init__(self,) -> None: + """ + Initialize a GenerativeAITask object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'GenerativeAITaskContentGroundedAnswering', + 'GenerativeAITaskGeneralPurposeAnswering' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'GenerativeAITask': + """Initialize a GenerativeAITask object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'GenerativeAITask'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'GenerativeAITaskContentGroundedAnswering', + 'GenerativeAITaskGeneralPurposeAnswering' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a GenerativeAITask object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'content_grounded_answering'] = 'GenerativeAITaskContentGroundedAnswering' + mapping[ + 'general_purpose_answering'] = 'GenerativeAITaskGeneralPurposeAnswering' + disc_value = _dict.get('task') + if disc_value is None: + raise ValueError( + 'Discriminator property \'task\' not found in GenerativeAITask JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class GenerativeAITaskConfidenceScores: + """ + The confidence scores for determining whether to show the generated response or an “I + don't know” response. + + :param float pre_gen: (optional) The confidence score based on user query and + search results. + :param float pre_gen_threshold: (optional) The pre_gen confidence score + threshold. If the pre_gen score is below this threshold, it shows an “I don't + know” response instead of the generated response. Shown in the conversational + search skill UI as the “Retrieval Confidence threshold”. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float post_gen_threshold: (optional) The post_gen confidence score + threshold. If the post_gen score is below this threshold, it shows an “I don't + know” response instead of the generated response. Shown in the conversational + search skill UI as the “Response Confidence threshold”. + """ + + def __init__( + self, + *, + pre_gen: Optional[float] = None, + pre_gen_threshold: Optional[float] = None, + post_gen: Optional[float] = None, + post_gen_threshold: Optional[float] = None, + ) -> None: + """ + Initialize a GenerativeAITaskConfidenceScores object. + + :param float pre_gen: (optional) The confidence score based on user query + and search results. + :param float pre_gen_threshold: (optional) The pre_gen confidence score + threshold. If the pre_gen score is below this threshold, it shows an “I + don't know” response instead of the generated response. Shown in the + conversational search skill UI as the “Retrieval Confidence threshold”. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float post_gen_threshold: (optional) The post_gen confidence score + threshold. If the post_gen score is below this threshold, it shows an “I + don't know” response instead of the generated response. Shown in the + conversational search skill UI as the “Response Confidence threshold”. + """ + self.pre_gen = pre_gen + self.pre_gen_threshold = pre_gen_threshold + self.post_gen = post_gen + self.post_gen_threshold = post_gen_threshold + + @classmethod + def from_dict(cls, _dict: Dict) -> 'GenerativeAITaskConfidenceScores': + """Initialize a GenerativeAITaskConfidenceScores object from a json dictionary.""" + args = {} + if (pre_gen := _dict.get('pre_gen')) is not None: + args['pre_gen'] = pre_gen + if (pre_gen_threshold := _dict.get('pre_gen_threshold')) is not None: + args['pre_gen_threshold'] = pre_gen_threshold + if (post_gen := _dict.get('post_gen')) is not None: + args['post_gen'] = post_gen + if (post_gen_threshold := _dict.get('post_gen_threshold')) is not None: + args['post_gen_threshold'] = post_gen_threshold + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a GenerativeAITaskConfidenceScores object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'pre_gen') and self.pre_gen is not None: + _dict['pre_gen'] = self.pre_gen + if hasattr(self, + 'pre_gen_threshold') and self.pre_gen_threshold is not None: + _dict['pre_gen_threshold'] = self.pre_gen_threshold + if hasattr(self, 'post_gen') and self.post_gen is not None: + _dict['post_gen'] = self.post_gen + if hasattr( + self, + 'post_gen_threshold') and self.post_gen_threshold is not None: + _dict['post_gen_threshold'] = self.post_gen_threshold + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this GenerativeAITaskConfidenceScores object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'GenerativeAITaskConfidenceScores') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'GenerativeAITaskConfidenceScores') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class IntegrationReference: + """ + IntegrationReference. + + :param str integration_id: (optional) The integration ID of the integration. + :param str type: (optional) The type of the integration. + """ + + def __init__( + self, + *, + integration_id: Optional[str] = None, + type: Optional[str] = None, + ) -> None: + """ + Initialize a IntegrationReference object. + + :param str integration_id: (optional) The integration ID of the + integration. + :param str type: (optional) The type of the integration. + """ + self.integration_id = integration_id + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'IntegrationReference': + """Initialize a IntegrationReference object from a json dictionary.""" + args = {} + if (integration_id := _dict.get('integration_id')) is not None: + args['integration_id'] = integration_id + if (type := _dict.get('type')) is not None: + args['type'] = type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a IntegrationReference object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'integration_id') and self.integration_id is not None: + _dict['integration_id'] = self.integration_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this IntegrationReference object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'IntegrationReference') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'IntegrationReference') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Log: + """ + Log. + + :param str log_id: A unique identifier for the logged event. + :param LogRequest request: A message request formatted for the watsonx Assistant + service. + :param LogResponse response: A response from the watsonx Assistant service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to the + message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message request + was made. + :param str customer_id: (optional) The customer ID specified for the message, if + any. + """ + + def __init__( + self, + log_id: str, + request: 'LogRequest', + response: 'LogResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, + *, + customer_id: Optional[str] = None, + ) -> None: + """ + Initialize a Log object. + + :param str log_id: A unique identifier for the logged event. + :param LogRequest request: A message request formatted for the watsonx + Assistant service. + :param LogResponse response: A response from the watsonx Assistant service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. + """ + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id + self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" + args = {} + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if (request := _dict.get('request')) is not None: + args['request'] = LogRequest.from_dict(request) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if (response := _dict.get('response')) is not None: + args['response'] = LogResponse.from_dict(response) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if (customer_id := _dict.get('customer_id')) is not None: + args['customer_id'] = customer_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Log object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Log object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Log') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Log') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogCollection: + """ + LogCollection. + + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + logs: List['Log'], + pagination: 'LogPagination', + ) -> None: + """ + Initialize a LogCollection object. + + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. For more information about using pagination, see + [Pagination](#pagination). + """ + self.logs = logs + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" + args = {} + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] + else: + raise ValueError( + 'Required property \'logs\' not present in LogCollection JSON') + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in LogCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'logs') and self.logs is not None: + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSource: + """ + An object that identifies the dialog element that generated the error message. + + """ + + def __init__(self,) -> None: + """ + Initialize a LogMessageSource object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'LogMessageSource'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a LogMessageSource object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['dialog_node'] = 'LogMessageSourceDialogNode' + mapping['action'] = 'LogMessageSourceAction' + mapping['step'] = 'LogMessageSourceStep' + mapping['handler'] = 'LogMessageSourceHandler' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in LogMessageSource JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class LogPagination: + """ + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). + + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. + """ + + def __init__( + self, + *, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, + ) -> None: + """ + Initialize a LogPagination object. + + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of + results. + """ + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" + args = {} + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogPagination object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogPagination object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogPagination') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogPagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogRequest: + """ + A message request formatted for the watsonx Assistant service. + + :param LogRequestInput input: (optional) An input object that includes the input + text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. + """ + + def __init__( + self, + *, + input: Optional['LogRequestInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + ) -> None: + """ + Initialize a LogRequest object. + + :param LogRequestInput input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. + """ + self.input = input + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogRequest': + """Initialize a LogRequest object from a json dictionary.""" + args = {} + if (input := _dict.get('input')) is not None: + args['input'] = LogRequestInput.from_dict(input) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogRequest object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogRequest object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogRequest') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogRequestInput: + """ + An input object that includes the input text. All private data is masked or removed. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. + """ + + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, + ) -> None: + """ + Initialize a LogRequestInput object. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogRequestInput': + """Initialize a LogRequestInput object from a json dictionary.""" + args = {} + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogRequestInput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogRequestInput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogRequestInput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogRequestInput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + + +class LogResponse: + """ + A response from the watsonx Assistant service. + + :param LogResponseOutput output: Assistant output to be rendered or processed by + the client. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ + + def __init__( + self, + output: 'LogResponseOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + ) -> None: + """ + Initialize a LogResponse object. + + :param LogResponseOutput output: Assistant output to be rendered or + processed by the client. All private data is masked or removed. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + """ + self.output = output + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogResponse': + """Initialize a LogResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = LogResponseOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in LogResponse JSON') + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + else: + raise ValueError( + 'Required property \'user_id\' not present in LogResponse JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogResponseOutput: + """ + Assistant output to be rendered or processed by the client. All private data is masked + or removed. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + + def __init__( + self, + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, + ) -> None: + """ + Initialize a LogResponseOutput object. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogResponseOutput': + """Initialize a LogResponseOutput object from a json dictionary.""" + args = {} + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogResponseOutput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogResponseOutput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogResponseOutput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogResponseOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContext: + """ + MessageContext. + + :param MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + + def __init__( + self, + *, + global_: Optional['MessageContextGlobal'] = None, + skills: Optional['MessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: + """ + Initialize a MessageContext object. + + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + self.global_ = global_ + self.skills = skills + self.integrations = integrations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" + args = {} + if (global_ := _dict.get('global')) is not None: + args['global_'] = MessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = MessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContext object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContext object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContext') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContext') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextActionSkill: + """ + Context variables that are used by the action skill. Private variables are persisted, + but not shown. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + """ + + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + ) -> None: + """ + Initialize a MessageContextActionSkill object. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + """ + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextActionSkill': + """Initialize a MessageContextActionSkill object from a json dictionary.""" + args = {} + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextActionSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextActionSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextActionSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextActionSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextDialogSkill: + """ + Context variables that are used by the dialog skill. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + """ + + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + ) -> None: + """ + Initialize a MessageContextDialogSkill object. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + """ + self.user_defined = user_defined + self.system = system + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextDialogSkill': + """Initialize a MessageContextDialogSkill object from a json dictionary.""" + args = {} + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextDialogSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextDialogSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextDialogSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextDialogSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextGlobal: + """ + Session context data that is shared by all skills used by the assistant. + + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The session ID. + """ + + def __init__( + self, + *, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, + ) -> None: + """ + Initialize a MessageContextGlobal object. + + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + """ + self.system = system + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" + args = {} + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextGlobal object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextGlobal object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextGlobal') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextGlobal') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextGlobalSystem: + """ + Built-in system properties that apply to all skills used by the assistant. + + :param str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically incremented + with each turn of the conversation. A value of 1 indicates that this is the the + first turn of a new conversation, which can affect the behavior of some skills + (for example, triggering the start node of a dialog). + :param str locale: (optional) The language code for localization in the user + input. The specified locale overrides the default for the assistant, and is used + for interpreting entity values in user input such as date values. For example, + `04/03/2018` might be interpreted either as April 3 or March 4, depending on the + locale. + This property is included only if the new system entities are enabled for the + skill. + :param str reference_time: (optional) The base time for interpreting any + relative time mentions in the user input. The specified time overrides the + current server time, and is used to calculate times mentioned in relative terms + such as `now` or `tomorrow`. This can be useful for simulating past or future + times for testing purposes, or when analyzing documents such as news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :param str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :param bool skip_user_input: (optional) For internal use only. + """ + + def __init__( + self, + *, + timezone: Optional[str] = None, + user_id: Optional[str] = None, + turn_count: Optional[int] = None, + locale: Optional[str] = None, + reference_time: Optional[str] = None, + session_start_time: Optional[str] = None, + state: Optional[str] = None, + skip_user_input: Optional[bool] = None, + ) -> None: + """ + Initialize a MessageContextGlobalSystem object. + + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented with each turn of the conversation. A value of 1 indicates that + this is the the first turn of a new conversation, which can affect the + behavior of some skills (for example, triggering the start node of a + dialog). + :param str locale: (optional) The language code for localization in the + user input. The specified locale overrides the default for the assistant, + and is used for interpreting entity values in user input such as date + values. For example, `04/03/2018` might be interpreted either as April 3 or + March 4, depending on the locale. + This property is included only if the new system entities are enabled for + the skill. + :param str reference_time: (optional) The base time for interpreting any + relative time mentions in the user input. The specified time overrides the + current server time, and is used to calculate times mentioned in relative + terms such as `now` or `tomorrow`. This can be useful for simulating past + or future times for testing purposes, or when analyzing documents such as + news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. + """ + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + args = {} + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (turn_count := _dict.get('turn_count')) is not None: + args['turn_count'] = turn_count + if (locale := _dict.get('locale')) is not None: + args['locale'] = locale + if (reference_time := _dict.get('reference_time')) is not None: + args['reference_time'] = reference_time + if (session_start_time := _dict.get('session_start_time')) is not None: + args['session_start_time'] = session_start_time + if (state := _dict.get('state')) is not None: + args['state'] = state + if (skip_user_input := _dict.get('skip_user_input')) is not None: + args['skip_user_input'] = skip_user_input + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'turn_count') and self.turn_count is not None: + _dict['turn_count'] = self.turn_count + if hasattr(self, 'locale') and self.locale is not None: + _dict['locale'] = self.locale + if hasattr(self, 'reference_time') and self.reference_time is not None: + _dict['reference_time'] = self.reference_time + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextGlobalSystem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class LocaleEnum(str, Enum): + """ + The language code for localization in the user input. The specified locale + overrides the default for the assistant, and is used for interpreting entity + values in user input such as date values. For example, `04/03/2018` might be + interpreted either as April 3 or March 4, depending on the locale. + This property is included only if the new system entities are enabled for the + skill. + """ + + EN_US = 'en-us' + EN_CA = 'en-ca' + EN_GB = 'en-gb' + AR_AR = 'ar-ar' + CS_CZ = 'cs-cz' + DE_DE = 'de-de' + ES_ES = 'es-es' + FR_FR = 'fr-fr' + IT_IT = 'it-it' + JA_JP = 'ja-jp' + KO_KR = 'ko-kr' + NL_NL = 'nl-nl' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + + +class MessageContextSkillSystem: + """ + System context data used by the skill. + + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + + This type supports additional properties of type object. For internal use only. + """ + + # The set of defined properties for the class + _properties = frozenset(['state']) + + def __init__( + self, + *, + state: Optional[str] = None, + **kwargs: Optional[object], + ) -> None: + """ + Initialize a MessageContextSkillSystem object. + + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param object **kwargs: (optional) For internal use only. + """ + self.state = state + for k, v in kwargs.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + args = {} + if (state := _dict.get('state')) is not None: + args['state'] = state + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return the additional properties from this instance of MessageContextSkillSystem in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of MessageContextSkillSystem""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkills: + """ + Context data specific to particular skills used by the assistant. + + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context variables + that are used by the action skill. Private variables are persisted, but not + shown. + """ + + def __init__( + self, + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional['MessageContextActionSkill'] = None, + ) -> None: + """ + Initialize a MessageContextSkills object. + + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context + variables that are used by the action skill. Private variables are + persisted, but not shown. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': + """Initialize a MessageContextSkills object from a json dictionary.""" + args = {} + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args['actions_skill'] = MessageContextActionSkill.from_dict( + actions_skill) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkills object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkills object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkills') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkills') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInput: + """ + An input object that includes the input text. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. + """ + + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, + ) -> None: + """ + Initialize a MessageInput object. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInput': + """Initialize a MessageInput object from a json dictionary.""" + args = {} + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + + +class MessageInputAttachment: + """ + A reference to a media file to be sent as an attachment with the message. + + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME type) + of the attachment. + """ + + def __init__( + self, + url: str, + *, + media_type: Optional[str] = None, + ) -> None: + """ + Initialize a MessageInputAttachment object. + + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME + type) of the attachment. + """ + self.url = url + self.media_type = media_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': + """Initialize a MessageInputAttachment object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in MessageInputAttachment JSON' + ) + if (media_type := _dict.get('media_type')) is not None: + args['media_type'] = media_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputAttachment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'media_type') and self.media_type is not None: + _dict['media_type'] = self.media_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputAttachment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputAttachment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputAttachment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputOptions: + """ + Optional properties that control how the assistant responds. + + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context with + the response. If you specify `true`, the response includes the `context` + property. If you also specify **debug**=`true`, the returned skill context + includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including full + conversation state. If you specify `true`, the response includes the `context` + property, and the skill context includes the `system.state` property. + **Note:** If **export**=`true`, the context is returned regardless of the value + of **return_context**. + """ + + def __init__( + self, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + return_context: Optional[bool] = None, + export: Optional[bool] = None, + ) -> None: + """ + Initialize a MessageInputOptions object. + + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context + with the response. If you specify `true`, the response includes the + `context` property. If you also specify **debug**=`true`, the returned + skill context includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including + full conversation state. If you specify `true`, the response includes the + `context` property, and the skill context includes the `system.state` + property. + **Note:** If **export**=`true`, the context is returned regardless of the + value of **return_context**. + """ + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug + self.return_context = return_context + self.export = export + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': + """Initialize a MessageInputOptions object from a json dictionary.""" + args = {} + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug + if (return_context := _dict.get('return_context')) is not None: + args['return_context'] = return_context + if (export := _dict.get('export')) is not None: + args['export'] = export + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + if hasattr(self, 'return_context') and self.return_context is not None: + _dict['return_context'] = self.return_context + if hasattr(self, 'export') and self.export is not None: + _dict['export'] = self.export + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputOptions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputOptions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputOptionsSpelling: + """ + Spelling correction options for the message. Any options specified on an individual + message override the settings configured for the skill. + + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** is + `true`, any spelling corrections are automatically applied to the user input. If + **auto_correct** is `false`, any suggested corrections are returned in the + **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property in + the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned in + the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings for the skill. + """ + + def __init__( + self, + *, + suggestions: Optional[bool] = None, + auto_correct: Optional[bool] = None, + ) -> None: + """ + Initialize a MessageInputOptionsSpelling object. + + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** + is `true`, any spelling corrections are automatically applied to the user + input. If **auto_correct** is `false`, any suggested corrections are + returned in the **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property + in the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned + in the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the + workspace settings for the skill. + """ + self.suggestions = suggestions + self.auto_correct = auto_correct + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + args = {} + if (suggestions := _dict.get('suggestions')) is not None: + args['suggestions'] = suggestions + if (auto_correct := _dict.get('auto_correct')) is not None: + args['auto_correct'] = auto_correct + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = self.suggestions + if hasattr(self, 'auto_correct') and self.auto_correct is not None: + _dict['auto_correct'] = self.auto_correct + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputOptionsSpelling object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageOutput: + """ + Assistant output to be rendered or processed by the client. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + + def __init__( + self, + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, + ) -> None: + """ + Initialize a MessageOutput object. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" + args = {} + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageOutputDebug: + """ + Additional detailed information about a message response and how it was generated. + + :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. + """ + + def __init__( + self, + *, + nodes_visited: Optional[List['DialogNodeVisited']] = None, + log_messages: Optional[List['DialogLogMessage']] = None, + branch_exited: Optional[bool] = None, + branch_exited_reason: Optional[str] = None, + turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, + ) -> None: + """ + Initialize a MessageOutputDebug object. + + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. + """ + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" + args = {} + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(v) for v in nodes_visited + ] + if (log_messages := _dict.get('log_messages')) is not None: + args['log_messages'] = [ + DialogLogMessage.from_dict(v) for v in log_messages + ] + if (branch_exited := _dict.get('branch_exited')) is not None: + args['branch_exited'] = branch_exited + if (branch_exited_reason := + _dict.get('branch_exited_reason')) is not None: + args['branch_exited_reason'] = branch_exited_reason + if (turn_events := _dict.get('turn_events')) is not None: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputDebug object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + nodes_visited_list = [] + for v in self.nodes_visited: + if isinstance(v, dict): + nodes_visited_list.append(v) + else: + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list + if hasattr(self, 'log_messages') and self.log_messages is not None: + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + turn_events_list = [] + for v in self.turn_events: + if isinstance(v, dict): + turn_events_list.append(v) + else: + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutputDebug object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutputDebug') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutputDebug') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class BranchExitedReasonEnum(str, Enum): + """ + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. + """ + + COMPLETED = 'completed' + FALLBACK = 'fallback' + + +class MessageOutputDebugTurnEvent: + """ + MessageOutputDebugTurnEvent. + + """ + + def __init__(self,) -> None: + """ + Initialize a MessageOutputDebugTurnEvent object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited', + 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd', + 'MessageOutputDebugTurnEventTurnEventManualRoute', + 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied', + 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied', + 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied', + 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled', + 'MessageOutputDebugTurnEventTurnEventClientActions' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited', + 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd', + 'MessageOutputDebugTurnEventTurnEventManualRoute', + 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied', + 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied', + 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied', + 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled', + 'MessageOutputDebugTurnEventTurnEventClientActions' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' + mapping[ + 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' + mapping[ + 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' + mapping[ + 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' + mapping[ + 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' + mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' + mapping[ + 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' + mapping[ + 'conversational_search_end'] = 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd' + mapping[ + 'manual_route'] = 'MessageOutputDebugTurnEventTurnEventManualRoute' + mapping[ + 'topic_switch_denied'] = 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied' + mapping[ + 'action_routing_denied'] = 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied' + mapping[ + 'suggestion_intents_denied'] = 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied' + mapping[ + 'generative_ai_called'] = 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled' + mapping[ + 'client_actions'] = 'MessageOutputDebugTurnEventTurnEventClientActions' + disc_value = _dict.get('event') + if disc_value is None: + raise ValueError( + 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class MessageOutputLLMMetadata: + """ + MessageOutputLLMMetadata. + + :param str task: (optional) The task that used a large language model. + :param str model_id: (optional) The id for the large language model used for the + task. + """ + + def __init__( + self, + *, + task: Optional[str] = None, + model_id: Optional[str] = None, + ) -> None: + """ + Initialize a MessageOutputLLMMetadata object. + + :param str task: (optional) The task that used a large language model. + :param str model_id: (optional) The id for the large language model used + for the task. + """ + self.task = task + self.model_id = model_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputLLMMetadata': + """Initialize a MessageOutputLLMMetadata object from a json dictionary.""" + args = {} + if (task := _dict.get('task')) is not None: + args['task'] = task + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputLLMMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'task') and self.task is not None: + _dict['task'] = self.task + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutputLLMMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutputLLMMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutputLLMMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageOutputSpelling: + """ + Properties describing any spelling corrections in the user input that was received. + + :param str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :param str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :param str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. + """ + + def __init__( + self, + *, + text: Optional[str] = None, + original_text: Optional[str] = None, + suggested_text: Optional[str] = None, + ) -> None: + """ + Initialize a MessageOutputSpelling object. + + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. + """ + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputSpelling object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutputSpelling object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutputSpelling') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutputSpelling') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageStreamMetadata: + """ + Contains meta-information about the item(s) being streamed. + + :param Metadata streaming_metadata: Contains meta-information about the item(s) + being streamed. + """ + + def __init__( + self, + streaming_metadata: 'Metadata', + ) -> None: + """ + Initialize a MessageStreamMetadata object. + + :param Metadata streaming_metadata: Contains meta-information about the + item(s) being streamed. + """ + self.streaming_metadata = streaming_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageStreamMetadata': + """Initialize a MessageStreamMetadata object from a json dictionary.""" + args = {} + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in MessageStreamMetadata JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageStreamMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageStreamMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageStreamMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageStreamMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageStreamResponse: + """ + A streamed response from the watsonx Assistant service. + + """ + + def __init__(self,) -> None: + """ + Initialize a MessageStreamResponse object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageStreamResponseMessageStreamPartialItem', + 'MessageStreamResponseMessageStreamCompleteItem', + 'MessageStreamResponseStatefulMessageStreamFinalResponse' + ])) + raise Exception(msg) + + +class Metadata: + """ + Contains meta-information about the item(s) being streamed. + + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. + """ + + def __init__( + self, + *, + id: Optional[int] = None, + ) -> None: + """ + Initialize a Metadata object. + + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. + """ + self.id = id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Metadata': + """Initialize a Metadata object from a json dictionary.""" + args = {} + if (id := _dict.get('id')) is not None: + args['id'] = id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Metadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Metadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Metadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Metadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MonitorAssistantReleaseImportArtifactResponse: + """ + MonitorAssistantReleaseImportArtifactResponse. + + :param str status: (optional) The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__( + self, + *, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: + """ + Initialize a MonitorAssistantReleaseImportArtifactResponse object. + + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. + """ + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.status_errors = status_errors + self.status_description = status_description + self.skill_impact_in_draft = skill_impact_in_draft + self.created = created + self.updated = updated + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'MonitorAssistantReleaseImportArtifactResponse': + """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" + args = {} + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MonitorAssistantReleaseImportArtifactResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. + """ + + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' + + class SkillImpactInDraftEnum(str, Enum): + """ + The type of the skill in the draft environment. + """ + + ACTION = 'action' + DIALOG = 'dialog' + + +class Pagination: + """ + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). + + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of + results. + :param str next_cursor: (optional) A token identifying the next page of results. + """ + + def __init__( + self, + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, + ) -> None: + """ + Initialize a Pagination object. + + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. + """ + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" + args = {} + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Pagination object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Pagination') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Pagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class PartialItem: + """ + Message response partial item content. + + :param str response_type: (optional) The type of response returned by the dialog + node. The specified response type must be supported by the client application or + channel. + :param str text: The text within the partial chunk of the message stream + response. + :param Metadata streaming_metadata: Contains meta-information about the item(s) + being streamed. + """ + + def __init__( + self, + text: str, + streaming_metadata: 'Metadata', + *, + response_type: Optional[str] = None, + ) -> None: + """ + Initialize a PartialItem object. + + :param str text: The text within the partial chunk of the message stream + response. + :param Metadata streaming_metadata: Contains meta-information about the + item(s) being streamed. + :param str response_type: (optional) The type of response returned by the + dialog node. The specified response type must be supported by the client + application or channel. + """ + self.response_type = response_type + self.text = text + self.streaming_metadata = streaming_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PartialItem': + """Initialize a PartialItem object from a json dictionary.""" + args = {} + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in PartialItem JSON') + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in PartialItem JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PartialItem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this PartialItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PartialItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'PartialItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderAuthenticationOAuth2: + """ + Non-private settings for oauth2 authentication. + + :param str preferred_flow: (optional) The preferred "flow" or "grant type" for + the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios performed + by the API client to fetch an access token from the authorization server. + """ + + def __init__( + self, + *, + preferred_flow: Optional[str] = None, + flows: Optional['ProviderAuthenticationOAuth2Flows'] = None, + ) -> None: + """ + Initialize a ProviderAuthenticationOAuth2 object. + + :param str preferred_flow: (optional) The preferred "flow" or "grant type" + for the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. + """ + self.preferred_flow = preferred_flow + self.flows = flows + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2': + """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" + args = {} + if (preferred_flow := _dict.get('preferred_flow')) is not None: + args['preferred_flow'] = preferred_flow + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'preferred_flow') and self.preferred_flow is not None: + _dict['preferred_flow'] = self.preferred_flow + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows + else: + _dict['flows'] = self.flows.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderAuthenticationOAuth2 object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderAuthenticationOAuth2') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderAuthenticationOAuth2') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class PreferredFlowEnum(str, Enum): + """ + The preferred "flow" or "grant type" for the API client to fetch an access token + from the authorization server. + """ + + PASSWORD = 'password' + CLIENT_CREDENTIALS = 'client_credentials' + AUTHORIZATION_CODE = 'authorization_code' + CUSTOM_FLOW_NAME = '<$custom_flow_name>' + + +class ProviderAuthenticationOAuth2Flows: + """ + Scenarios performed by the API client to fetch an access token from the authorization + server. + + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderAuthenticationOAuth2Flows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderAuthenticationOAuth2PasswordUsername: + """ + The username for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + value: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderAuthenticationOAuth2PasswordUsername object. + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. + """ + self.type = type + self.value = value + + @classmethod + def from_dict( + cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2PasswordUsername': + """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderAuthenticationOAuth2PasswordUsername object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' + + +class ProviderAuthenticationTypeAndValue: + """ + ProviderAuthenticationTypeAndValue. + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + value: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderAuthenticationTypeAndValue object. + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. + """ + self.type = type + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationTypeAndValue': + """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderAuthenticationTypeAndValue object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' + + +class ProviderCollection: + """ + ProviderCollection. + + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + conversational_skill_providers: List['ProviderResponse'], + pagination: 'Pagination', + ) -> None: + """ + Initialize a ProviderCollection object. + + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.conversational_skill_providers = conversational_skill_providers + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderCollection': + """Initialize a ProviderCollection object from a json dictionary.""" + args = {} + if (conversational_skill_providers := + _dict.get('conversational_skill_providers')) is not None: + args['conversational_skill_providers'] = [ + ProviderResponse.from_dict(v) + for v in conversational_skill_providers + ] + else: + raise ValueError( + 'Required property \'conversational_skill_providers\' not present in ProviderCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ProviderCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'conversational_skill_providers' + ) and self.conversational_skill_providers is not None: + conversational_skill_providers_list = [] + for v in self.conversational_skill_providers: + if isinstance(v, dict): + conversational_skill_providers_list.append(v) + else: + conversational_skill_providers_list.append(v.to_dict()) + _dict[ + 'conversational_skill_providers'] = conversational_skill_providers_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderPrivate: + """ + Private information of the provider. + + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. + """ + + def __init__( + self, + authentication: 'ProviderPrivateAuthentication', + ) -> None: + """ + Initialize a ProviderPrivate object. + + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. + """ + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderPrivate': + """Initialize a ProviderPrivate object from a json dictionary.""" + args = {} + if (authentication := _dict.get('authentication')) is not None: + args['authentication'] = authentication + else: + raise ValueError( + 'Required property \'authentication\' not present in ProviderPrivate JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderPrivate object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderPrivate object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderPrivate') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderPrivate') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderPrivateAuthentication: + """ + Private authentication information of the provider. + + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthentication object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationBearerFlow', + 'ProviderPrivateAuthenticationBasicFlow', + 'ProviderPrivateAuthenticationOAuth2Flow' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2FlowFlows: + """ + Scenarios performed by the API client to fetch an access token from the authorization + server. + + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2PasswordPassword: + """ + The password for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + value: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object. + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. + """ + self.type = type + self.value = value + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2PasswordPassword': + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2PasswordPassword object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' + + +class ProviderResponse: + """ + ProviderResponse. + + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The specification + of the provider. + """ + + def __init__( + self, + *, + provider_id: Optional[str] = None, + specification: Optional['ProviderResponseSpecification'] = None, + ) -> None: + """ + Initialize a ProviderResponse object. + + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The + specification of the provider. + """ + self.provider_id = provider_id + self.specification = specification + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponse': + """Initialize a ProviderResponse object from a json dictionary.""" + args = {} + if (provider_id := _dict.get('provider_id')) is not None: + args['provider_id'] = provider_id + if (specification := _dict.get('specification')) is not None: + args['specification'] = ProviderResponseSpecification.from_dict( + specification) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'provider_id') and self.provider_id is not None: + _dict['provider_id'] = self.provider_id + if hasattr(self, 'specification') and self.specification is not None: + if isinstance(self.specification, dict): + _dict['specification'] = self.specification + else: + _dict['specification'] = self.specification.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecification: + """ + The specification of the provider. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) An + array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + + def __init__( + self, + *, + servers: Optional[ + List['ProviderResponseSpecificationServersItem']] = None, + components: Optional['ProviderResponseSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecification object. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) + An array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An + object defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponseSpecification': + """Initialize a ProviderResponseSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderResponseSpecificationServersItem.from_dict(v) + for v in servers + ] + if (components := _dict.get('components')) is not None: + args[ + 'components'] = ProviderResponseSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecification object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderResponseSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecification') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponseSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderResponseSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponents object. + + :param ProviderResponseSpecificationComponentsSecuritySchemes + security_schemes: (optional) The definition of the security scheme for the + provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationComponents': + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes + else: + _dict['securitySchemes'] = self.security_schemes.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderResponseSpecificationComponents object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecificationComponents') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponseSpecificationComponents') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponentsSecuritySchemes: + """ + The definition of the security scheme for the provider. + + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. + """ + + def __init__( + self, + *, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object. + + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. + """ + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemes': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + args = {} + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderResponseSpecificationComponentsSecuritySchemes object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + + +class ProviderResponseSpecificationComponentsSecuritySchemesBasic: + """ + Non-private settings for basic access authentication. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. + """ + + def __init__( + self, + *, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. + """ + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + args = {} + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderResponseSpecificationComponentsSecuritySchemesBasic object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationServersItem: + """ + ProviderResponseSpecificationServersItem. + + :param str url: (optional) The URL of the conversational skill provider. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationServersItem object. + + :param str url: (optional) The URL of the conversational skill provider. + """ + self.url = url + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationServersItem': + """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderResponseSpecificationServersItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecificationServersItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponseSpecificationServersItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecification: + """ + The specification of the provider. + + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object defining + various reusable definitions of the provider. + """ + + def __init__( + self, + servers: List['ProviderSpecificationServersItem'], + *, + components: Optional['ProviderSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderSpecification object. + + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecification': + """Initialize a ProviderSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderSpecificationServersItem.from_dict(v) for v in servers + ] + else: + raise ValueError( + 'Required property \'servers\' not present in ProviderSpecification JSON' + ) + if (components := _dict.get('components')) is not None: + args['components'] = ProviderSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecification object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecification') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponents object. + + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationComponents': + """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes + else: + _dict['securitySchemes'] = self.security_schemes.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderSpecificationComponents object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecificationComponents') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderSpecificationComponents') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationComponentsSecuritySchemes: + """ + The definition of the security scheme for the provider. + + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: (optional) + Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. + """ + + def __init__( + self, + *, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponentsSecuritySchemes object. + + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. + """ + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'ProviderSpecificationComponentsSecuritySchemes': + """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + args = {} + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderSpecificationComponentsSecuritySchemes object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + + +class ProviderSpecificationComponentsSecuritySchemesBasic: + """ + Non-private settings for basic access authentication. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. + """ + + def __init__( + self, + *, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. + """ + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + args = {} + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderSpecificationComponentsSecuritySchemesBasic object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationServersItem: + """ + ProviderSpecificationServersItem. + + :param str url: (optional) The URL of the conversational skill provider. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderSpecificationServersItem object. + + :param str url: (optional) The URL of the conversational skill provider. + """ + self.url = url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationServersItem': + """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderSpecificationServersItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecificationServersItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderSpecificationServersItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Release: + """ + Release. + + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :param ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :param str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__( + self, + *, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: + """ + Initialize a Release object. + + :param str description: (optional) The description of the release. + """ + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" + args = {} + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in environment_references + ] + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Release object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Release') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class ReleaseCollection: + """ + ReleaseCollection. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + releases: List['Release'], + pagination: 'Pagination', + ) -> None: + """ + Initialize a ReleaseCollection object. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.releases = releases + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" + args = {} + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseContent: + """ + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. + + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. + """ + + def __init__( + self, + *, + skills: Optional[List['ReleaseSkill']] = None, + ) -> None: + """ + Initialize a ReleaseContent object. + + """ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" + args = {} + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseContent object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseContent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseContent') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseContent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseSkill: + """ + ReleaseSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + snapshot: Optional[str] = None, + ) -> None: + """ + Initialize a ReleaseSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). + """ + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" + args = {} + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in ReleaseSkill JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics: + """ + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. + + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. + """ + + def __init__( + self, + *, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, + ) -> None: + """ + Initialize a RequestAnalytics object. + + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. + """ + self.browser = browser + self.device = device + self.page_url = page_url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" + args = {} + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RequestAnalytics object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RequestAnalytics object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RequestAnalytics') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RequestAnalytics') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericChannel: + """ + ResponseGenericChannel. + + :param str channel: (optional) A channel for which the response is intended. + """ + + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericCitation: + """ + ResponseGenericCitation. + + :param str title: The title of the citation text. + :param str text: The text of the citation. + :param str body: The body content of the citation. + :param int search_result_index: (optional) The index of the search_result where + the citation is generated. + :param List[ResponseGenericCitationRangesItem] ranges: The offsets of the start + and end of the citation in the generated response. For example, `ranges:[ { + start:0, end:5 }, ...]`. + """ + + def __init__( + self, + title: str, + text: str, + body: str, + ranges: List['ResponseGenericCitationRangesItem'], + *, + search_result_index: Optional[int] = None, + ) -> None: + """ + Initialize a ResponseGenericCitation object. + + :param str title: The title of the citation text. + :param str text: The text of the citation. + :param str body: The body content of the citation. + :param List[ResponseGenericCitationRangesItem] ranges: The offsets of the + start and end of the citation in the generated response. For example, + `ranges:[ { start:0, end:5 }, ...]`. + :param int search_result_index: (optional) The index of the search_result + where the citation is generated. + """ + self.title = title + self.text = text + self.body = body + self.search_result_index = search_result_index + self.ranges = ranges + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericCitation': + """Initialize a ResponseGenericCitation object from a json dictionary.""" + args = {} + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in ResponseGenericCitation JSON' + ) + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in ResponseGenericCitation JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in ResponseGenericCitation JSON' + ) + if (search_result_index := + _dict.get('search_result_index')) is not None: + args['search_result_index'] = search_result_index + if (ranges := _dict.get('ranges')) is not None: + args['ranges'] = [ + ResponseGenericCitationRangesItem.from_dict(v) for v in ranges + ] + else: + raise ValueError( + 'Required property \'ranges\' not present in ResponseGenericCitation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericCitation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr( + self, + 'search_result_index') and self.search_result_index is not None: + _dict['search_result_index'] = self.search_result_index + if hasattr(self, 'ranges') and self.ranges is not None: + ranges_list = [] + for v in self.ranges: + if isinstance(v, dict): + ranges_list.append(v) + else: + ranges_list.append(v.to_dict()) + _dict['ranges'] = ranges_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ResponseGenericCitation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericCitation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ResponseGenericCitation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericCitationRangesItem: + """ + ResponseGenericCitationRangesItem. + + :param int start: (optional) The offset of the start of the citation in the + generated response. + :param int end: (optional) The offset of the end of the citation in the + generated response. + """ + + def __init__( + self, + *, + start: Optional[int] = None, + end: Optional[int] = None, + ) -> None: + """ + Initialize a ResponseGenericCitationRangesItem object. + + :param int start: (optional) The offset of the start of the citation in the + generated response. + :param int end: (optional) The offset of the end of the citation in the + generated response. + """ + self.start = start + self.end = end + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericCitationRangesItem': + """Initialize a ResponseGenericCitationRangesItem object from a json dictionary.""" + args = {} + if (start := _dict.get('start')) is not None: + args['start'] = start + if (end := _dict.get('end')) is not None: + args['end'] = end + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericCitationRangesItem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'start') and self.start is not None: + _dict['start'] = self.start + if hasattr(self, 'end') and self.end is not None: + _dict['end'] = self.end + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ResponseGenericCitationRangesItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericCitationRangesItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ResponseGenericCitationRangesItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericConfidenceScores: + """ + The confidence scores for determining whether to show the generated response or an “I + don't know” response. + + :param float threshold: (optional) The confidence score threshold. If either the + pre_gen or post_gen score is below this threshold, it shows an “I don't know” + response to replace the generated text. You can configure the threshold in + either the user interface or through the Update skill API. For more information, + see the [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#behavioral-tuning-conversational-search). + :param float pre_gen: (optional) The confidence score based on user query and + search results. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float extractiveness: (optional) It indicates how extractive the + generated response is from the search results. + """ + + def __init__( + self, + *, + threshold: Optional[float] = None, + pre_gen: Optional[float] = None, + post_gen: Optional[float] = None, + extractiveness: Optional[float] = None, + ) -> None: + """ + Initialize a ResponseGenericConfidenceScores object. + + :param float threshold: (optional) The confidence score threshold. If + either the pre_gen or post_gen score is below this threshold, it shows an + “I don't know” response to replace the generated text. You can configure + the threshold in either the user interface or through the Update skill API. + For more information, see the [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#behavioral-tuning-conversational-search). + :param float pre_gen: (optional) The confidence score based on user query + and search results. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float extractiveness: (optional) It indicates how extractive the + generated response is from the search results. + """ + self.threshold = threshold + self.pre_gen = pre_gen + self.post_gen = post_gen + self.extractiveness = extractiveness + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericConfidenceScores': + """Initialize a ResponseGenericConfidenceScores object from a json dictionary.""" + args = {} + if (threshold := _dict.get('threshold')) is not None: + args['threshold'] = threshold + if (pre_gen := _dict.get('pre_gen')) is not None: + args['pre_gen'] = pre_gen + if (post_gen := _dict.get('post_gen')) is not None: + args['post_gen'] = post_gen + if (extractiveness := _dict.get('extractiveness')) is not None: + args['extractiveness'] = extractiveness + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericConfidenceScores object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'threshold') and self.threshold is not None: + _dict['threshold'] = self.threshold + if hasattr(self, 'pre_gen') and self.pre_gen is not None: + _dict['pre_gen'] = self.pre_gen + if hasattr(self, 'post_gen') and self.post_gen is not None: + _dict['post_gen'] = self.post_gen + if hasattr(self, 'extractiveness') and self.extractiveness is not None: + _dict['extractiveness'] = self.extractiveness + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ResponseGenericConfidenceScores object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericConfidenceScores') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ResponseGenericConfidenceScores') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity: + """ + The entity value that was recognized in the user input. + + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :param str value: The term in the input text that was recognized as an entity + value. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + :param List[CaptureGroup] groups: (optional) The recognized capture groups for + the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user input. + This property is included only if the new system entities are enabled for the + skill. + For more information about how the new system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of the + value returned in the **value** property. This property is returned only for + `@sys-time` and `@sys-date` entities when the user's input is ambiguous. + This property is included only if the new system entities are enabled for the + skill. + :param RuntimeEntityRole role: (optional) An object describing the role played + by a system entity that is specifies the beginning or end of a range recognized + in the user input. This property is included only if the new system entities are + enabled for the skill. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + :param List[CaptureGroup] groups: (optional) The recognized capture groups + for the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user + input. This property is included only if the new system entities are + enabled for the skill. + For more information about how the new system entities are interpreted, see + the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of + the value returned in the **value** property. This property is returned + only for `@sys-time` and `@sys-date` entities when the user's input is + ambiguous. + This property is included only if the new system entities are enabled for + the skill. + :param RuntimeEntityRole role: (optional) An object describing the role + played by a system entity that is specifies the beginning or end of a range + recognized in the user input. This property is included only if the new + system entities are enabled for the skill. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: + args['interpretation'] = RuntimeEntityInterpretation.from_dict( + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: + args['alternatives'] = [ + RuntimeEntityAlternative.from_dict(v) for v in alternatives + ] + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntity') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityAlternative: + """ + An alternative value for the recognized entity. + + :param str value: (optional) The entity value that was recognized in the user + input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + """ + + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: + """ + Initialize a RuntimeEntityAlternative object. + + :param str value: (optional) The entity value that was recognized in the + user input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + """ + self.value = value + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + args = {} + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityAlternative object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityInterpretation: + """ + RuntimeEntityInterpretation. + + :param str calendar_type: (optional) The calendar used to represent a recognized + date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate a + recognized time and date. If the user input contains a date and time that are + mentioned together (for example, `Today at 5`, the same **datetime_link** value + is returned for both the `@sys-date` and `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a `@sys-date` + entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time range + specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate multiple + recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are + recognized as a range of values in the user's input (for example, `from July 4 + until July 14` or `from 20 to 25`). + :param str range_modifier: (optional) The word in the user input that indicates + that a `sys-date` or `sys-time` entity is part of an implied range where only + one date or time is specified (for example, `since` or `until`). + :param float relative_day: (optional) A recognized mention of a relative day, + represented numerically as an offset from the current date (for example, `-1` + for `yesterday` or `10` for `in ten days`). + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for example, + `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative week, + represented numerically as an offset from the current week (for example, `2` for + `in two weeks` or `-1` for `last week). + :param float relative_weekend: (optional) A recognized mention of a relative + date range for a weekend, represented numerically as an offset from the current + weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). + :param float relative_year: (optional) A recognized mention of a relative year, + represented numerically as an offset from the current year (for example, `1` for + `next year` or `-5` for `five years ago`). + :param float specific_day: (optional) A recognized mention of a specific date, + represented numerically as the date within the month (for example, `30` for + `June 30`.). + :param str specific_day_of_week: (optional) A recognized mention of a specific + day of the week as a lowercase string (for example, `monday`). + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a specific + quarter, represented numerically (for example, `3` for `the third quarter`). + :param float specific_year: (optional) A recognized mention of a specific year + (for example, `2016`). + :param float numeric_value: (optional) A recognized numeric value, represented + as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the user + input (`integer` or `rational`). + :param str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` or + `afternoon`). + :param float relative_hour: (optional) A recognized mention of a relative hour, + represented numerically as an offset from the current hour (for example, `3` for + `in three hours` or `-1` for `an hour ago`). + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time (for + example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time (for + example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :param float specific_hour: (optional) A recognized specific hour mentioned as + part of a time value (for example, `10` for `10:15 AM`.). + :param float specific_minute: (optional) A recognized specific minute mentioned + as part of a time value (for example, `15` for `10:15 AM`.). + :param float specific_second: (optional) A recognized specific second mentioned + as part of a time value (for example, `30` for `10:15:30 AM`.). + :param str timezone: (optional) A recognized time zone mentioned as part of a + time value (for example, `EST`). + """ + + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntityInterpretation object. + + :param str calendar_type: (optional) The calendar used to represent a + recognized date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate + a recognized time and date. If the user input contains a date and time that + are mentioned together (for example, `Today at 5`, the same + **datetime_link** value is returned for both the `@sys-date` and + `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a + `@sys-date` entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time + range specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate + multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities + that are recognized as a range of values in the user's input (for example, + `from July 4 until July 14` or `from 20 to 25`). + :param str range_modifier: (optional) The word in the user input that + indicates that a `sys-date` or `sys-time` entity is part of an implied + range where only one date or time is specified (for example, `since` or + `until`). + :param float relative_day: (optional) A recognized mention of a relative + day, represented numerically as an offset from the current date (for + example, `-1` for `yesterday` or `10` for `in ten days`). + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for + example, `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative + week, represented numerically as an offset from the current week (for + example, `2` for `in two weeks` or `-1` for `last week). + :param float relative_weekend: (optional) A recognized mention of a + relative date range for a weekend, represented numerically as an offset + from the current weekend (for example, `0` for `this weekend` or `-1` for + `last weekend`). + :param float relative_year: (optional) A recognized mention of a relative + year, represented numerically as an offset from the current year (for + example, `1` for `next year` or `-5` for `five years ago`). + :param float specific_day: (optional) A recognized mention of a specific + date, represented numerically as the date within the month (for example, + `30` for `June 30`.). + :param str specific_day_of_week: (optional) A recognized mention of a + specific day of the week as a lowercase string (for example, `monday`). + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a + specific quarter, represented numerically (for example, `3` for `the third + quarter`). + :param float specific_year: (optional) A recognized mention of a specific + year (for example, `2016`). + :param float numeric_value: (optional) A recognized numeric value, + represented as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the + user input (`integer` or `rational`). + :param str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` + or `afternoon`). + :param float relative_hour: (optional) A recognized mention of a relative + hour, represented numerically as an offset from the current hour (for + example, `3` for `in three hours` or `-1` for `an hour ago`). + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time + (for example, `5` for `in five minutes` or `-15` for `fifteen minutes + ago`). + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time + (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :param float specific_hour: (optional) A recognized specific hour mentioned + as part of a time value (for example, `10` for `10:15 AM`.). + :param float specific_minute: (optional) A recognized specific minute + mentioned as part of a time value (for example, `15` for `10:15 AM`.). + :param float specific_second: (optional) A recognized specific second + mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). + :param str timezone: (optional) A recognized time zone mentioned as part of + a time value (for example, `EST`). + """ + self.calendar_type = calendar_type + self.datetime_link = datetime_link + self.festival = festival + self.granularity = granularity + self.range_link = range_link + self.range_modifier = range_modifier + self.relative_day = relative_day + self.relative_month = relative_month + self.relative_week = relative_week + self.relative_weekend = relative_weekend + self.relative_year = relative_year + self.specific_day = specific_day + self.specific_day_of_week = specific_day_of_week + self.specific_month = specific_month + self.specific_quarter = specific_quarter + self.specific_year = specific_year + self.numeric_value = numeric_value + self.subtype = subtype + self.part_of_day = part_of_day + self.relative_hour = relative_hour + self.relative_minute = relative_minute + self.relative_second = relative_second + self.specific_hour = specific_hour + self.specific_minute = specific_minute + self.specific_second = specific_second + self.timezone = timezone + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + args = {} + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'calendar_type') and self.calendar_type is not None: + _dict['calendar_type'] = self.calendar_type + if hasattr(self, 'datetime_link') and self.datetime_link is not None: + _dict['datetime_link'] = self.datetime_link + if hasattr(self, 'festival') and self.festival is not None: + _dict['festival'] = self.festival + if hasattr(self, 'granularity') and self.granularity is not None: + _dict['granularity'] = self.granularity + if hasattr(self, 'range_link') and self.range_link is not None: + _dict['range_link'] = self.range_link + if hasattr(self, 'range_modifier') and self.range_modifier is not None: + _dict['range_modifier'] = self.range_modifier + if hasattr(self, 'relative_day') and self.relative_day is not None: + _dict['relative_day'] = self.relative_day + if hasattr(self, 'relative_month') and self.relative_month is not None: + _dict['relative_month'] = self.relative_month + if hasattr(self, 'relative_week') and self.relative_week is not None: + _dict['relative_week'] = self.relative_week + if hasattr(self, + 'relative_weekend') and self.relative_weekend is not None: + _dict['relative_weekend'] = self.relative_weekend + if hasattr(self, 'relative_year') and self.relative_year is not None: + _dict['relative_year'] = self.relative_year + if hasattr(self, 'specific_day') and self.specific_day is not None: + _dict['specific_day'] = self.specific_day + if hasattr(self, 'specific_day_of_week' + ) and self.specific_day_of_week is not None: + _dict['specific_day_of_week'] = self.specific_day_of_week + if hasattr(self, 'specific_month') and self.specific_month is not None: + _dict['specific_month'] = self.specific_month + if hasattr(self, + 'specific_quarter') and self.specific_quarter is not None: + _dict['specific_quarter'] = self.specific_quarter + if hasattr(self, 'specific_year') and self.specific_year is not None: + _dict['specific_year'] = self.specific_year + if hasattr(self, 'numeric_value') and self.numeric_value is not None: + _dict['numeric_value'] = self.numeric_value + if hasattr(self, 'subtype') and self.subtype is not None: + _dict['subtype'] = self.subtype + if hasattr(self, 'part_of_day') and self.part_of_day is not None: + _dict['part_of_day'] = self.part_of_day + if hasattr(self, 'relative_hour') and self.relative_hour is not None: + _dict['relative_hour'] = self.relative_hour + if hasattr(self, + 'relative_minute') and self.relative_minute is not None: + _dict['relative_minute'] = self.relative_minute + if hasattr(self, + 'relative_second') and self.relative_second is not None: + _dict['relative_second'] = self.relative_second + if hasattr(self, 'specific_hour') and self.specific_hour is not None: + _dict['specific_hour'] = self.specific_hour + if hasattr(self, + 'specific_minute') and self.specific_minute is not None: + _dict['specific_minute'] = self.specific_minute + if hasattr(self, + 'specific_second') and self.specific_second is not None: + _dict['specific_second'] = self.specific_second + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityInterpretation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class GranularityEnum(str, Enum): + """ + The precision or duration of a time range specified by a recognized `@sys-time` or + `@sys-date` entity. + """ + + DAY = 'day' + FORTNIGHT = 'fortnight' + HOUR = 'hour' + INSTANT = 'instant' + MINUTE = 'minute' + MONTH = 'month' + QUARTER = 'quarter' + SECOND = 'second' + WEEK = 'week' + WEEKEND = 'weekend' + YEAR = 'year' + + +class RuntimeEntityRole: + """ + An object describing the role played by a system entity that is specifies the + beginning or end of a range recognized in the user input. This property is included + only if the new system entities are enabled for the skill. + + :param str type: (optional) The relationship of the entity to the range. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntityRole object. + + :param str type: (optional) The relationship of the entity to the range. + """ + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': + """Initialize a RuntimeEntityRole object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityRole object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityRole object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The relationship of the entity to the range. + """ + + DATE_FROM = 'date_from' + DATE_TO = 'date_to' + NUMBER_FROM = 'number_from' + NUMBER_TO = 'number_to' + TIME_FROM = 'time_from' + TIME_TO = 'time_to' + + +class RuntimeIntent: + """ + An intent identified in the user input. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric: + """ + RuntimeResponseGeneric. + + """ + + def __init__(self,) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch', + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate', + 'RuntimeResponseGenericRuntimeResponseTypeDtmf', + 'RuntimeResponseGenericRuntimeResponseTypeEndSession' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch', + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate', + 'RuntimeResponseGenericRuntimeResponseTypeDtmf', + 'RuntimeResponseGenericRuntimeResponseTypeEndSession' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'conversation_search'] = 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch' + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + mapping['dtmf'] = 'RuntimeResponseGenericRuntimeResponseTypeDtmf' + mapping[ + 'end_session'] = 'RuntimeResponseGenericRuntimeResponseTypeEndSession' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult: + """ + SearchResult. + + :param str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the + search skill configuration. + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if (id := _dict.get('id')) is not None: + args['id'] = id + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer: + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__( + self, + text: str, + confidence: float, + ) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultHighlight: + """ + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. + + :param List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. + + This type supports additional properties of type List[str]. An array of strings + containing segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings highlighted. The + property name is the name of the field in the Discovery collection. + """ + + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__( + self, + *, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs: Optional[List[str]], + ) -> None: + """ + Initialize a SearchResultHighlight object. + + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param List[str] **kwargs: (optional) An array of strings containing + segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings + highlighted. The property name is the name of the field in the Discovery + collection. + """ + self.body = body + self.title = title + self.url = url + for k, v in kwargs.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[Foo]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + args[k] = _v + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return the additional properties from this instance of SearchResultHighlight in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of SearchResultHighlight""" + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata: + """ + An object containing search result metadata from the Discovery service. + + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResults: + """ + SearchResults. + + :param SearchResultsResultMetadata result_metadata: The metadata of the search + result. + :param str id: The ID of the search result. It may not be unique. + :param str title: The title of the search result. + :param str body: The body content of the search result. + """ + + def __init__( + self, + result_metadata: 'SearchResultsResultMetadata', + id: str, + title: str, + body: str, + ) -> None: + """ + Initialize a SearchResults object. + + :param SearchResultsResultMetadata result_metadata: The metadata of the + search result. + :param str id: The ID of the search result. It may not be unique. + :param str title: The title of the search result. + :param str body: The body content of the search result. + """ + self.result_metadata = result_metadata + self.id = id + self.title = title + self.body = body + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResults': + """Initialize a SearchResults object from a json dictionary.""" + args = {} + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultsResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResults JSON' + ) + if (id := _dict.get('id')) is not None: + args['id'] = id + else: + raise ValueError( + 'Required property \'id\' not present in SearchResults JSON') + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in SearchResults JSON') + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchResults JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResults object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResults') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultsResultMetadata: + """ + The metadata of the search result. + + :param str document_retrieval_source: (optional) The source of the search + result. + :param int score: (optional) The relevance score of the search result to the + user query. + """ + + def __init__( + self, + *, + document_retrieval_source: Optional[str] = None, + score: Optional[int] = None, + ) -> None: + """ + Initialize a SearchResultsResultMetadata object. + + :param str document_retrieval_source: (optional) The source of the search + result. + :param int score: (optional) The relevance score of the search result to + the user query. + """ + self.document_retrieval_source = document_retrieval_source + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultsResultMetadata': + """Initialize a SearchResultsResultMetadata object from a json dictionary.""" + args = {} + if (document_retrieval_source := + _dict.get('document_retrieval_source')) is not None: + args['document_retrieval_source'] = document_retrieval_source + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultsResultMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_retrieval_source' + ) and self.document_retrieval_source is not None: + _dict['document_retrieval_source'] = self.document_retrieval_source + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResultsResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultsResultMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultsResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettings: + """ + An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. + + :param SearchSettingsDiscovery discovery: (optional) Configuration settings for + the Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You can + provide either basic auth or apiKey auth. + :param SearchSettingsConversationalSearch conversational_search: Configuration + settings for conversational search. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side search + service used by the search integration. + """ + + def __init__( + self, + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + conversational_search: 'SearchSettingsConversationalSearch', + *, + discovery: Optional['SearchSettingsDiscovery'] = None, + elastic_search: Optional['SearchSettingsElasticSearch'] = None, + server_side_search: Optional['SearchSettingsServerSideSearch'] = None, + client_side_search: Optional['SearchSettingsClientSideSearch'] = None, + ) -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + :param SearchSettingsConversationalSearch conversational_search: + Configuration settings for conversational search. + :param SearchSettingsDiscovery discovery: (optional) Configuration settings + for the Watson Discovery service instance used by the search integration. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You + can provide either basic auth or apiKey auth. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the + search integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side + search service used by the search integration. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + self.elastic_search = elastic_search + self.conversational_search = conversational_search + self.server_side_search = server_side_search + self.client_side_search = client_side_search + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if (schema_mapping := _dict.get('schema_mapping')) is not None: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + schema_mapping) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + if (elastic_search := _dict.get('elastic_search')) is not None: + args['elastic_search'] = SearchSettingsElasticSearch.from_dict( + elastic_search) + if (conversational_search := + _dict.get('conversational_search')) is not None: + args[ + 'conversational_search'] = SearchSettingsConversationalSearch.from_dict( + conversational_search) + else: + raise ValueError( + 'Required property \'conversational_search\' not present in SearchSettings JSON' + ) + if (server_side_search := _dict.get('server_side_search')) is not None: + args[ + 'server_side_search'] = SearchSettingsServerSideSearch.from_dict( + server_side_search) + if (client_side_search := _dict.get('client_side_search')) is not None: + args[ + 'client_side_search'] = SearchSettingsClientSideSearch.from_dict( + client_side_search) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + if hasattr(self, 'elastic_search') and self.elastic_search is not None: + if isinstance(self.elastic_search, dict): + _dict['elastic_search'] = self.elastic_search + else: + _dict['elastic_search'] = self.elastic_search.to_dict() + if hasattr(self, 'conversational_search' + ) and self.conversational_search is not None: + if isinstance(self.conversational_search, dict): + _dict['conversational_search'] = self.conversational_search + else: + _dict[ + 'conversational_search'] = self.conversational_search.to_dict( + ) + if hasattr( + self, + 'server_side_search') and self.server_side_search is not None: + if isinstance(self.server_side_search, dict): + _dict['server_side_search'] = self.server_side_search + else: + _dict['server_side_search'] = self.server_side_search.to_dict() + if hasattr( + self, + 'client_side_search') and self.client_side_search is not None: + if isinstance(self.client_side_search, dict): + _dict['client_side_search'] = self.client_side_search + else: + _dict['client_side_search'] = self.client_side_search.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsClientSideSearch: + """ + Configuration settings for the client-side search service or server-side search + service used by the search integration. + + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + """ + + def __init__( + self, + *, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + ) -> None: + """ + Initialize a SearchSettingsClientSideSearch object. + + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + """ + self.filter = filter + self.metadata = metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsClientSideSearch': + """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + args = {} + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsClientSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsClientSideSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsClientSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearch: + """ + Configuration settings for conversational search. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence search_confidence: + (optional) + """ + + def __init__( + self, + enabled: bool, + *, + response_length: Optional[ + 'SearchSettingsConversationalSearchResponseLength'] = None, + search_confidence: Optional[ + 'SearchSettingsConversationalSearchSearchConfidence'] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearch object. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence + search_confidence: (optional) + """ + self.enabled = enabled + self.response_length = response_length + self.search_confidence = search_confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsConversationalSearch': + """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + args = {} + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + else: + raise ValueError( + 'Required property \'enabled\' not present in SearchSettingsConversationalSearch JSON' + ) + if (response_length := _dict.get('response_length')) is not None: + args[ + 'response_length'] = SearchSettingsConversationalSearchResponseLength.from_dict( + response_length) + if (search_confidence := _dict.get('search_confidence')) is not None: + args[ + 'search_confidence'] = SearchSettingsConversationalSearchSearchConfidence.from_dict( + search_confidence) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, + 'response_length') and self.response_length is not None: + if isinstance(self.response_length, dict): + _dict['response_length'] = self.response_length + else: + _dict['response_length'] = self.response_length.to_dict() + if hasattr(self, + 'search_confidence') and self.search_confidence is not None: + if isinstance(self.search_confidence, dict): + _dict['search_confidence'] = self.search_confidence + else: + _dict['search_confidence'] = self.search_confidence.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsConversationalSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsConversationalSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsConversationalSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearchResponseLength: + """ + SearchSettingsConversationalSearchResponseLength. + + :param str option: (optional) The response length option. It controls the length + of the generated response. + """ + + def __init__( + self, + *, + option: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchResponseLength object. + + :param str option: (optional) The response length option. It controls the + length of the generated response. + """ + self.option = option + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'SearchSettingsConversationalSearchResponseLength': + """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + args = {} + if (option := _dict.get('option')) is not None: + args['option'] = option + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'option') and self.option is not None: + _dict['option'] = self.option + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsConversationalSearchResponseLength object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'SearchSettingsConversationalSearchResponseLength') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, + other: 'SearchSettingsConversationalSearchResponseLength') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OptionEnum(str, Enum): + """ + The response length option. It controls the length of the generated response. + """ + + CONCISE = 'concise' + MODERATE = 'moderate' + VERBOSE = 'verbose' + + +class SearchSettingsConversationalSearchSearchConfidence: + """ + SearchSettingsConversationalSearchSearchConfidence. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + def __init__( + self, + *, + threshold: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchSearchConfidence object. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't + know” answers. + """ + self.threshold = threshold + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'SearchSettingsConversationalSearchSearchConfidence': + """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + args = {} + if (threshold := _dict.get('threshold')) is not None: + args['threshold'] = threshold + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'threshold') and self.threshold is not None: + _dict['threshold'] = self.threshold + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsConversationalSearchSearchConfidence object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ThresholdEnum(str, Enum): + """ + The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + RARELY = 'rarely' + LESS_OFTEN = 'less_often' + MORE_OFTEN = 'more_often' + MOST_OFTEN = 'most_often' + + +class SearchSettingsDiscovery: + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :param int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :param bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + args = {} + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + authentication) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results + if hasattr(self, + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsDiscovery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscoveryAuthentication: + """ + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + + def __init__( + self, + *, + basic: Optional[str] = None, + bearer: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscoveryAuthentication object. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + self.basic = basic + self.bearer = bearer + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + args = {} + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsElasticSearch: + """ + Configuration settings for the Elasticsearch service used by the search integration. + You can provide either basic auth or apiKey auth. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str index: The Elasticsearch index to use for the search integration. + :param List[object] filter: (optional) An array of filters that can be applied + to the search results via the `$FILTER` variable in the `query_body`.For more + information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication method. + Use either basic auth or apiKey auth. The credentials are not returned due to + security reasons. + """ + + def __init__( + self, + url: str, + port: str, + index: str, + *, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[List[object]] = None, + query_body: Optional[dict] = None, + managed_index: Optional[str] = None, + apikey: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsElasticSearch object. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str index: The Elasticsearch index to use for the search + integration. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param List[object] filter: (optional) An array of filters that can be + applied to the search results via the `$FILTER` variable in the + `query_body`.For more information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication + method. Use either basic auth or apiKey auth. The credentials are not + returned due to security reasons. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.index = index + self.filter = filter + self.query_body = query_body + self.managed_index = managed_index + self.apikey = apikey + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsElasticSearch': + """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsElasticSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + else: + raise ValueError( + 'Required property \'port\' not present in SearchSettingsElasticSearch JSON' + ) + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (index := _dict.get('index')) is not None: + args['index'] = index + else: + raise ValueError( + 'Required property \'index\' not present in SearchSettingsElasticSearch JSON' + ) + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (query_body := _dict.get('query_body')) is not None: + args['query_body'] = query_body + if (managed_index := _dict.get('managed_index')) is not None: + args['managed_index'] = managed_index + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'index') and self.index is not None: + _dict['index'] = self.index + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'query_body') and self.query_body is not None: + _dict['query_body'] = self.query_body + if hasattr(self, 'managed_index') and self.managed_index is not None: + _dict['managed_index'] = self.managed_index + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsElasticSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsElasticSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsElasticSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsMessages: + """ + The messages included with responses from the search integration. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is no + result from the query. + """ + + def __init__( + self, + success: str, + error: str, + no_result: str, + ) -> None: + """ + Initialize a SearchSettingsMessages object. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. + """ + self.success = success + self.error = error + self.no_result = no_result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" + args = {} + if (success := _dict.get('success')) is not None: + args['success'] = success + else: + raise ValueError( + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if (error := _dict.get('error')) is not None: + args['error'] = error + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsMessages object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsMessages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping: + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :param str url: The field in the collection to map to the **url** property of + the response. + :param str body: The field in the collection to map to the **body** property in + the response. + :param str title: The field in the collection to map to the **title** property + for the schema. + """ + + def __init__( + self, + url: str, + body: str, + title: str, + ) -> None: + """ + Initialize a SearchSettingsSchemaMapping object. + + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. + """ + self.url = url + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsSchemaMapping object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsServerSideSearch: + """ + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search service. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication method. + The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + + def __init__( + self, + url: str, + *, + port: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + apikey: Optional[str] = None, + no_auth: Optional[bool] = None, + auth_type: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsServerSideSearch object. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search + service. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication + method. The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.filter = filter + self.metadata = metadata + self.apikey = apikey + self.no_auth = no_auth + self.auth_type = auth_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsServerSideSearch': + """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsServerSideSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + if (no_auth := _dict.get('no_auth')) is not None: + args['no_auth'] = no_auth + if (auth_type := _dict.get('auth_type')) is not None: + args['auth_type'] = auth_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + if hasattr(self, 'no_auth') and self.no_auth is not None: + _dict['no_auth'] = self.no_auth + if hasattr(self, 'auth_type') and self.auth_type is not None: + _dict['auth_type'] = self.auth_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsServerSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsServerSideSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsServerSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthTypeEnum(str, Enum): + """ + The authorization type that is used. + """ + + BASIC = 'basic' + APIKEY = 'apikey' + NONE = 'none' + + +class SearchSkillWarning: + """ + A warning describing an error in the search skill configuration. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + + def __init__( + self, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSkillWarning object. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + self.code = code + self.path = path + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" + args = {} + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSkillWarning object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSkillWarning object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse: + """ + SessionResponse. + + :param str session_id: The session ID. + """ + + def __init__( + self, + session_id: str, + ) -> None: + """ + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SessionResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SessionResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SessionResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Skill: + """ + Skill. + + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: + """ + Initialize a Skill object. + + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Skill JSON') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in Skill JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Skill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Skill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Skill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Skill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' + + +class SkillImport: + """ + SkillImport. + + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: + """ + Initialize a SkillImport object. + + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in SkillImport JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in SkillImport JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillImport object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillImport object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillImport') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillImport') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + + +class SkillsAsyncRequestStatus: + """ + SkillsAsyncRequestStatus. + + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + """ + + def __init__( + self, + *, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + ) -> None: + """ + Initialize a SkillsAsyncRequestStatus object. + + """ + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + args = {} + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillsAsyncRequestStatus object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + """ + + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class SkillsExport: + """ + SkillsExport. + + :param List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. + """ + + def __init__( + self, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', + ) -> None: + """ + Initialize a SkillsExport object. + + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + """ + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" + args = {} + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in assistant_skills + ] + else: + raise ValueError( + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) + else: + raise ValueError( + 'Required property \'assistant_state\' not present in SkillsExport JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillsExport object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillsExport object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillsExport') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillsExport') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatefulMessageResponse: + """ + A response from the watsonx Assistant service. + + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + """ + + def __init__( + self, + output: 'MessageOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + ) -> None: + """ + Initialize a StatefulMessageResponse object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + """ + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': + """Initialize a StatefulMessageResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in StatefulMessageResponse JSON' + ) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + else: + raise ValueError( + 'Required property \'user_id\' not present in StatefulMessageResponse JSON' + ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatefulMessageResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatefulMessageResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatefulMessageResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatefulMessageResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessFinalResponse: + """ + Message final response content. + + :param StatelessFinalResponseOutput output: (optional) Assistant output to be + rendered or processed by the client. + :param StatelessMessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The context + is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ + + def __init__( + self, + *, + output: Optional['StatelessFinalResponseOutput'] = None, + context: Optional['StatelessMessageContext'] = None, + user_id: Optional[str] = None, + ) -> None: + """ + Initialize a StatelessFinalResponse object. + + :param StatelessFinalResponseOutput output: (optional) Assistant output to + be rendered or processed by the client. + :param StatelessMessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + """ + self.output = output + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessFinalResponse': + """Initialize a StatelessFinalResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = StatelessFinalResponseOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessFinalResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessFinalResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessFinalResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessFinalResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessFinalResponseOutput: + """ + Assistant output to be rendered or processed by the client. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + :param StatelessMessageContext streaming_metadata: + """ + + def __init__( + self, + streaming_metadata: 'StatelessMessageContext', + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, + ) -> None: + """ + Initialize a StatelessFinalResponseOutput object. + + :param StatelessMessageContext streaming_metadata: + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata + self.streaming_metadata = streaming_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessFinalResponseOutput': + """Initialize a StatelessFinalResponseOutput object from a json dictionary.""" + args = {} + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = StatelessMessageContext.from_dict( + streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in StatelessFinalResponseOutput JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessFinalResponseOutput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessFinalResponseOutput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessFinalResponseOutput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessFinalResponseOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContext: + """ + StatelessMessageContext. + + :param StatelessMessageContextGlobal global_: (optional) Session context data + that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + + def __init__( + self, + *, + global_: Optional['StatelessMessageContextGlobal'] = None, + skills: Optional['StatelessMessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: + """ + Initialize a StatelessMessageContext object. + + :param StatelessMessageContextGlobal global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data + specific to particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + self.global_ = global_ + self.skills = skills + self.integrations = integrations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': + """Initialize a StatelessMessageContext object from a json dictionary.""" + args = {} + if (global_ := _dict.get('global')) is not None: + args['global_'] = StatelessMessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = StatelessMessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContext object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContext object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageContext') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageContext') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContextGlobal: + """ + Session context data that is shared by all skills used by the assistant. + + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. + """ + + def __init__( + self, + *, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, + ) -> None: + """ + Initialize a StatelessMessageContextGlobal object. + + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. + """ + self.system = system + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + args = {} + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContextGlobal object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageContextGlobal') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContextSkills: + """ + Context data specific to particular skills used by the assistant. + + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. + """ + + def __init__( + self, + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional[ + 'StatelessMessageContextSkillsActionsSkill'] = None, + ) -> None: + """ + Initialize a StatelessMessageContextSkills object. + + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + args = {} + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args[ + 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( + actions_skill) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContextSkills object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageContextSkills') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageContextSkillsActionsSkill: + """ + Context variables that are used by the action skill. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + :param dict private_action_variables: (optional) An object containing private + action variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. Private variables are + encrypted. + :param dict private_skill_variables: (optional) An object containing private + skill variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action and + persist for the duration of the session. Private variables are encrypted. + """ + + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + private_action_variables: Optional[dict] = None, + private_skill_variables: Optional[dict] = None, + ) -> None: + """ + Initialize a StatelessMessageContextSkillsActionsSkill object. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + :param dict private_action_variables: (optional) An object containing + private action variables. Action variables can be accessed only by steps in + the same action, and do not persist after the action ends. Private + variables are encrypted. + :param dict private_skill_variables: (optional) An object containing + private skill variables. (In the watsonx Assistant user interface, skill + variables are called _session variables_.) Skill variables can be accessed + by any action and persist for the duration of the session. Private + variables are encrypted. + """ + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + self.private_action_variables = private_action_variables + self.private_skill_variables = private_skill_variables + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" + args = {} + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + if (private_action_variables := + _dict.get('private_action_variables')) is not None: + args['private_action_variables'] = private_action_variables + if (private_skill_variables := + _dict.get('private_skill_variables')) is not None: + args['private_skill_variables'] = private_skill_variables + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + if hasattr(self, 'private_action_variables' + ) and self.private_action_variables is not None: + _dict['private_action_variables'] = self.private_action_variables + if hasattr(self, 'private_skill_variables' + ) and self.private_skill_variables is not None: + _dict['private_skill_variables'] = self.private_skill_variables + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageInput: + """ + An input object that includes the input text. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param StatelessMessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['StatelessMessageInputOptions'] = None, + ) -> None: + """ + Initialize a StatelessMessageInput object. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param StatelessMessageInputOptions options: (optional) Optional properties + that control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': + """Initialize a StatelessMessageInput object from a json dictionary.""" + args = {} + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = StatelessMessageInputOptions.from_dict(options) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageInput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageInput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageInput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageInput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + + +class StatelessMessageInputOptions: + """ + Optional properties that control how the assistant responds. + + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + + def __init__( + self, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + ) -> None: + """ + Initialize a StatelessMessageInputOptions object. + + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + args = {} + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageInputOptions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageInputOptions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageResponse: + """ + A stateless response from the watsonx Assistant service. + + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param StatelessMessageContext context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ + + def __init__( + self, + output: 'MessageOutput', + context: 'StatelessMessageContext', + *, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + user_id: Optional[str] = None, + ) -> None: + """ + Initialize a StatelessMessageResponse object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param StatelessMessageContext context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + """ + self.output = output + self.context = context + self.masked_output = masked_output + self.masked_input = masked_input + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': + """Initialize a StatelessMessageResponse object from a json dictionary.""" + args = {} + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in StatelessMessageResponse JSON' + ) + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) + else: + raise ValueError( + 'Required property \'context\' not present in StatelessMessageResponse JSON' + ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatelessMessageResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'BulkClassifyOutput') -> bool: + def __ne__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class BulkClassifyResponse(): +class StatelessMessageStreamResponse: """ - BulkClassifyResponse. + A stateless streamed response form the watsonx Assistant service. - :attr List[BulkClassifyOutput] output: (optional) An array of objects that - contain classification information for the submitted input utterances. """ - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def __init__(self,) -> None: """ - Initialize a BulkClassifyResponse object. + Initialize a StatelessMessageStreamResponse object. - :param List[BulkClassifyOutput] output: (optional) An array of objects that - contain classification information for the submitted input utterances. """ - self.output = output + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'StatelessMessageStreamResponseMessageStreamPartialItem', + 'StatelessMessageStreamResponseMessageStreamCompleteItem', + 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse' + ])) + raise Exception(msg) + + +class StatusError: + """ + An object describing an error that occurred during processing of an asynchronous + operation. + + :param str message: (optional) The text of the error message. + """ + + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: + """ + Initialize a StatusError object. + + :param str message: (optional) The text of the error message. + """ + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': - """Initialize a BulkClassifyResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(x) for x in _dict.get('output') - ] + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a BulkClassifyResponse object from a json dictionary.""" + """Initialize a StatusError object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x.to_dict() for x in self.output] + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -714,57 +16372,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this BulkClassifyResponse object.""" + """Return a `str` version of this StatusError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'BulkClassifyResponse') -> bool: + def __eq__(self, other: 'StatusError') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'BulkClassifyResponse') -> bool: + def __ne__(self, other: 'StatusError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class BulkClassifyUtterance(): +class TurnEventActionSource: """ - The user input utterance to classify. + TurnEventActionSource. - :attr str text: The text of the input utterance. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog node. """ - def __init__(self, text: str) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + condition: Optional[str] = None, + ) -> None: """ - Initialize a BulkClassifyUtterance object. + Initialize a TurnEventActionSource object. - :param str text: The text of the input utterance. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog + node. """ - self.text = text + self.type = type + self.action = action + self.action_title = action_title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': - """Initialize a BulkClassifyUtterance object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': + """Initialize a TurnEventActionSource object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in BulkClassifyUtterance JSON' - ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a BulkClassifyUtterance object from a json dictionary.""" + """Initialize a TurnEventActionSource object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -772,65 +16457,225 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this BulkClassifyUtterance object.""" + """Return a `str` version of this TurnEventActionSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'BulkClassifyUtterance') -> bool: + def __eq__(self, other: 'TurnEventActionSource') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'BulkClassifyUtterance') -> bool: + def __ne__(self, other: 'TurnEventActionSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ -class CaptureGroup(): - """ - CaptureGroup. + ACTION = 'action' - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate - where the entity value begins and ends in the input text. + +class TurnEventCalloutCallout: + """ + TurnEventCalloutCallout. + + :param str type: (optional) The type of callout. Currently, the only supported + value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request object + executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response object + received by the external server made by the extension. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + internal: Optional[dict] = None, + result_variable: Optional[str] = None, + request: Optional['TurnEventCalloutCalloutRequest'] = None, + response: Optional['TurnEventCalloutCalloutResponse'] = None, + ) -> None: """ - Initialize a CaptureGroup object. + Initialize a TurnEventCalloutCallout object. + + :param str type: (optional) The type of callout. Currently, the only + supported value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request + object executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response + object received by the external server made by the extension. + """ + self.type = type + self.internal = internal + self.result_variable = result_variable + self.request = request + self.response = response - :param str group: A recognized capture group for the entity. - :param List[int] location: (optional) Zero-based character offsets that - indicate where the entity value begins and ends in the input text. + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (internal := _dict.get('internal')) is not None: + args['internal'] = internal + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + if (request := _dict.get('request')) is not None: + args['request'] = TurnEventCalloutCalloutRequest.from_dict(request) + if (response := _dict.get('response')) is not None: + args['response'] = TurnEventCalloutCalloutResponse.from_dict( + response) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'internal') and self.internal is not None: + _dict['internal'] = self.internal + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventCalloutCallout object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventCalloutCallout') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): """ - self.group = group - self.location = location + The type of callout. Currently, the only supported value is + `integration_interaction` (for calls to extensions). + """ + + INTEGRATION_INTERACTION = 'integration_interaction' + + +class TurnEventCalloutCalloutRequest: + """ + TurnEventCalloutCalloutRequest. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to the URL + of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server or an + object. In cases like timeouts or connections errors, it will contain details of + why the callout to the external server failed. + """ + + def __init__( + self, + *, + method: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None, + query_parameters: Optional[str] = None, + headers_: Optional[dict] = None, + body: Optional[dict] = None, + ) -> None: + """ + Initialize a TurnEventCalloutCalloutRequest object. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to + the URL of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server + or an object. In cases like timeouts or connections errors, it will contain + details of why the callout to the external server failed. + """ + self.method = method + self.url = url + self.path = path + self.query_parameters = query_parameters + self.headers_ = headers_ + self.body = body @classmethod - def from_dict(cls, _dict: Dict) -> 'CaptureGroup': - """Initialize a CaptureGroup object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutRequest': + """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') - else: - raise ValueError( - 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (method := _dict.get('method')) is not None: + args['method'] = method + if (url := _dict.get('url')) is not None: + args['url'] = url + if (path := _dict.get('path')) is not None: + args['path'] = path + if (query_parameters := _dict.get('query_parameters')) is not None: + args['query_parameters'] = query_parameters + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = headers_ + if (body := _dict.get('body')) is not None: + args['body'] = body return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CaptureGroup object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'group') and self.group is not None: - _dict['group'] = self.group - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if hasattr(self, 'method') and self.method is not None: + _dict['method'] = self.method + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'query_parameters') and self.query_parameters is not None: + _dict['query_parameters'] = self.query_parameters + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = self.headers_ + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body return _dict def _to_dict(self): @@ -838,65 +16683,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CaptureGroup object.""" + """Return a `str` version of this TurnEventCalloutCalloutRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CaptureGroup') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CaptureGroup') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MethodEnum(str, Enum): + """ + The REST method of the request. + """ + + GET = 'get' + POST = 'post' + PUT = 'put' + DELETE = 'delete' + PATCH = 'patch' + -class ChannelTransferInfo(): +class TurnEventCalloutCalloutResponse: """ - Information used by an integration to transfer the conversation to a different - channel. + TurnEventCalloutCalloutResponse. - :attr ChannelTransferTarget target: An object specifying target channels - available for the transfer. Each property of this object represents an available - transfer target. Currently, the only supported property is **chat**, - representing the web chat integration. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk received + from the response stream. """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__( + self, + *, + body: Optional[str] = None, + status_code: Optional[int] = None, + last_event: Optional[dict] = None, + ) -> None: """ - Initialize a ChannelTransferInfo object. + Initialize a TurnEventCalloutCalloutResponse object. - :param ChannelTransferTarget target: An object specifying target channels - available for the transfer. Each property of this object represents an - available transfer target. Currently, the only supported property is - **chat**, representing the web chat integration. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk + received from the response stream. """ - self.target = target + self.body = body + self.status_code = status_code + self.last_event = last_event @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': - """Initialize a ChannelTransferInfo object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutResponse': + """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) - else: - raise ValueError( - 'Required property \'target\' not present in ChannelTransferInfo JSON' - ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (status_code := _dict.get('status_code')) is not None: + args['status_code'] = status_code + if (last_event := _dict.get('last_event')) is not None: + args['last_event'] = last_event return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferInfo object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code + if hasattr(self, 'last_event') and self.last_event is not None: + _dict['last_event'] = self.last_event return _dict def _to_dict(self): @@ -904,58 +16772,59 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferInfo object.""" + """Return a `str` version of this TurnEventCalloutCalloutResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferInfo') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ChannelTransferInfo') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ChannelTransferTarget(): +class TurnEventCalloutError: """ - An object specifying target channels available for the transfer. Each property of this - object represents an available transfer target. Currently, the only supported property - is **chat**, representing the web chat integration. + TurnEventCalloutError. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :param str message: (optional) Any error message returned by a failed call to an + external service. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ - Initialize a ChannelTransferTarget object. + Initialize a TurnEventCalloutError object. - :param ChannelTransferTargetChat chat: (optional) Information for - transferring to the web chat integration. + :param str message: (optional) Any error message returned by a failed call + to an external service. """ - self.chat = chat + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': - """Initialize a ChannelTransferTarget object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': + """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferTarget object from a json dictionary.""" + """Initialize a TurnEventCalloutError object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'chat') and self.chat is not None: - _dict['chat'] = self.chat.to_dict() + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -963,53 +16832,252 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferTarget object.""" + """Return a `str` version of this TurnEventCalloutError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferTarget') -> bool: + def __eq__(self, other: 'TurnEventCalloutError') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ChannelTransferTarget') -> bool: + def __ne__(self, other: 'TurnEventCalloutError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ChannelTransferTargetChat(): +class TurnEventGenerativeAICalledCallout: """ - Information for transferring to the web chat integration. + TurnEventGenerativeAICalledCallout. + + :param bool search_called: (optional) Whether the document search engine was + called. + :param bool llm_called: (optional) Whether watsonx.ai was called during answer + generation. + :param TurnEventGenerativeAICalledCalloutSearch search: (optional) + :param TurnEventGenerativeAICalledCalloutLlm llm: (optional) + :param str idk_reason_code: (optional) Indicates why a conversational search + response resolved to an idk response. This field will only be available when the + conversational search response is an idk response. + """ + + def __init__( + self, + *, + search_called: Optional[bool] = None, + llm_called: Optional[bool] = None, + search: Optional['TurnEventGenerativeAICalledCalloutSearch'] = None, + llm: Optional['TurnEventGenerativeAICalledCalloutLlm'] = None, + idk_reason_code: Optional[str] = None, + ) -> None: + """ + Initialize a TurnEventGenerativeAICalledCallout object. + + :param bool search_called: (optional) Whether the document search engine + was called. + :param bool llm_called: (optional) Whether watsonx.ai was called during + answer generation. + :param TurnEventGenerativeAICalledCalloutSearch search: (optional) + :param TurnEventGenerativeAICalledCalloutLlm llm: (optional) + :param str idk_reason_code: (optional) Indicates why a conversational + search response resolved to an idk response. This field will only be + available when the conversational search response is an idk response. + """ + self.search_called = search_called + self.llm_called = llm_called + self.search = search + self.llm = llm + self.idk_reason_code = idk_reason_code + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventGenerativeAICalledCallout': + """Initialize a TurnEventGenerativeAICalledCallout object from a json dictionary.""" + args = {} + if (search_called := _dict.get('search_called')) is not None: + args['search_called'] = search_called + if (llm_called := _dict.get('llm_called')) is not None: + args['llm_called'] = llm_called + if (search := _dict.get('search')) is not None: + args['search'] = TurnEventGenerativeAICalledCalloutSearch.from_dict( + search) + if (llm := _dict.get('llm')) is not None: + args['llm'] = TurnEventGenerativeAICalledCalloutLlm.from_dict(llm) + if (idk_reason_code := _dict.get('idk_reason_code')) is not None: + args['idk_reason_code'] = idk_reason_code + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventGenerativeAICalledCallout object from a json dictionary.""" + return cls.from_dict(_dict) - :attr str url: (optional) The URL of the target web chat. + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'search_called') and self.search_called is not None: + _dict['search_called'] = self.search_called + if hasattr(self, 'llm_called') and self.llm_called is not None: + _dict['llm_called'] = self.llm_called + if hasattr(self, 'search') and self.search is not None: + if isinstance(self.search, dict): + _dict['search'] = self.search + else: + _dict['search'] = self.search.to_dict() + if hasattr(self, 'llm') and self.llm is not None: + if isinstance(self.llm, dict): + _dict['llm'] = self.llm + else: + _dict['llm'] = self.llm.to_dict() + if hasattr(self, + 'idk_reason_code') and self.idk_reason_code is not None: + _dict['idk_reason_code'] = self.idk_reason_code + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventGenerativeAICalledCallout object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventGenerativeAICalledCallout') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventGenerativeAICalledCallout') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TurnEventGenerativeAICalledCalloutLlm: + """ + TurnEventGenerativeAICalledCalloutLlm. + + :param str type: (optional) The name of the LLM engine called by the system. + :param str model_id: (optional) The LLM model used to generate the response. + :param str model_class_id: (optional) The watsonx.ai class ID that was used + during the answer generation request to the LLM. This is only included when a + request to the LLM has been made by the system. + :param int generated_token_count: (optional) The number of tokens that were + generated in the response by the LLM. This is only included when a request to + the LLM was successful and a response was generated. + :param int input_token_count: (optional) The number of tokens that were sent to + the LLM during answer generation. This is only included when a request to the + LLM has been made by the system. + :param bool success: (optional) Whether the answer generation request to the LLM + was successful. + :param TurnEventGenerativeAICalledCalloutLlmResponse response: (optional) + :param List[SearchResults] request: (optional) n array of objects containing the + search results. """ - def __init__(self, *, url: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + model_id: Optional[str] = None, + model_class_id: Optional[str] = None, + generated_token_count: Optional[int] = None, + input_token_count: Optional[int] = None, + success: Optional[bool] = None, + response: Optional[ + 'TurnEventGenerativeAICalledCalloutLlmResponse'] = None, + request: Optional[List['SearchResults']] = None, + ) -> None: """ - Initialize a ChannelTransferTargetChat object. + Initialize a TurnEventGenerativeAICalledCalloutLlm object. - :param str url: (optional) The URL of the target web chat. + :param str type: (optional) The name of the LLM engine called by the + system. + :param str model_id: (optional) The LLM model used to generate the + response. + :param str model_class_id: (optional) The watsonx.ai class ID that was used + during the answer generation request to the LLM. This is only included when + a request to the LLM has been made by the system. + :param int generated_token_count: (optional) The number of tokens that were + generated in the response by the LLM. This is only included when a request + to the LLM was successful and a response was generated. + :param int input_token_count: (optional) The number of tokens that were + sent to the LLM during answer generation. This is only included when a + request to the LLM has been made by the system. + :param bool success: (optional) Whether the answer generation request to + the LLM was successful. + :param TurnEventGenerativeAICalledCalloutLlmResponse response: (optional) + :param List[SearchResults] request: (optional) n array of objects + containing the search results. """ - self.url = url + self.type = type + self.model_id = model_id + self.model_class_id = model_class_id + self.generated_token_count = generated_token_count + self.input_token_count = input_token_count + self.success = success + self.response = response + self.request = request @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': - """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutLlm': + """Initialize a TurnEventGenerativeAICalledCalloutLlm object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (model_class_id := _dict.get('model_class_id')) is not None: + args['model_class_id'] = model_class_id + if (generated_token_count := + _dict.get('generated_token_count')) is not None: + args['generated_token_count'] = generated_token_count + if (input_token_count := _dict.get('input_token_count')) is not None: + args['input_token_count'] = input_token_count + if (success := _dict.get('success')) is not None: + args['success'] = success + if (response := _dict.get('response')) is not None: + args[ + 'response'] = TurnEventGenerativeAICalledCalloutLlmResponse.from_dict( + response) + if (request := _dict.get('request')) is not None: + args['request'] = [SearchResults.from_dict(v) for v in request] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutLlm object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'model_class_id') and self.model_class_id is not None: + _dict['model_class_id'] = self.model_class_id + if hasattr(self, 'generated_token_count' + ) and self.generated_token_count is not None: + _dict['generated_token_count'] = self.generated_token_count + if hasattr(self, + 'input_token_count') and self.input_token_count is not None: + _dict['input_token_count'] = self.input_token_count + if hasattr(self, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() + if hasattr(self, 'request') and self.request is not None: + request_list = [] + for v in self.request: + if isinstance(v, dict): + request_list.append(v) + else: + request_list.append(v.to_dict()) + _dict['request'] = request_list return _dict def _to_dict(self): @@ -1017,95 +17085,77 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferTargetChat object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutLlm object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferTargetChat') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledCalloutLlm') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledCalloutLlm') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogLogMessage(): +class TurnEventGenerativeAICalledCalloutLlmResponse: """ - Dialog log message details. + - :attr str level: The severity of the log message. - :attr str message: The text of the log message. - :attr str code: A code that indicates the category to which the error message - belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog - element that generated the error message. + :param str text: (optional) The LLM response that is returned. + :param str response_type: (optional) The type of response that is returned. + :param bool is_idk_response: (optional) Whether the response is an idk response. """ - def __init__(self, - level: str, - message: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + response_type: Optional[str] = None, + is_idk_response: Optional[bool] = None, + ) -> None: """ - Initialize a DialogLogMessage object. + Initialize a TurnEventGenerativeAICalledCalloutLlmResponse object. - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error - message belongs. - :param LogMessageSource source: (optional) An object that identifies the - dialog element that generated the error message. + :param str text: (optional) The LLM response that is returned. + :param str response_type: (optional) The type of response that is returned. + :param bool is_idk_response: (optional) Whether the response is an idk + response. """ - self.level = level - self.message = message - self.code = code - self.source = source + self.text = text + self.response_type = response_type + self.is_idk_response = is_idk_response @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': - """Initialize a DialogLogMessage object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutLlmResponse': + """Initialize a TurnEventGenerativeAICalledCalloutLlmResponse object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - else: - raise ValueError( - 'Required property \'level\' not present in DialogLogMessage JSON' - ) - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in DialogLogMessage JSON' - ) - if 'code' in _dict: - args['code'] = _dict.get('code') - else: - raise ValueError( - 'Required property \'code\' not present in DialogLogMessage JSON' - ) - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + if (is_idk_response := _dict.get('is_idk_response')) is not None: + args['is_idk_response'] = is_idk_response return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogLogMessage object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutLlmResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'is_idk_response') and self.is_idk_response is not None: + _dict['is_idk_response'] = self.is_idk_response return _dict def _to_dict(self): @@ -1113,110 +17163,115 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogLogMessage object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutLlmResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogLogMessage') -> bool: + def __eq__(self, + other: 'TurnEventGenerativeAICalledCalloutLlmResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogLogMessage') -> bool: + def __ne__(self, + other: 'TurnEventGenerativeAICalledCalloutLlmResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LevelEnum(str, Enum): - """ - The severity of the log message. - """ - INFO = 'info' - ERROR = 'error' - WARN = 'warn' - -class DialogNodeAction(): +class TurnEventGenerativeAICalledCalloutRequest: """ - DialogNodeAction. - - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result - of the action is stored. - :attr str credentials: (optional) The name of the context variable that the - client application will use to pass in credentials for the action. + TurnEventGenerativeAICalledCalloutRequest. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str port: (optional) The host port of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to the URL + of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server or an + object. In cases like timeouts or connections errors, it will contain details of + why the callout to the external server failed. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__( + self, + *, + method: Optional[str] = None, + url: Optional[str] = None, + port: Optional[str] = None, + path: Optional[str] = None, + query_parameters: Optional[str] = None, + headers_: Optional[dict] = None, + body: Optional[dict] = None, + ) -> None: """ - Initialize a DialogNodeAction object. - - :param str name: The name of the action. - :param str result_variable: The location in the dialog context where the - result of the action is stored. - :param str type: (optional) The type of action to invoke. - :param dict parameters: (optional) A map of key/value pairs to be provided - to the action. - :param str credentials: (optional) The name of the context variable that - the client application will use to pass in credentials for the action. + Initialize a TurnEventGenerativeAICalledCalloutRequest object. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str port: (optional) The host port of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to + the URL of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server + or an object. In cases like timeouts or connections errors, it will contain + details of why the callout to the external server failed. """ - self.name = name - self.type = type - self.parameters = parameters - self.result_variable = result_variable - self.credentials = credentials + self.method = method + self.url = url + self.port = port + self.path = path + self.query_parameters = query_parameters + self.headers_ = headers_ + self.body = body @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': - """Initialize a DialogNodeAction object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutRequest': + """Initialize a TurnEventGenerativeAICalledCalloutRequest object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in DialogNodeAction JSON' - ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') - else: - raise ValueError( - 'Required property \'result_variable\' not present in DialogNodeAction JSON' - ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if (method := _dict.get('method')) is not None: + args['method'] = method + if (url := _dict.get('url')) is not None: + args['url'] = url + if (port := _dict.get('port')) is not None: + args['port'] = port + if (path := _dict.get('path')) is not None: + args['path'] = path + if (query_parameters := _dict.get('query_parameters')) is not None: + args['query_parameters'] = query_parameters + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = headers_ + if (body := _dict.get('body')) is not None: + args['body'] = body return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeAction object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutRequest object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'parameters') and self.parameters is not None: - _dict['parameters'] = self.parameters + if hasattr(self, 'method') and self.method is not None: + _dict['method'] = self.method + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable - if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = self.credentials + 'query_parameters') and self.query_parameters is not None: + _dict['query_parameters'] = self.query_parameters + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = self.headers_ + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body return _dict def _to_dict(self): @@ -1224,63 +17279,81 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeAction object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeAction') -> bool: + def __eq__(self, + other: 'TurnEventGenerativeAICalledCalloutRequest') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeAction') -> bool: + def __ne__(self, + other: 'TurnEventGenerativeAICalledCalloutRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class MethodEnum(str, Enum): """ - The type of action to invoke. + The REST method of the request. """ - CLIENT = 'client' - SERVER = 'server' - WEB_ACTION = 'web-action' - CLOUD_FUNCTION = 'cloud-function' + GET = 'GET' + POST = 'POST' + PUT = 'PUT' + DELETE = 'DELETE' + PATCH = 'PATCH' -class DialogNodeOutputConnectToAgentTransferInfo(): + +class TurnEventGenerativeAICalledCalloutResponse: """ - Routing or other contextual information to be used by target service desk systems. + TurnEventGenerativeAICalledCalloutResponse. - :attr dict target: (optional) + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. """ - def __init__(self, *, target: dict = None) -> None: + def __init__( + self, + *, + body: Optional[str] = None, + status_code: Optional[int] = None, + ) -> None: """ - Initialize a DialogNodeOutputConnectToAgentTransferInfo object. + Initialize a TurnEventGenerativeAICalledCalloutResponse object. - :param dict target: (optional) + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. """ - self.target = target + self.body = body + self.status_code = status_code @classmethod def from_dict(cls, - _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': - """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutResponse': + """Initialize a TurnEventGenerativeAICalledCalloutResponse object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if (body := _dict.get('body')) is not None: + args['body'] = body + if (status_code := _dict.get('status_code')) is not None: + args['status_code'] = status_code return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code return _dict def _to_dict(self): @@ -1288,75 +17361,109 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutResponse object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, - other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + other: 'TurnEventGenerativeAICalledCalloutResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, - other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + other: 'TurnEventGenerativeAICalledCalloutResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputOptionsElement(): +class TurnEventGenerativeAICalledCalloutSearch: """ - DialogNodeOutputOptionsElement. - - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message - input to be sent to the assistant if the user selects the corresponding option. + TurnEventGenerativeAICalledCalloutSearch. + + :param str engine: (optional) The search engine that was used to scan the + documents. + :param str index: (optional) The name of the Elasticsearch index being used. + This field is only available if the engine being used is Elasticsearch. + :param str query: (optional) The query that will be used by the system to + initiate search on the document search engine. + :param TurnEventGenerativeAICalledCalloutRequest request: (optional) + :param TurnEventGenerativeAICalledCalloutResponse response: (optional) """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__( + self, + *, + engine: Optional[str] = None, + index: Optional[str] = None, + query: Optional[str] = None, + request: Optional['TurnEventGenerativeAICalledCalloutRequest'] = None, + response: Optional['TurnEventGenerativeAICalledCalloutResponse'] = None, + ) -> None: """ - Initialize a DialogNodeOutputOptionsElement object. - - :param str label: The user-facing label for the option. - :param DialogNodeOutputOptionsElementValue value: An object defining the - message input to be sent to the assistant if the user selects the - corresponding option. + Initialize a TurnEventGenerativeAICalledCalloutSearch object. + + :param str engine: (optional) The search engine that was used to scan the + documents. + :param str index: (optional) The name of the Elasticsearch index being + used. This field is only available if the engine being used is + Elasticsearch. + :param str query: (optional) The query that will be used by the system to + initiate search on the document search engine. + :param TurnEventGenerativeAICalledCalloutRequest request: (optional) + :param TurnEventGenerativeAICalledCalloutResponse response: (optional) """ - self.label = label - self.value = value + self.engine = engine + self.index = index + self.query = query + self.request = request + self.response = response @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': - """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutSearch': + """Initialize a TurnEventGenerativeAICalledCalloutSearch object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' - ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) - else: - raise ValueError( - 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' - ) + if (engine := _dict.get('engine')) is not None: + args['engine'] = engine + if (index := _dict.get('index')) is not None: + args['index'] = index + if (query := _dict.get('query')) is not None: + args['query'] = query + if (request := _dict.get('request')) is not None: + args[ + 'request'] = TurnEventGenerativeAICalledCalloutRequest.from_dict( + request) + if (response := _dict.get('response')) is not None: + args[ + 'response'] = TurnEventGenerativeAICalledCalloutResponse.from_dict( + response) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutSearch object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if hasattr(self, 'engine') and self.engine is not None: + _dict['engine'] = self.engine + if hasattr(self, 'index') and self.index is not None: + _dict['index'] = self.index + if hasattr(self, 'query') and self.query is not None: + _dict['query'] = self.query + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() return _dict def _to_dict(self): @@ -1364,56 +17471,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputOptionsElement object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledCalloutSearch') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledCalloutSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputOptionsElementValue(): +class TurnEventGenerativeAICalledMetrics: """ - An object defining the message input to be sent to the assistant if the user selects - the corresponding option. - - :attr MessageInput input: (optional) An input object that includes the input - text. + TurnEventGenerativeAICalledMetrics. + + :param float search_time_ms: (optional) The amount of time (in milliseconds) it + took for the system to complete the search using the document search engine. + :param float answer_generation_time_ms: (optional) The amount of time (in + milliseconds) it took for the system to complete answer generation process by + reaching out to watsonx.ai. + :param float total_time_ms: (optional) The amount of time (in milliseconds) it + took for the system to fully process the conversational search. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__( + self, + *, + search_time_ms: Optional[float] = None, + answer_generation_time_ms: Optional[float] = None, + total_time_ms: Optional[float] = None, + ) -> None: """ - Initialize a DialogNodeOutputOptionsElementValue object. - - :param MessageInput input: (optional) An input object that includes the - input text. + Initialize a TurnEventGenerativeAICalledMetrics object. + + :param float search_time_ms: (optional) The amount of time (in + milliseconds) it took for the system to complete the search using the + document search engine. + :param float answer_generation_time_ms: (optional) The amount of time (in + milliseconds) it took for the system to complete answer generation process + by reaching out to watsonx.ai. + :param float total_time_ms: (optional) The amount of time (in milliseconds) + it took for the system to fully process the conversational search. """ - self.input = input + self.search_time_ms = search_time_ms + self.answer_generation_time_ms = answer_generation_time_ms + self.total_time_ms = total_time_ms @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': - """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventGenerativeAICalledMetrics': + """Initialize a TurnEventGenerativeAICalledMetrics object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (search_time_ms := _dict.get('search_time_ms')) is not None: + args['search_time_ms'] = search_time_ms + if (answer_generation_time_ms := + _dict.get('answer_generation_time_ms')) is not None: + args['answer_generation_time_ms'] = answer_generation_time_ms + if (total_time_ms := _dict.get('total_time_ms')) is not None: + args['total_time_ms'] = total_time_ms return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledMetrics object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if hasattr(self, 'search_time_ms') and self.search_time_ms is not None: + _dict['search_time_ms'] = self.search_time_ms + if hasattr(self, 'answer_generation_time_ms' + ) and self.answer_generation_time_ms is not None: + _dict['answer_generation_time_ms'] = self.answer_generation_time_ms + if hasattr(self, 'total_time_ms') and self.total_time_ms is not None: + _dict['total_time_ms'] = self.total_time_ms return _dict def _to_dict(self): @@ -1421,75 +17556,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" + """Return a `str` version of this TurnEventGenerativeAICalledMetrics object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledMetrics') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledMetrics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeVisited(): +class TurnEventNodeSource: """ - An objects containing detailed diagnostic information about a dialog node that was - triggered during processing of the input message. + TurnEventNodeSource. - :attr str dialog_node: (optional) A dialog node that was triggered during + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog node. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + condition: Optional[str] = None, + ) -> None: """ - Initialize a DialogNodeVisited object. + Initialize a TurnEventNodeSource object. - :param str dialog_node: (optional) A dialog node that was triggered during + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. :param str title: (optional) The title of the dialog node. - :param str conditions: (optional) The conditions that trigger the dialog + :param str condition: (optional) The condition that triggered the dialog node. """ + self.type = type self.dialog_node = dialog_node self.title = title - self.conditions = conditions + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': - """Initialize a DialogNodeVisited object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': + """Initialize a TurnEventNodeSource object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeVisited object from a json dictionary.""" + """Initialize a TurnEventNodeSource object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title - if hasattr(self, 'conditions') and self.conditions is not None: - _dict['conditions'] = self.conditions + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -1497,89 +17641,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeVisited object.""" + """Return a `str` version of this TurnEventNodeSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeVisited') -> bool: + def __eq__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeVisited') -> bool: + def __ne__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + DIALOG_NODE = 'dialog_node' -class DialogSuggestion(): + +class TurnEventSearchError: """ - DialogSuggestion. + TurnEventSearchError. - :attr str label: The user-facing label for the suggestion. This label is taken - from the **title** or **user_label** property of the corresponding dialog node, - depending on the disambiguation options. - :attr DialogSuggestionValue value: An object defining the message input to be - sent to the assistant if the user selects the corresponding disambiguation - option. - :attr dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. + :param str message: (optional) Any error message returned by a failed call to a + search skill. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ - Initialize a DialogSuggestion object. + Initialize a TurnEventSearchError object. - :param str label: The user-facing label for the suggestion. This label is - taken from the **title** or **user_label** property of the corresponding - dialog node, depending on the disambiguation options. - :param DialogSuggestionValue value: An object defining the message input to - be sent to the assistant if the user selects the corresponding - disambiguation option. - :param dict output: (optional) The dialog output that will be returned from - the Watson Assistant service if the user selects the corresponding option. + :param str message: (optional) Any error message returned by a failed call + to a search skill. """ - self.label = label - self.value = value - self.output = output + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': - """Initialize a DialogSuggestion object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': + """Initialize a TurnEventSearchError object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in DialogSuggestion JSON' - ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) - else: - raise ValueError( - 'Required property \'value\' not present in DialogSuggestion JSON' - ) - if 'output' in _dict: - args['output'] = _dict.get('output') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestion object from a json dictionary.""" + """Initialize a TurnEventSearchError object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -1587,56 +17708,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogSuggestion object.""" + """Return a `str` version of this TurnEventSearchError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestion') -> bool: + def __eq__(self, other: 'TurnEventSearchError') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogSuggestion') -> bool: + def __ne__(self, other: 'TurnEventSearchError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogSuggestionValue(): +class TurnEventStepSource: """ - An object defining the message input to be sent to the assistant if the user selects - the corresponding disambiguation option. + TurnEventStepSource. - :attr MessageInput input: (optional) An input object that includes the input - text. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str step: (optional) A step that was visited during processing of the + message. + :param bool is_ai_guided: (optional) Whether the action that the turn event was + generated from is an AI-guided action. + :param bool is_skill_based: (optional) Whether the action that the turn event + was generated from is a skill-guided action. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + step: Optional[str] = None, + is_ai_guided: Optional[bool] = None, + is_skill_based: Optional[bool] = None, + ) -> None: """ - Initialize a DialogSuggestionValue object. + Initialize a TurnEventStepSource object. - :param MessageInput input: (optional) An input object that includes the - input text. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str step: (optional) A step that was visited during processing of + the message. + :param bool is_ai_guided: (optional) Whether the action that the turn event + was generated from is an AI-guided action. + :param bool is_skill_based: (optional) Whether the action that the turn + event was generated from is a skill-guided action. """ - self.input = input + self.type = type + self.action = action + self.action_title = action_title + self.step = step + self.is_ai_guided = is_ai_guided + self.is_skill_based = is_skill_based @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': - """Initialize a DialogSuggestionValue object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventStepSource': + """Initialize a TurnEventStepSource object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (step := _dict.get('step')) is not None: + args['step'] = step + if (is_ai_guided := _dict.get('is_ai_guided')) is not None: + args['is_ai_guided'] = is_ai_guided + if (is_skill_based := _dict.get('is_skill_based')) is not None: + args['is_skill_based'] = is_skill_based return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestionValue object from a json dictionary.""" + """Initialize a TurnEventStepSource object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'is_ai_guided') and self.is_ai_guided is not None: + _dict['is_ai_guided'] = self.is_ai_guided + if hasattr(self, 'is_skill_based') and self.is_skill_based is not None: + _dict['is_skill_based'] = self.is_skill_based return _dict def _to_dict(self): @@ -1644,183 +17814,72 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogSuggestionValue object.""" + """Return a `str` version of this TurnEventStepSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestionValue') -> bool: + def __eq__(self, other: 'TurnEventStepSource') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogSuggestionValue') -> bool: + def __ne__(self, other: 'TurnEventStepSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + STEP = 'step' -class Log(): + +class UpdateEnvironmentOrchestration: """ - Log. + The search skill orchestration settings for the environment. - :attr str log_id: A unique identifier for the logged event. - :attr MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :attr MessageResponse response: A response from the Watson Assistant service. - :attr str assistant_id: Unique identifier of the assistant. - :attr str session_id: The ID of the session the message was part of. - :attr str skill_id: The unique identifier of the skill that responded to the - message. - :attr str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the - message. - :attr str language: The language of the assistant to which the message request - was made. - :attr str customer_id: (optional) The customer ID specified for the message, if - any. + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). """ - def __init__(self, - log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, - *, - customer_id: str = None) -> None: + def __init__( + self, + *, + search_skill_fallback: Optional[bool] = None, + ) -> None: """ - Initialize a Log object. + Initialize a UpdateEnvironmentOrchestration object. - :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant - service. - :param str assistant_id: Unique identifier of the assistant. - :param str session_id: The ID of the session the message was part of. - :param str skill_id: The unique identifier of the skill that responded to - the message. - :param str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :param str request_timestamp: The timestamp for receipt of the message. - :param str response_timestamp: The timestamp for the system response to the - message. - :param str language: The language of the assistant to which the message - request was made. - :param str customer_id: (optional) The customer ID specified for the - message, if any. + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). """ - self.log_id = log_id - self.request = request - self.response = response - self.assistant_id = assistant_id - self.session_id = session_id - self.skill_id = skill_id - self.snapshot = snapshot - self.request_timestamp = request_timestamp - self.response_timestamp = response_timestamp - self.language = language - self.customer_id = customer_id + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, _dict: Dict) -> 'Log': - """Initialize a Log object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentOrchestration': + """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" args = {} - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') - else: - raise ValueError( - 'Required property \'log_id\' not present in Log JSON') - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) - else: - raise ValueError( - 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) - else: - raise ValueError( - 'Required property \'response\' not present in Log JSON') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - else: - raise ValueError( - 'Required property \'assistant_id\' not present in Log JSON') - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - else: - raise ValueError( - 'Required property \'session_id\' not present in Log JSON') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - else: - raise ValueError( - 'Required property \'skill_id\' not present in Log JSON') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - else: - raise ValueError( - 'Required property \'snapshot\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') - else: - raise ValueError( - 'Required property \'request_timestamp\' not present in Log JSON' - ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') - else: - raise ValueError( - 'Required property \'response_timestamp\' not present in Log JSON' - ) - if 'language' in _dict: - args['language'] = _dict.get('language') - else: - raise ValueError( - 'Required property \'language\' not present in Log JSON') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Log object from a json dictionary.""" + """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'log_id') and self.log_id is not None: - _dict['log_id'] = self.log_id - if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() - if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() - if hasattr(self, 'assistant_id') and self.assistant_id is not None: - _dict['assistant_id'] = self.assistant_id - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id - if hasattr(self, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - if hasattr(self, - 'request_timestamp') and self.request_timestamp is not None: - _dict['request_timestamp'] = self.request_timestamp - if hasattr( - self, - 'response_timestamp') and self.response_timestamp is not None: - _dict['response_timestamp'] = self.response_timestamp - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id + if hasattr(self, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback return _dict def _to_dict(self): @@ -1828,69 +17887,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Log object.""" + """Return a `str` version of this UpdateEnvironmentOrchestration object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Log') -> bool: + def __eq__(self, other: 'UpdateEnvironmentOrchestration') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Log') -> bool: + def __ne__(self, other: 'UpdateEnvironmentOrchestration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogCollection(): +class UpdateEnvironmentReleaseReference: """ - LogCollection. + An object describing the release that is currently deployed in the environment. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :param str release: (optional) The name of the deployed release. """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__( + self, + *, + release: Optional[str] = None, + ) -> None: """ - Initialize a LogCollection object. + Initialize a UpdateEnvironmentReleaseReference object. - :param List[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned - objects. + :param str release: (optional) The name of the deployed release. """ - self.logs = logs - self.pagination = pagination + self.release = release @classmethod - def from_dict(cls, _dict: Dict) -> 'LogCollection': - """Initialize a LogCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentReleaseReference': + """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] - else: - raise ValueError( - 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) - else: - raise ValueError( - 'Required property \'pagination\' not present in LogCollection JSON' - ) + if (release := _dict.get('release')) is not None: + args['release'] = release return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogCollection object from a json dictionary.""" + """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x.to_dict() for x in self.logs] - if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -1898,134 +17945,187 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogCollection object.""" + """Return a `str` version of this UpdateEnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogCollection') -> bool: + def __eq__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogCollection') -> bool: + def __ne__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSource(): +class CompleteItem(RuntimeResponseGeneric): """ - An object that identifies the dialog element that generated the error message. + CompleteItem. + :param Metadata streaming_metadata: """ - def __init__(self) -> None: + def __init__( + self, + streaming_metadata: 'Metadata', + ) -> None: """ - Initialize a LogMessageSource object. + Initialize a CompleteItem object. + :param Metadata streaming_metadata: """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) + # pylint: disable=super-init-not-called + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSource': - """Initialize a LogMessageSource object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) + def from_dict(cls, _dict: Dict) -> 'CompleteItem': + """Initialize a CompleteItem object from a json dictionary.""" + args = {} + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in CompleteItem JSON' + ) + return cls(**args) @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a LogMessageSource object from a json dictionary.""" + def _from_dict(cls, _dict): + """Initialize a CompleteItem object from a json dictionary.""" return cls.from_dict(_dict) - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['dialog_node'] = 'LogMessageSourceDialogNode' - mapping['action'] = 'LogMessageSourceAction' - mapping['step'] = 'LogMessageSourceStep' - mapping['handler'] = 'LogMessageSourceHandler' - disc_value = _dict.get('type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'type\' not found in LogMessageSource JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() + return _dict + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() -class LogPagination(): - """ - The pagination data for the returned objects. + def __str__(self) -> str: + """Return a `str` version of this CompleteItem object.""" + return json.dumps(self.to_dict(), indent=2) - :attr str next_url: (optional) The URL that will return the next page of - results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + def __eq__(self, other: 'CompleteItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CompleteItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class GenerativeAITaskContentGroundedAnswering(GenerativeAITask): + """ + GenerativeAITaskContentGroundedAnswering. + + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk response. + :param bool is_hap_detected: (optional) Whether response was a hap response. + :param GenerativeAITaskConfidenceScores confidence_scores: (optional) The + confidence scores for determining whether to show the generated response or an + “I don't know” response. + :param str original_response: (optional) The original response returned by the + generative ai. + :param str inferred_query: (optional) Generated from the input text after + auto-correction. If this field is not present, the input text was used as the + query to the generative ai. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__( + self, + *, + task: Optional[str] = None, + is_idk_response: Optional[bool] = None, + is_hap_detected: Optional[bool] = None, + confidence_scores: Optional['GenerativeAITaskConfidenceScores'] = None, + original_response: Optional[str] = None, + inferred_query: Optional[str] = None, + ) -> None: """ - Initialize a LogPagination object. + Initialize a GenerativeAITaskContentGroundedAnswering object. - :param str next_url: (optional) The URL that will return the next page of - results, if any. - :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk + response. + :param bool is_hap_detected: (optional) Whether response was a hap + response. + :param GenerativeAITaskConfidenceScores confidence_scores: (optional) The + confidence scores for determining whether to show the generated response or + an “I don't know” response. + :param str original_response: (optional) The original response returned by + the generative ai. + :param str inferred_query: (optional) Generated from the input text after + auto-correction. If this field is not present, the input text was used as + the query to the generative ai. """ - self.next_url = next_url - self.matched = matched - self.next_cursor = next_cursor + # pylint: disable=super-init-not-called + self.task = task + self.is_idk_response = is_idk_response + self.is_hap_detected = is_hap_detected + self.confidence_scores = confidence_scores + self.original_response = original_response + self.inferred_query = inferred_query @classmethod - def from_dict(cls, _dict: Dict) -> 'LogPagination': - """Initialize a LogPagination object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'GenerativeAITaskContentGroundedAnswering': + """Initialize a GenerativeAITaskContentGroundedAnswering object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (task := _dict.get('task')) is not None: + args['task'] = task + if (is_idk_response := _dict.get('is_idk_response')) is not None: + args['is_idk_response'] = is_idk_response + if (is_hap_detected := _dict.get('is_hap_detected')) is not None: + args['is_hap_detected'] = is_hap_detected + if (confidence_scores := _dict.get('confidence_scores')) is not None: + args[ + 'confidence_scores'] = GenerativeAITaskConfidenceScores.from_dict( + confidence_scores) + if (original_response := _dict.get('original_response')) is not None: + args['original_response'] = original_response + if (inferred_query := _dict.get('inferred_query')) is not None: + args['inferred_query'] = inferred_query return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogPagination object from a json dictionary.""" + """Initialize a GenerativeAITaskContentGroundedAnswering object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'task') and self.task is not None: + _dict['task'] = self.task + if hasattr(self, + 'is_idk_response') and self.is_idk_response is not None: + _dict['is_idk_response'] = self.is_idk_response + if hasattr(self, + 'is_hap_detected') and self.is_hap_detected is not None: + _dict['is_hap_detected'] = self.is_hap_detected + if hasattr(self, + 'confidence_scores') and self.confidence_scores is not None: + if isinstance(self.confidence_scores, dict): + _dict['confidence_scores'] = self.confidence_scores + else: + _dict['confidence_scores'] = self.confidence_scores.to_dict() + if hasattr(self, + 'original_response') and self.original_response is not None: + _dict['original_response'] = self.original_response + if hasattr(self, 'inferred_query') and self.inferred_query is not None: + _dict['inferred_query'] = self.inferred_query return _dict def _to_dict(self): @@ -2033,87 +18133,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogPagination object.""" + """Return a `str` version of this GenerativeAITaskContentGroundedAnswering object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogPagination') -> bool: + def __eq__(self, other: 'GenerativeAITaskContentGroundedAnswering') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogPagination') -> bool: + def __ne__(self, other: 'GenerativeAITaskContentGroundedAnswering') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContext(): +class GenerativeAITaskGeneralPurposeAnswering(GenerativeAITask): """ - MessageContext. + GenerativeAITaskGeneralPurposeAnswering. - :attr MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :attr object integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk response. + :param bool is_hap_detected: (optional) Whether response was a hap response. """ - def __init__(self, - *, - global_: 'MessageContextGlobal' = None, - skills: dict = None, - integrations: object = None) -> None: + def __init__( + self, + *, + task: Optional[str] = None, + is_idk_response: Optional[bool] = None, + is_hap_detected: Optional[bool] = None, + ) -> None: """ - Initialize a MessageContext object. + Initialize a GenerativeAITaskGeneralPurposeAnswering object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk + response. + :param bool is_hap_detected: (optional) Whether response was a hap + response. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + # pylint: disable=super-init-not-called + self.task = task + self.is_idk_response = is_idk_response + self.is_hap_detected = is_hap_detected @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'GenerativeAITaskGeneralPurposeAnswering': + """Initialize a GenerativeAITaskGeneralPurposeAnswering object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobal.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (task := _dict.get('task')) is not None: + args['task'] = task + if (is_idk_response := _dict.get('is_idk_response')) is not None: + args['is_idk_response'] = is_idk_response + if (is_hap_detected := _dict.get('is_hap_detected')) is not None: + args['is_hap_detected'] = is_hap_detected return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a GenerativeAITaskGeneralPurposeAnswering object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'task') and self.task is not None: + _dict['task'] = self.task + if hasattr(self, + 'is_idk_response') and self.is_idk_response is not None: + _dict['is_idk_response'] = self.is_idk_response + if hasattr(self, + 'is_hap_detected') and self.is_hap_detected is not None: + _dict['is_hap_detected'] = self.is_hap_detected return _dict def _to_dict(self): @@ -2121,66 +18213,77 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContext object.""" + """Return a `str` version of this GenerativeAITaskGeneralPurposeAnswering object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContext') -> bool: + def __eq__(self, other: 'GenerativeAITaskGeneralPurposeAnswering') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContext') -> bool: + def __ne__(self, other: 'GenerativeAITaskGeneralPurposeAnswering') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal(): +class LogMessageSourceAction(LogMessageSource): """ - Session context data that is shared by all skills used by the assistant. + An object that identifies the dialog element that generated the error message. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The session ID. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__( + self, + type: str, + action: str, + ) -> None: """ - Initialize a MessageContextGlobal object. + Initialize a LogMessageSourceAction object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. """ - self.system = system - self.session_id = session_id + # pylint: disable=super-init-not-called + self.type = type + self.action = action @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" + """Initialize a LogMessageSourceAction object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action return _dict def _to_dict(self): @@ -2188,66 +18291,77 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this LogMessageSourceAction object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'LogMessageSourceAction') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'LogMessageSourceAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalStateless(): +class LogMessageSourceDialogNode(LogMessageSource): """ - Session context data that is shared by all skills used by the assistant. + An object that identifies the dialog element that generated the error message. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The unique identifier of the session. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that generated + the error message. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__( + self, + type: str, + dialog_node: str, + ) -> None: """ - Initialize a MessageContextGlobalStateless object. + Initialize a LogMessageSourceDialogNode object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. """ - self.system = system - self.session_id = session_id + # pylint: disable=super-init-not-called + self.type = type + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' + ) + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + else: + raise ValueError( + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -2255,194 +18369,102 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalStateless object.""" + """Return a `str` version of this LogMessageSourceDialogNode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: + def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: + def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalSystem(): +class LogMessageSourceHandler(LogMessageSource): """ - Built-in system properties that apply to all skills used by the assistant. + An object that identifies the dialog element that generated the error message. - :attr str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :attr int turn_count: (optional) A counter that is automatically incremented - with each turn of the conversation. A value of 1 indicates that this is the the - first turn of a new conversation, which can affect the behavior of some skills - (for example, triggering the start node of a dialog). - :attr str locale: (optional) The language code for localization in the user - input. The specified locale overrides the default for the assistant, and is used - for interpreting entity values in user input such as date values. For example, - `04/03/2018` might be interpreted either as April 3 or March 4, depending on the - locale. - This property is included only if the new system entities are enabled for the - skill. - :attr str reference_time: (optional) The base time for interpreting any relative - time mentions in the user input. The specified time overrides the current server - time, and is used to calculate times mentioned in relative terms such as `now` - or `tomorrow`. This can be useful for simulating past or future times for - testing purposes, or when analyzing documents such as news articles. - This value must be a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :attr str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :attr str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :attr bool skip_user_input: (optional) For internal use only. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: (optional) The unique identifier of the step that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. """ - def __init__(self, - *, - timezone: str = None, - user_id: str = None, - turn_count: int = None, - locale: str = None, - reference_time: str = None, - session_start_time: str = None, - state: str = None, - skip_user_input: bool = None) -> None: + def __init__( + self, + type: str, + action: str, + handler: str, + *, + step: Optional[str] = None, + ) -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a LogMessageSourceHandler object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented with each turn of the conversation. A value of 1 indicates that - this is the the first turn of a new conversation, which can affect the - behavior of some skills (for example, triggering the start node of a - dialog). - :param str locale: (optional) The language code for localization in the - user input. The specified locale overrides the default for the assistant, - and is used for interpreting entity values in user input such as date - values. For example, `04/03/2018` might be interpreted either as April 3 or - March 4, depending on the locale. - This property is included only if the new system entities are enabled for - the skill. - :param str reference_time: (optional) The base time for interpreting any - relative time mentions in the user input. The specified time overrides the - current server time, and is used to calculate times mentioned in relative - terms such as `now` or `tomorrow`. This can be useful for simulating past - or future times for testing purposes, or when analyzing documents such as - news articles. - This value must be a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. - """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. + """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - if 'turn_count' in _dict: - args['turn_count'] = _dict.get('turn_count') - if 'locale' in _dict: - args['locale'] = _dict.get('locale') - if 'reference_time' in _dict: - args['reference_time'] = _dict.get('reference_time') - if 'session_start_time' in _dict: - args['session_start_time'] = _dict.get('session_start_time') - if 'state' in _dict: - args['state'] = _dict.get('state') - if 'skip_user_input' in _dict: - args['skip_user_input'] = _dict.get('skip_user_input') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceHandler JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + if (handler := _dict.get('handler')) is not None: + args['handler'] = handler + else: + raise ValueError( + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a LogMessageSourceHandler object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'turn_count') and self.turn_count is not None: - _dict['turn_count'] = self.turn_count - if hasattr(self, 'locale') and self.locale is not None: - _dict['locale'] = self.locale - if hasattr(self, 'reference_time') and self.reference_time is not None: - _dict['reference_time'] = self.reference_time - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler return _dict def _to_dict(self): @@ -2450,94 +18472,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this LogMessageSourceHandler object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, Enum): - """ - The language code for localization in the user input. The specified locale - overrides the default for the assistant, and is used for interpreting entity - values in user input such as date values. For example, `04/03/2018` might be - interpreted either as April 3 or March 4, depending on the locale. - This property is included only if the new system entities are enabled for the - skill. - """ - EN_US = 'en-us' - EN_CA = 'en-ca' - EN_GB = 'en-gb' - AR_AR = 'ar-ar' - CS_CZ = 'cs-cz' - DE_DE = 'de-de' - ES_ES = 'es-es' - FR_FR = 'fr-fr' - IT_IT = 'it-it' - JA_JP = 'ja-jp' - KO_KR = 'ko-kr' - NL_NL = 'nl-nl' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - -class MessageContextSkill(): +class LogMessageSourceStep(LogMessageSource): """ - Contains information specific to a particular skill used by the assistant. The - property name must be the same as the name of the skill (for example, `main skill`). + An object that identifies the dialog element that generated the error message. - :attr dict user_defined: (optional) Arbitrary variables that can be read and - written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by - the skill. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: The unique identifier of the step that generated the error + message. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + def __init__( + self, + type: str, + action: str, + step: str, + ) -> None: """ - Initialize a MessageContextSkill object. + Initialize a LogMessageSourceStep object. - :param dict user_defined: (optional) Arbitrary variables that can be read - and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. """ - self.user_defined = user_defined - self.system = system + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': - """Initialize a MessageContextSkill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceStep JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + else: + raise ValueError( + 'Required property \'step\' not present in LogMessageSourceStep JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkill object from a json dictionary.""" + """Initialize a LogMessageSourceStep object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step return _dict def _to_dict(self): @@ -2545,186 +18564,228 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkill object.""" + """Return a `str` version of this LogMessageSourceStep object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkill') -> bool: + def __eq__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkill') -> bool: + def __ne__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillSystem(): +class MessageOutputDebugTurnEventTurnEventActionFinished( + MessageOutputDebugTurnEvent): """ - System context data used by the skill. - - :attr str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + MessageOutputDebugTurnEventTurnEventActionFinished. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables at + the time the action finished. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - - def __init__(self, *, state: str = None, **kwargs) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + action_variables: Optional[dict] = None, + ) -> None: """ - Initialize a MessageContextSkillSystem object. - - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables + at the time the action finished. """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.action_variables = action_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if 'state' in _dict: - args['state'] = _dict.get('state') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkillSystem') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action finished processing. + """ + + ALL_STEPS_DONE = 'all_steps_done' + NO_STEPS_VISITED = 'no_steps_visited' + ENDED_BY_STEP = 'ended_by_step' + CONNECT_TO_AGENT = 'connect_to_agent' + MAX_RETRIES_REACHED = 'max_retries_reached' + FALLBACK = 'fallback' + -class MessageContextStateless(): +class MessageOutputDebugTurnEventTurnEventActionRoutingDenied( + MessageOutputDebugTurnEvent): """ - MessageContextStateless. + MessageOutputDebugTurnEventTurnEventActionRoutingDenied. - :attr MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :attr object integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. """ - def __init__(self, - *, - global_: 'MessageContextGlobalStateless' = None, - skills: dict = None, - integrations: object = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + ) -> None: """ - Initialize a MessageContextStateless object. + Initialize a MessageOutputDebugTurnEventTurnEventActionRoutingDenied object. - :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': - """Initialize a MessageContextStateless object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied': + """Initialize a MessageOutputDebugTurnEventTurnEventActionRoutingDenied object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextStateless object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionRoutingDenied object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -2732,141 +18793,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextStateless object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionRoutingDenied object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextStateless') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextStateless') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MessageInput(): - """ - An input object that includes the input text. - - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. - """ - - def __init__(self, - *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptions' = None) -> None: - """ - Initialize a MessageInput object. - - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action was visited. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + + ACTION_CONDITIONS_FAILED = 'action_conditions_failed' + + +class MessageOutputDebugTurnEventTurnEventActionVisited( + MessageOutputDebugTurnEvent): + """ + MessageOutputDebugTurnEventTurnEventActionVisited. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the call + to the action is stored. Included only if **reason**=`subaction_return`. + """ + + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + result_variable: Optional[str] = None, + ) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the + call to the action is stored. Included only if + **reason**=`subaction_return`. + """ + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.result_variable = result_variable @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInput': - """Initialize a MessageInput object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptions.from_dict( - _dict.get('options')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInput object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable return _dict def _to_dict(self): @@ -2874,78 +18927,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInput object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInput') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInput') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. + The type of condition (if any) that is defined for the action. """ - TEXT = 'text' - SEARCH = 'search' + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + + INTENT = 'intent' + INVOKE_SUBACTION = 'invoke_subaction' + SUBACTION_RETURN = 'subaction_return' + INVOKE_EXTERNAL = 'invoke_external' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + AGENT_REQUESTED = 'agent_requested' + STEP_VALIDATION_FAILED = 'step_validation_failed' + NO_ACTION_MATCHES = 'no_action_matches' -class MessageInputAttachment(): +class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ - A reference to a media file to be sent as an attachment with the message. + MessageOutputDebugTurnEventTurnEventCallout. - :attr str url: The URL of the media file. - :attr str media_type: (optional) The media content type (such as a MIME type) of - the attachment. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - def __init__(self, url: str, *, media_type: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + callout: Optional['TurnEventCalloutCallout'] = None, + error: Optional['TurnEventCalloutError'] = None, + ) -> None: """ - Initialize a MessageInputAttachment object. + Initialize a MessageOutputDebugTurnEventTurnEventCallout object. - :param str url: The URL of the media file. - :param str media_type: (optional) The media content type (such as a MIME - type) of the attachment. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - self.url = url - self.media_type = media_type + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.callout = callout + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': - """Initialize a MessageInputAttachment object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') - else: - raise ValueError( - 'Required property \'url\' not present in MessageInputAttachment JSON' - ) - if 'media_type' in _dict: - args['media_type'] = _dict.get('media_type') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventCalloutCallout.from_dict(callout) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventCalloutError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputAttachment object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'media_type') and self.media_type is not None: - _dict['media_type'] = self.media_type + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -2953,128 +19048,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputAttachment object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputAttachment') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputAttachment') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptions(): +class MessageOutputDebugTurnEventTurnEventClientActions( + MessageOutputDebugTurnEvent): """ - Optional properties that control how the assistant responds. + MessageOutputDebugTurnEventTurnEventClientActions. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response includes the `context` property. - If you also specify **debug**=`true`, the returned skill context includes the - `system.state` property. - :attr bool export: (optional) Whether to return session context, including full - conversation state. If you specify `true`, the response includes the `context` - property, and the skill context includes the `system.state` property. - **Note:** If **export**=`true`, the context is returned regardless of the value - of **return_context**. + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param List[ClientAction] client_actions: (optional) An array of client actions. """ - def __init__(self, - *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None, - return_context: bool = None, - export: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventStepSource'] = None, + client_actions: Optional[List['ClientAction']] = None, + ) -> None: """ - Initialize a MessageInputOptions object. + Initialize a MessageOutputDebugTurnEventTurnEventClientActions object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :param bool return_context: (optional) Whether to return session context - with the response. If you specify `true`, the response includes the - `context` property. If you also specify **debug**=`true`, the returned - skill context includes the `system.state` property. - :param bool export: (optional) Whether to return session context, including - full conversation state. If you specify `true`, the response includes the - `context` property, and the skill context includes the `system.state` - property. - **Note:** If **export**=`true`, the context is returned regardless of the - value of **return_context**. + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param List[ClientAction] client_actions: (optional) An array of client + actions. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug - self.return_context = return_context - self.export = export + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.client_actions = client_actions @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': - """Initialize a MessageInputOptions object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventClientActions': + """Initialize a MessageOutputDebugTurnEventTurnEventClientActions object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') - if 'return_context' in _dict: - args['return_context'] = _dict.get('return_context') - if 'export' in _dict: - args['export'] = _dict.get('export') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventStepSource.from_dict(source) + if (client_actions := _dict.get('client_actions')) is not None: + args['client_actions'] = [ + ClientAction.from_dict(v) for v in client_actions + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptions object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventClientActions object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug - if hasattr(self, 'return_context') and self.return_context is not None: - _dict['return_context'] = self.return_context - if hasattr(self, 'export') and self.export is not None: - _dict['export'] = self.export + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'client_actions') and self.client_actions is not None: + client_actions_list = [] + for v in self.client_actions: + if isinstance(v, dict): + client_actions_list.append(v) + else: + client_actions_list.append(v.to_dict()) + _dict['client_actions'] = client_actions_list return _dict def _to_dict(self): @@ -3082,86 +19140,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptions object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventClientActions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptions') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventClientActions') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptions') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventClientActions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsSpelling(): +class MessageOutputDebugTurnEventTurnEventConversationalSearchEnd( + MessageOutputDebugTurnEvent): """ - Spelling correction options for the message. Any options specified on an individual - message override the settings configured for the skill. + MessageOutputDebugTurnEventTurnEventConversationalSearchEnd. - :attr bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** is - `true`, any spelling corrections are automatically applied to the user input. If - **auto_correct** is `false`, any suggested corrections are returned in the - **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property in - the workspace settings for the skill. - :attr bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned in - the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the workspace - settings for the skill. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. """ - def __init__(self, - *, - suggestions: bool = None, - auto_correct: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + ) -> None: """ - Initialize a MessageInputOptionsSpelling object. + Initialize a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object. - :param bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** - is `true`, any spelling corrections are automatically applied to the user - input. If **auto_correct** is `false`, any suggested corrections are - returned in the **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property - in the workspace settings for the skill. - :param bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned - in the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the - workspace settings for the skill. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. """ - self.suggestions = suggestions - self.auto_correct = auto_correct + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd': + """Initialize a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object from a json dictionary.""" args = {} - if 'suggestions' in _dict: - args['suggestions'] = _dict.get('suggestions') - if 'auto_correct' in _dict: - args['auto_correct'] = _dict.get('auto_correct') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = self.suggestions - if hasattr(self, 'auto_correct') and self.auto_correct is not None: - _dict['auto_correct'] = self.auto_correct + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type return _dict def _to_dict(self): @@ -3169,95 +19227,131 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsSpelling object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class MessageInputOptionsStateless(): - """ - Optional properties that control how the assistant responds. + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + +class MessageOutputDebugTurnEventTurnEventGenerativeAICalled( + MessageOutputDebugTurnEvent): + """ + MessageOutputDebugTurnEventTurnEventGenerativeAICalled. + + :param str event: (optional) The type of turn event. + :param dict source: (optional) For internal use only. + :param str generative_ai_start_time: (optional) The time when generative ai + started processing the message. + :param GenerativeAITask generative_ai: (optional) + :param TurnEventGenerativeAICalledCallout callout: (optional) + :param TurnEventGenerativeAICalledMetrics metrics: (optional) """ - def __init__(self, - *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional[dict] = None, + generative_ai_start_time: Optional[str] = None, + generative_ai: Optional['GenerativeAITask'] = None, + callout: Optional['TurnEventGenerativeAICalledCallout'] = None, + metrics: Optional['TurnEventGenerativeAICalledMetrics'] = None, + ) -> None: """ - Initialize a MessageInputOptionsStateless object. - - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + Initialize a MessageOutputDebugTurnEventTurnEventGenerativeAICalled object. + + :param str event: (optional) The type of turn event. + :param dict source: (optional) For internal use only. + :param str generative_ai_start_time: (optional) The time when generative ai + started processing the message. + :param GenerativeAITask generative_ai: (optional) + :param TurnEventGenerativeAICalledCallout callout: (optional) + :param TurnEventGenerativeAICalledMetrics metrics: (optional) """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.generative_ai_start_time = generative_ai_start_time + self.generative_ai = generative_ai + self.callout = callout + self.metrics = metrics @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled': + """Initialize a MessageOutputDebugTurnEventTurnEventGenerativeAICalled object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = source + if (generative_ai_start_time := + _dict.get('generative_ai_start_time')) is not None: + args['generative_ai_start_time'] = generative_ai_start_time + if (generative_ai := _dict.get('generative_ai')) is not None: + args['generative_ai'] = GenerativeAITask.from_dict(generative_ai) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventGenerativeAICalledCallout.from_dict( + callout) + if (metrics := _dict.get('metrics')) is not None: + args['metrics'] = TurnEventGenerativeAICalledMetrics.from_dict( + metrics) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventGenerativeAICalled object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'generative_ai_start_time' + ) and self.generative_ai_start_time is not None: + _dict['generative_ai_start_time'] = self.generative_ai_start_time + if hasattr(self, 'generative_ai') and self.generative_ai is not None: + if isinstance(self.generative_ai, dict): + _dict['generative_ai'] = self.generative_ai + else: + _dict['generative_ai'] = self.generative_ai.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'metrics') and self.metrics is not None: + if isinstance(self.metrics, dict): + _dict['metrics'] = self.metrics + else: + _dict['metrics'] = self.metrics.to_dict() return _dict def _to_dict(self): @@ -3265,141 +19359,87 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsStateless object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventGenerativeAICalled object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputStateless(): +class MessageOutputDebugTurnEventTurnEventHandlerVisited( + MessageOutputDebugTurnEvent): """ - An input object that includes the input text. + MessageOutputDebugTurnEventTurnEventHandlerVisited. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptionsStateless options: (optional) Optional properties that - control how the assistant responds. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ - def __init__(self, - *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptionsStateless' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + ) -> None: """ - Initialize a MessageInputStateless object. + Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptionsStateless options: (optional) Optional properties - that control how the assistant responds. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': - """Initialize a MessageInputStateless object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptionsStateless.from_dict( - _dict.get('options')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputStateless object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time return _dict def _to_dict(self): @@ -3407,144 +19447,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputStateless object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputStateless') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputStateless') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - TEXT = 'text' - SEARCH = 'search' - -class MessageOutput(): +class MessageOutputDebugTurnEventTurnEventManualRoute( + MessageOutputDebugTurnEvent): """ - Assistant output to be rendered or processed by the client. - - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :attr dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :attr MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + MessageOutputDebugTurnEventTurnEventManualRoute. + + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str route_name: (optional) The name of the route. """ - def __init__(self, - *, - generic: List['RuntimeResponseGeneric'] = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - actions: List['DialogNodeAction'] = None, - debug: 'MessageOutputDebug' = None, - user_defined: dict = None, - spelling: 'MessageOutputSpelling' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventStepSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + route_name: Optional[str] = None, + ) -> None: """ - Initialize a MessageOutput object. - - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + Initialize a MessageOutputDebugTurnEventTurnEventManualRoute object. + + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str route_name: (optional) The name of the route. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.route_name = route_name @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventManualRoute': + """Initialize a MessageOutputDebugTurnEventTurnEventManualRoute object from a json dictionary.""" args = {} - if 'generic' in _dict: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') - ] - if 'debug' in _dict: - args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling.from_dict( - _dict.get('spelling')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventStepSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (route_name := _dict.get('route_name')) is not None: + args['route_name'] = route_name return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventManualRoute object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'route_name') and self.route_name is not None: + _dict['route_name'] = self.route_name return _dict def _to_dict(self): @@ -3552,97 +19553,93 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventManualRoute object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutput') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventManualRoute') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageOutput') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventManualRoute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + -class MessageOutputDebug(): +class MessageOutputDebugTurnEventTurnEventNodeVisited( + MessageOutputDebugTurnEvent): """ - Additional detailed information about a message response and how it was generated. + MessageOutputDebugTurnEventTurnEventNodeVisited. - :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were - triggered during processing of the input message. - :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ - def __init__(self, - *, - nodes_visited: List['DialogNodeVisited'] = None, - log_messages: List['DialogLogMessage'] = None, - branch_exited: bool = None, - branch_exited_reason: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventNodeSource'] = None, + reason: Optional[str] = None, + ) -> None: """ - Initialize a MessageOutputDebug object. + Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were triggered during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(x) - for x in _dict.get('nodes_visited') - ] - if 'log_messages' in _dict: - args['log_messages'] = [ - DialogLogMessage.from_dict(x) for x in _dict.get('log_messages') - ] - if 'branch_exited' in _dict: - args['branch_exited'] = _dict.get('branch_exited') - if 'branch_exited_reason' in _dict: - args['branch_exited_reason'] = _dict.get('branch_exited_reason') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventNodeSource.from_dict(source) + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: - _dict['nodes_visited'] = [x.to_dict() for x in self.nodes_visited] - if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -3650,90 +19647,97 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputDebug') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageOutputDebug') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(str, Enum): + class ReasonEnum(str, Enum): """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. + The reason the dialog node was visited. """ - COMPLETED = 'completed' - FALLBACK = 'fallback' + WELCOME = 'welcome' + BRANCH_START = 'branch_start' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' + JUMP = 'jump' -class MessageOutputSpelling(): + +class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ - Properties describing any spelling corrections in the user input that was received. + MessageOutputDebugTurnEventTurnEventSearch. - :attr str text: (optional) The user input text that was used to generate the - response. If spelling autocorrection is enabled, this text reflects any spelling - corrections that were applied. - :attr str original_text: (optional) The original user input text. This property - is returned only if autocorrection is enabled and the user input was corrected. - :attr str suggested_text: (optional) Any suggested corrections of the input - text. This property is returned only if spelling correction is enabled and - autocorrection is disabled. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ - def __init__(self, - *, - text: str = None, - original_text: str = None, - suggested_text: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + error: Optional['TurnEventSearchError'] = None, + ) -> None: """ - Initialize a MessageOutputSpelling object. + Initialize a MessageOutputDebugTurnEventTurnEventSearch object. - :param str text: (optional) The user input text that was used to generate - the response. If spelling autocorrection is enabled, this text reflects any - spelling corrections that were applied. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ - self.text = text - self.original_text = original_text - self.suggested_text = suggested_text + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': - """Initialize a MessageOutputSpelling object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventSearchError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputSpelling object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -3741,101 +19745,107 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputSpelling object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputSpelling') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageOutputSpelling') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageRequest(): +class MessageOutputDebugTurnEventTurnEventStepAnswered( + MessageOutputDebugTurnEvent): """ - A stateful message request formatted for the Watson Assistant service. - - :attr MessageInput input: (optional) An input object that includes the input - text. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. + MessageOutputDebugTurnEventTurnEventStepAnswered. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response to a + prompt from the assistant. If this property is `false`, the user provided the + answer without visiting the step. """ - def __init__(self, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + prompted: Optional[bool] = None, + ) -> None: """ - Initialize a MessageRequest object. - - :param MessageInput input: (optional) An input object that includes the - input text. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. + Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response + to a prompt from the assistant. If this property is `false`, the user + provided the answer without visiting the step. """ - self.input = input - self.context = context - self.user_id = user_id + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.prompted = prompted @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageRequest': - """Initialize a MessageRequest object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (prompted := _dict.get('prompted')) is not None: + args['prompted'] = prompted return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageRequest object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'prompted') and self.prompted is not None: + _dict['prompted'] = self.prompted return _dict def _to_dict(self): @@ -3843,107 +19853,116 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageRequest object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageRequest') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageRequest') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class MessageResponse(): - """ - A response from the Watson Assistant service. + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :attr str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + +class MessageOutputDebugTurnEventTurnEventStepVisited( + MessageOutputDebugTurnEvent): + """ + MessageOutputDebugTurnEventTurnEventStepVisited. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ - def __init__(self, - output: 'MessageOutput', - user_id: str, - *, - context: 'MessageContext' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + has_question: Optional[bool] = None, + ) -> None: """ - Initialize a MessageResponse object. - - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. + Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ - self.output = output - self.context = context - self.user_id = user_id + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.has_question = has_question @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponse': - """Initialize a MessageResponse object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponse JSON' - ) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - else: - raise ValueError( - 'Required property \'user_id\' not present in MessageResponse JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (has_question := _dict.get('has_question')) is not None: + args['has_question'] = has_question return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponse object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'has_question') and self.has_question is not None: + _dict['has_question'] = self.has_question return _dict def _to_dict(self): @@ -3951,104 +19970,92 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponse object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponse') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageResponse') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' -class MessageResponseStateless(): + +class MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied( + MessageOutputDebugTurnEvent): """ - A stateless response from the Watson Assistant service. + MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied. - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContextStateless context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param str event: (optional) The type of turn event. + :param List[RuntimeIntent] intents_denied: (optional) An array of denied + intents. """ - def __init__(self, - output: 'MessageOutput', - context: 'MessageContextStateless', - *, - user_id: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + intents_denied: Optional[List['RuntimeIntent']] = None, + ) -> None: """ - Initialize a MessageResponseStateless object. + Initialize a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param MessageContextStateless context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param str event: (optional) The type of turn event. + :param List[RuntimeIntent] intents_denied: (optional) An array of denied + intents. """ - self.output = output - self.context = context - self.user_id = user_id + # pylint: disable=super-init-not-called + self.event = event + self.intents_denied = intents_denied @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': - """Initialize a MessageResponseStateless object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied': + """Initialize a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponseStateless JSON' - ) - if 'context' in _dict: - args['context'] = MessageContextStateless.from_dict( - _dict.get('context')) - else: - raise ValueError( - 'Required property \'context\' not present in MessageResponseStateless JSON' - ) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (intents_denied := _dict.get('intents_denied')) is not None: + args['intents_denied'] = [ + RuntimeIntent.from_dict(v) for v in intents_denied + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponseStateless object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'intents_denied') and self.intents_denied is not None: + intents_denied_list = [] + for v in self.intents_denied: + if isinstance(v, dict): + intents_denied_list.append(v) + else: + intents_denied_list.append(v.to_dict()) + _dict['intents_denied'] = intents_denied_list return _dict def _to_dict(self): @@ -4056,54 +20063,96 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponseStateless object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponseStateless') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageResponseStateless') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ResponseGenericChannel(): +class MessageOutputDebugTurnEventTurnEventTopicSwitchDenied( + MessageOutputDebugTurnEvent): """ - ResponseGenericChannel. + MessageOutputDebugTurnEventTurnEventTopicSwitchDenied. - :attr str channel: (optional) A channel for which the response is intended. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + ) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object. - :param str channel: (optional) A channel for which the response is - intended. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. """ - self.channel = channel + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied': + """Initialize a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -4111,161 +20160,85 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ResponseGenericChannel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class RuntimeEntity(): - """ - The entity value that was recognized in the user input. - - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity - value. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for - the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object - containing detailed information about the entity recognized in the user input. - This property is included only if the new system entities are enabled for the - skill. - For more information about how the new system entities are interpreted, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of - possible alternative values that the user might have intended instead of the - value returned in the **value** property. This property is returned only for - `@sys-time` and `@sys-date` entities when the user's input is ambiguous. - This property is included only if the new system entities are enabled for the - skill. - :attr RuntimeEntityRole role: (optional) An object describing the role played by - a system entity that is specifies the beginning or end of a range recognized in - the user input. This property is included only if the new system entities are - enabled for the skill. - """ - - def __init__(self, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None) -> None: - """ - Initialize a RuntimeEntity object. - - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. - :param List[CaptureGroup] groups: (optional) The recognized capture groups - for the entity, as defined by the entity pattern. - :param RuntimeEntityInterpretation interpretation: (optional) An object - containing detailed information about the entity recognized in the user - input. This property is included only if the new system entities are - enabled for the skill. - For more information about how the new system entities are interpreted, see - the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :param List[RuntimeEntityAlternative] alternatives: (optional) An array of - possible alternative values that the user might have intended instead of - the value returned in the **value** property. This property is returned - only for `@sys-time` and `@sys-date` entities when the user's input is - ambiguous. - This property is included only if the new system entities are enabled for - the skill. - :param RuntimeEntityRole role: (optional) An object describing the role - played by a system entity that is specifies the beginning or end of a range - recognized in the user input. This property is included only if the new - system entities are enabled for the skill. + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ConditionTypeEnum(str, Enum): """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + + ACTION_CONDITIONS_FAILED = 'action_conditions_failed' + + +class MessageStreamResponseMessageStreamCompleteItem(MessageStreamResponse): + """ + A completed response item. A complete item is a composition of every streamed partial + item with the same streaming_metadata.id, and each complete item contains its own + unique streaming_metadata.id. + + :param CompleteItem complete_item: (optional) + """ + + def __init__( + self, + *, + complete_item: Optional['CompleteItem'] = None, + ) -> None: + """ + Initialize a MessageStreamResponseMessageStreamCompleteItem object. + + :param CompleteItem complete_item: (optional) + """ + # pylint: disable=super-init-not-called + self.complete_item = complete_item @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageStreamResponseMessageStreamCompleteItem': + """Initialize a MessageStreamResponseMessageStreamCompleteItem object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') - else: - raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' - ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') - else: - raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(x) for x in _dict.get('groups') - ] - if 'interpretation' in _dict: - args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: - args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(x) - for x in _dict.get('alternatives') - ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if (complete_item := _dict.get('complete_item')) is not None: + args['complete_item'] = CompleteItem.from_dict(complete_item) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a MessageStreamResponseMessageStreamCompleteItem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x.to_dict() for x in self.groups] - if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] - if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role.to_dict() + if hasattr(self, 'complete_item') and self.complete_item is not None: + if isinstance(self.complete_item, dict): + _dict['complete_item'] = self.complete_item + else: + _dict['complete_item'] = self.complete_item.to_dict() return _dict def _to_dict(self): @@ -4273,64 +20246,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this MessageStreamResponseMessageStreamCompleteItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, + other: 'MessageStreamResponseMessageStreamCompleteItem') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntity') -> bool: + def __ne__(self, + other: 'MessageStreamResponseMessageStreamCompleteItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative(): +class MessageStreamResponseMessageStreamPartialItem(MessageStreamResponse): """ - An alternative value for the recognized entity. + A chunk of the streamed message response. - :attr str value: (optional) The entity value that was recognized in the user - input. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. + :param PartialItem partial_item: (optional) Message response partial item + content. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__( + self, + *, + partial_item: Optional['PartialItem'] = None, + ) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a MessageStreamResponseMessageStreamPartialItem object. - :param str value: (optional) The entity value that was recognized in the - user input. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + :param PartialItem partial_item: (optional) Message response partial item + content. """ - self.value = value - self.confidence = confidence + # pylint: disable=super-init-not-called + self.partial_item = partial_item @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageStreamResponseMessageStreamPartialItem': + """Initialize a MessageStreamResponseMessageStreamPartialItem object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (partial_item := _dict.get('partial_item')) is not None: + args['partial_item'] = PartialItem.from_dict(partial_item) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a MessageStreamResponseMessageStreamPartialItem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'partial_item') and self.partial_item is not None: + if isinstance(self.partial_item, dict): + _dict['partial_item'] = self.partial_item + else: + _dict['partial_item'] = self.partial_item.to_dict() return _dict def _to_dict(self): @@ -4338,351 +20314,183 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this MessageStreamResponseMessageStreamPartialItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__(self, + other: 'MessageStreamResponseMessageStreamPartialItem') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + def __ne__(self, + other: 'MessageStreamResponseMessageStreamPartialItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityInterpretation(): +class MessageStreamResponseStatefulMessageStreamFinalResponse( + MessageStreamResponse): """ - RuntimeEntityInterpretation. + The final and stateful message response. - :attr str calendar_type: (optional) The calendar used to represent a recognized - date (for example, `Gregorian`). - :attr str datetime_link: (optional) A unique identifier used to associate a - recognized time and date. If the user input contains a date and time that are - mentioned together (for example, `Today at 5`, the same **datetime_link** value - is returned for both the `@sys-date` and `@sys-time` entities). - :attr str festival: (optional) A locale-specific holiday name (such as - `thanksgiving` or `christmas`). This property is included when a `@sys-date` - entity is recognized based on a holiday name in the user input. - :attr str granularity: (optional) The precision or duration of a time range - specified by a recognized `@sys-time` or `@sys-date` entity. - :attr str range_link: (optional) A unique identifier used to associate multiple - recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are - recognized as a range of values in the user's input (for example, `from July 4 - until July 14` or `from 20 to 25`). - :attr str range_modifier: (optional) The word in the user input that indicates - that a `sys-date` or `sys-time` entity is part of an implied range where only - one date or time is specified (for example, `since` or `until`). - :attr float relative_day: (optional) A recognized mention of a relative day, - represented numerically as an offset from the current date (for example, `-1` - for `yesterday` or `10` for `in ten days`). - :attr float relative_month: (optional) A recognized mention of a relative month, - represented numerically as an offset from the current month (for example, `1` - for `next month` or `-3` for `three months ago`). - :attr float relative_week: (optional) A recognized mention of a relative week, - represented numerically as an offset from the current week (for example, `2` for - `in two weeks` or `-1` for `last week). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current - weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). - :attr float relative_year: (optional) A recognized mention of a relative year, - represented numerically as an offset from the current year (for example, `1` for - `next year` or `-5` for `five years ago`). - :attr float specific_day: (optional) A recognized mention of a specific date, - represented numerically as the date within the month (for example, `30` for - `June 30`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific - day of the week as a lowercase string (for example, `monday`). - :attr float specific_month: (optional) A recognized mention of a specific month, - represented numerically (for example, `7` for `July`). - :attr float specific_quarter: (optional) A recognized mention of a specific - quarter, represented numerically (for example, `3` for `the third quarter`). - :attr float specific_year: (optional) A recognized mention of a specific year - (for example, `2016`). - :attr float numeric_value: (optional) A recognized numeric value, represented as - an integer or double. - :attr str subtype: (optional) The type of numeric value recognized in the user - input (`integer` or `rational`). - :attr str part_of_day: (optional) A recognized term for a time that was - mentioned as a part of the day in the user's input (for example, `morning` or - `afternoon`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, - represented numerically as an offset from the current hour (for example, `3` for - `in three hours` or `-1` for `an hour ago`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for - example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for - example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as - part of a time value (for example, `10` for `10:15 AM`.). - :attr float specific_minute: (optional) A recognized specific minute mentioned - as part of a time value (for example, `15` for `10:15 AM`.). - :attr float specific_second: (optional) A recognized specific second mentioned - as part of a time value (for example, `30` for `10:15:30 AM`.). - :attr str timezone: (optional) A recognized time zone mentioned as part of a - time value (for example, `EST`). + :param FinalResponse final_response: (optional) Message final response content. """ - def __init__(self, - *, - calendar_type: str = None, - datetime_link: str = None, - festival: str = None, - granularity: str = None, - range_link: str = None, - range_modifier: str = None, - relative_day: float = None, - relative_month: float = None, - relative_week: float = None, - relative_weekend: float = None, - relative_year: float = None, - specific_day: float = None, - specific_day_of_week: str = None, - specific_month: float = None, - specific_quarter: float = None, - specific_year: float = None, - numeric_value: float = None, - subtype: str = None, - part_of_day: str = None, - relative_hour: float = None, - relative_minute: float = None, - relative_second: float = None, - specific_hour: float = None, - specific_minute: float = None, - specific_second: float = None, - timezone: str = None) -> None: + def __init__( + self, + *, + final_response: Optional['FinalResponse'] = None, + ) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a MessageStreamResponseStatefulMessageStreamFinalResponse object. - :param str calendar_type: (optional) The calendar used to represent a - recognized date (for example, `Gregorian`). - :param str datetime_link: (optional) A unique identifier used to associate - a recognized time and date. If the user input contains a date and time that - are mentioned together (for example, `Today at 5`, the same - **datetime_link** value is returned for both the `@sys-date` and - `@sys-time` entities). - :param str festival: (optional) A locale-specific holiday name (such as - `thanksgiving` or `christmas`). This property is included when a - `@sys-date` entity is recognized based on a holiday name in the user input. - :param str granularity: (optional) The precision or duration of a time - range specified by a recognized `@sys-time` or `@sys-date` entity. - :param str range_link: (optional) A unique identifier used to associate - multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities - that are recognized as a range of values in the user's input (for example, - `from July 4 until July 14` or `from 20 to 25`). - :param str range_modifier: (optional) The word in the user input that - indicates that a `sys-date` or `sys-time` entity is part of an implied - range where only one date or time is specified (for example, `since` or - `until`). - :param float relative_day: (optional) A recognized mention of a relative - day, represented numerically as an offset from the current date (for - example, `-1` for `yesterday` or `10` for `in ten days`). - :param float relative_month: (optional) A recognized mention of a relative - month, represented numerically as an offset from the current month (for - example, `1` for `next month` or `-3` for `three months ago`). - :param float relative_week: (optional) A recognized mention of a relative - week, represented numerically as an offset from the current week (for - example, `2` for `in two weeks` or `-1` for `last week). - :param float relative_weekend: (optional) A recognized mention of a - relative date range for a weekend, represented numerically as an offset - from the current weekend (for example, `0` for `this weekend` or `-1` for - `last weekend`). - :param float relative_year: (optional) A recognized mention of a relative - year, represented numerically as an offset from the current year (for - example, `1` for `next year` or `-5` for `five years ago`). - :param float specific_day: (optional) A recognized mention of a specific - date, represented numerically as the date within the month (for example, - `30` for `June 30`.). - :param str specific_day_of_week: (optional) A recognized mention of a - specific day of the week as a lowercase string (for example, `monday`). - :param float specific_month: (optional) A recognized mention of a specific - month, represented numerically (for example, `7` for `July`). - :param float specific_quarter: (optional) A recognized mention of a - specific quarter, represented numerically (for example, `3` for `the third - quarter`). - :param float specific_year: (optional) A recognized mention of a specific - year (for example, `2016`). - :param float numeric_value: (optional) A recognized numeric value, - represented as an integer or double. - :param str subtype: (optional) The type of numeric value recognized in the - user input (`integer` or `rational`). - :param str part_of_day: (optional) A recognized term for a time that was - mentioned as a part of the day in the user's input (for example, `morning` - or `afternoon`). - :param float relative_hour: (optional) A recognized mention of a relative - hour, represented numerically as an offset from the current hour (for - example, `3` for `in three hours` or `-1` for `an hour ago`). - :param float relative_minute: (optional) A recognized mention of a relative - time, represented numerically as an offset in minutes from the current time - (for example, `5` for `in five minutes` or `-15` for `fifteen minutes - ago`). - :param float relative_second: (optional) A recognized mention of a relative - time, represented numerically as an offset in seconds from the current time - (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :param float specific_hour: (optional) A recognized specific hour mentioned - as part of a time value (for example, `10` for `10:15 AM`.). - :param float specific_minute: (optional) A recognized specific minute - mentioned as part of a time value (for example, `15` for `10:15 AM`.). - :param float specific_second: (optional) A recognized specific second - mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - :param str timezone: (optional) A recognized time zone mentioned as part of - a time value (for example, `EST`). + :param FinalResponse final_response: (optional) Message final response + content. """ - self.calendar_type = calendar_type - self.datetime_link = datetime_link - self.festival = festival - self.granularity = granularity - self.range_link = range_link - self.range_modifier = range_modifier - self.relative_day = relative_day - self.relative_month = relative_month - self.relative_week = relative_week - self.relative_weekend = relative_weekend - self.relative_year = relative_year - self.specific_day = specific_day - self.specific_day_of_week = specific_day_of_week - self.specific_month = specific_month - self.specific_quarter = specific_quarter - self.specific_year = specific_year - self.numeric_value = numeric_value - self.subtype = subtype - self.part_of_day = part_of_day - self.relative_hour = relative_hour - self.relative_minute = relative_minute - self.relative_second = relative_second - self.specific_hour = specific_hour - self.specific_minute = specific_minute - self.specific_second = specific_second - self.timezone = timezone + # pylint: disable=super-init-not-called + self.final_response = final_response + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'MessageStreamResponseStatefulMessageStreamFinalResponse': + """Initialize a MessageStreamResponseStatefulMessageStreamFinalResponse object from a json dictionary.""" + args = {} + if (final_response := _dict.get('final_response')) is not None: + args['final_response'] = FinalResponse.from_dict(final_response) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageStreamResponseStatefulMessageStreamFinalResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'final_response') and self.final_response is not None: + if isinstance(self.final_response, dict): + _dict['final_response'] = self.final_response + else: + _dict['final_response'] = self.final_response.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageStreamResponseStatefulMessageStreamFinalResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'MessageStreamResponseStatefulMessageStreamFinalResponse' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'MessageStreamResponseStatefulMessageStreamFinalResponse' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode( + ProviderAuthenticationOAuth2Flows): + """ + Non-private authentication settings for authorization-code flow. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param str authorization_url: (optional) The authorization URL. + :param str redirect_uri: (optional) The redirect URI. + """ + + def __init__( + self, + *, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + authorization_url: Optional[str] = None, + redirect_uri: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param str authorization_url: (optional) The authorization URL. + :param str redirect_uri: (optional) The redirect URI. + """ + # pylint: disable=super-init-not-called + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix + self.authorization_url = authorization_url + self.redirect_uri = redirect_uri @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" args = {} - if 'calendar_type' in _dict: - args['calendar_type'] = _dict.get('calendar_type') - if 'datetime_link' in _dict: - args['datetime_link'] = _dict.get('datetime_link') - if 'festival' in _dict: - args['festival'] = _dict.get('festival') - if 'granularity' in _dict: - args['granularity'] = _dict.get('granularity') - if 'range_link' in _dict: - args['range_link'] = _dict.get('range_link') - if 'range_modifier' in _dict: - args['range_modifier'] = _dict.get('range_modifier') - if 'relative_day' in _dict: - args['relative_day'] = _dict.get('relative_day') - if 'relative_month' in _dict: - args['relative_month'] = _dict.get('relative_month') - if 'relative_week' in _dict: - args['relative_week'] = _dict.get('relative_week') - if 'relative_weekend' in _dict: - args['relative_weekend'] = _dict.get('relative_weekend') - if 'relative_year' in _dict: - args['relative_year'] = _dict.get('relative_year') - if 'specific_day' in _dict: - args['specific_day'] = _dict.get('specific_day') - if 'specific_day_of_week' in _dict: - args['specific_day_of_week'] = _dict.get('specific_day_of_week') - if 'specific_month' in _dict: - args['specific_month'] = _dict.get('specific_month') - if 'specific_quarter' in _dict: - args['specific_quarter'] = _dict.get('specific_quarter') - if 'specific_year' in _dict: - args['specific_year'] = _dict.get('specific_year') - if 'numeric_value' in _dict: - args['numeric_value'] = _dict.get('numeric_value') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') - if 'part_of_day' in _dict: - args['part_of_day'] = _dict.get('part_of_day') - if 'relative_hour' in _dict: - args['relative_hour'] = _dict.get('relative_hour') - if 'relative_minute' in _dict: - args['relative_minute'] = _dict.get('relative_minute') - if 'relative_second' in _dict: - args['relative_second'] = _dict.get('relative_second') - if 'specific_hour' in _dict: - args['specific_hour'] = _dict.get('specific_hour') - if 'specific_minute' in _dict: - args['specific_minute'] = _dict.get('specific_minute') - if 'specific_second' in _dict: - args['specific_second'] = _dict.get('specific_second') - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix + if (authorization_url := _dict.get('authorization_url')) is not None: + args['authorization_url'] = authorization_url + if (redirect_uri := _dict.get('redirect_uri')) is not None: + args['redirect_uri'] = redirect_uri return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'calendar_type') and self.calendar_type is not None: - _dict['calendar_type'] = self.calendar_type - if hasattr(self, 'datetime_link') and self.datetime_link is not None: - _dict['datetime_link'] = self.datetime_link - if hasattr(self, 'festival') and self.festival is not None: - _dict['festival'] = self.festival - if hasattr(self, 'granularity') and self.granularity is not None: - _dict['granularity'] = self.granularity - if hasattr(self, 'range_link') and self.range_link is not None: - _dict['range_link'] = self.range_link - if hasattr(self, 'range_modifier') and self.range_modifier is not None: - _dict['range_modifier'] = self.range_modifier - if hasattr(self, 'relative_day') and self.relative_day is not None: - _dict['relative_day'] = self.relative_day - if hasattr(self, 'relative_month') and self.relative_month is not None: - _dict['relative_month'] = self.relative_month - if hasattr(self, 'relative_week') and self.relative_week is not None: - _dict['relative_week'] = self.relative_week - if hasattr(self, - 'relative_weekend') and self.relative_weekend is not None: - _dict['relative_weekend'] = self.relative_weekend - if hasattr(self, 'relative_year') and self.relative_year is not None: - _dict['relative_year'] = self.relative_year - if hasattr(self, 'specific_day') and self.specific_day is not None: - _dict['specific_day'] = self.specific_day - if hasattr(self, 'specific_day_of_week' - ) and self.specific_day_of_week is not None: - _dict['specific_day_of_week'] = self.specific_day_of_week - if hasattr(self, 'specific_month') and self.specific_month is not None: - _dict['specific_month'] = self.specific_month - if hasattr(self, - 'specific_quarter') and self.specific_quarter is not None: - _dict['specific_quarter'] = self.specific_quarter - if hasattr(self, 'specific_year') and self.specific_year is not None: - _dict['specific_year'] = self.specific_year - if hasattr(self, 'numeric_value') and self.numeric_value is not None: - _dict['numeric_value'] = self.numeric_value - if hasattr(self, 'subtype') and self.subtype is not None: - _dict['subtype'] = self.subtype - if hasattr(self, 'part_of_day') and self.part_of_day is not None: - _dict['part_of_day'] = self.part_of_day - if hasattr(self, 'relative_hour') and self.relative_hour is not None: - _dict['relative_hour'] = self.relative_hour - if hasattr(self, - 'relative_minute') and self.relative_minute is not None: - _dict['relative_minute'] = self.relative_minute + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url if hasattr(self, - 'relative_second') and self.relative_second is not None: - _dict['relative_second'] = self.relative_second - if hasattr(self, 'specific_hour') and self.specific_hour is not None: - _dict['specific_hour'] = self.specific_hour + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix if hasattr(self, - 'specific_minute') and self.specific_minute is not None: - _dict['specific_minute'] = self.specific_minute - if hasattr(self, - 'specific_second') and self.specific_second is not None: - _dict['specific_second'] = self.specific_second - if hasattr(self, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone + 'authorization_url') and self.authorization_url is not None: + _dict['authorization_url'] = self.authorization_url + if hasattr(self, 'redirect_uri') and self.redirect_uri is not None: + _dict['redirect_uri'] = self.redirect_uri return _dict def _to_dict(self): @@ -4690,72 +20498,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __ne__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, Enum): + class ClientAuthTypeEnum(str, Enum): """ - The precision or duration of a time range specified by a recognized `@sys-time` or - `@sys-date` entity. + The client authorization type. """ - DAY = 'day' - FORTNIGHT = 'fortnight' - HOUR = 'hour' - INSTANT = 'instant' - MINUTE = 'minute' - MONTH = 'month' - QUARTER = 'quarter' - SECOND = 'second' - WEEK = 'week' - WEEKEND = 'weekend' - YEAR = 'year' + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' -class RuntimeEntityRole(): + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials( + ProviderAuthenticationOAuth2Flows): """ - An object describing the role played by a system entity that is specifies the - beginning or end of a range recognized in the user input. This property is included - only if the new system entities are enabled for the skill. + ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials. - :attr str type: (optional) The relationship of the entity to the range. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. """ - def __init__(self, *, type: str = None) -> None: + def __init__( + self, + *, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + ) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object. - :param str type: (optional) The relationship of the entity to the range. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. """ - self.type = type + # pylint: disable=super-init-not-called + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix return _dict def _to_dict(self): @@ -4763,81 +20607,269 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityRole') -> bool: + def __ne__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class ClientAuthTypeEnum(str, Enum): """ - The relationship of the entity to the range. + The client authorization type. """ - DATE_FROM = 'date_from' - DATE_TO = 'date_to' - NUMBER_FROM = 'number_from' - NUMBER_TO = 'number_to' - TIME_FROM = 'time_from' - TIME_TO = 'time_to' + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' -class RuntimeIntent(): + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password( + ProviderAuthenticationOAuth2Flows): """ - An intent identified in the user input. + Non-private authentication settings for resource owner password flow. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param ProviderAuthenticationOAuth2PasswordUsername username: (optional) The + username for oauth2 authentication when the preferred flow is "password". + """ + + def __init__( + self, + *, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + username: Optional[ + 'ProviderAuthenticationOAuth2PasswordUsername'] = None, + ) -> None: + """ + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param ProviderAuthenticationOAuth2PasswordUsername username: (optional) + The username for oauth2 authentication when the preferred flow is + "password". + """ + # pylint: disable=super-init-not-called + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object from a json dictionary.""" + args = {} + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix + if (username := _dict.get('username')) is not None: + args[ + 'username'] = ProviderAuthenticationOAuth2PasswordUsername.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ClientAuthTypeEnum(str, Enum): + """ + The client authorization type. + """ + + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' + + +class ProviderPrivateAuthenticationBasicFlow(ProviderPrivateAuthentication): + """ + The private data for basic authentication. + + :param ProviderAuthenticationTypeAndValue password: (optional) The password for + bearer authentication. + """ + + def __init__( + self, + *, + password: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderPrivateAuthenticationBasicFlow object. + + :param ProviderAuthenticationTypeAndValue password: (optional) The password + for bearer authentication. + """ + # pylint: disable=super-init-not-called + self.password = password + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderPrivateAuthenticationBasicFlow': + """Initialize a ProviderPrivateAuthenticationBasicFlow object from a json dictionary.""" + args = {} + if (password := _dict.get('password')) is not None: + args['password'] = ProviderAuthenticationTypeAndValue.from_dict( + password) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderPrivateAuthenticationBasicFlow object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'password') and self.password is not None: + if isinstance(self.password, dict): + _dict['password'] = self.password + else: + _dict['password'] = self.password.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ProviderPrivateAuthenticationBasicFlow object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderPrivateAuthenticationBasicFlow') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderPrivateAuthenticationBasicFlow') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderPrivateAuthenticationBearerFlow(ProviderPrivateAuthentication): + """ + The private data for bearer authentication. - :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :param ProviderAuthenticationTypeAndValue token: (optional) The token for bearer + authentication. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__( + self, + *, + token: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: """ - Initialize a RuntimeIntent object. + Initialize a ProviderPrivateAuthenticationBearerFlow object. - :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param ProviderAuthenticationTypeAndValue token: (optional) The token for + bearer authentication. """ - self.intent = intent - self.confidence = confidence + # pylint: disable=super-init-not-called + self.token = token @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderPrivateAuthenticationBearerFlow': + """Initialize a ProviderPrivateAuthenticationBearerFlow object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') - else: - raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' - ) + if (token := _dict.get('token')) is not None: + args['token'] = ProviderAuthenticationTypeAndValue.from_dict(token) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationBearerFlow object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'token') and self.token is not None: + if isinstance(self.token, dict): + _dict['token'] = self.token + else: + _dict['token'] = self.token.to_dict() return _dict def _to_dict(self): @@ -4845,240 +20877,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this ProviderPrivateAuthenticationBearerFlow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationBearerFlow') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationBearerFlow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGeneric(): - """ - RuntimeResponseGeneric. - - """ - - def __init__(self) -> None: - """ - Initialize a RuntimeResponseGeneric object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class SearchResult(): +class ProviderPrivateAuthenticationOAuth2Flow(ProviderPrivateAuthentication): """ - SearchResult. + The private data for oauth2 authentication. - :attr str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :attr SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the - search skill configuration. - :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :attr List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Note:** This property uses the answer finding beta feature, and is available - only if the search skill is connected to a Discovery v2 service instance. + :param ProviderPrivateAuthenticationOAuth2FlowFlows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. """ - def __init__(self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: str = None, - title: str = None, - url: str = None, - highlight: 'SearchResultHighlight' = None, - answers: List['SearchResultAnswer'] = None) -> None: + def __init__( + self, + *, + flows: Optional['ProviderPrivateAuthenticationOAuth2FlowFlows'] = None, + ) -> None: """ - Initialize a SearchResult object. + Initialize a ProviderPrivateAuthenticationOAuth2Flow object. - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Note:** This property uses the answer finding beta feature, and is - available only if the search skill is connected to a Discovery v2 service - instance. + :param ProviderPrivateAuthenticationOAuth2FlowFlows flows: (optional) + Scenarios performed by the API client to fetch an access token from the + authorization server. """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers + # pylint: disable=super-init-not-called + self.flows = flows @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderPrivateAuthenticationOAuth2Flow': + """Initialize a ProviderPrivateAuthenticationOAuth2Flow object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - else: - raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if 'result_metadata' in _dict: - args['result_metadata'] = SearchResultMetadata.from_dict( - _dict.get('result_metadata')) - else: - raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' - ) - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight.from_dict( - _dict.get('highlight')) - if 'answers' in _dict: - args['answers'] = [ - SearchResultAnswer.from_dict(x) for x in _dict.get('answers') - ] + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2Flow object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows + else: + _dict['flows'] = self.flows.to_dict() return _dict def _to_dict(self): @@ -5086,71 +20944,95 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2Flow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationOAuth2Flow') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResult') -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationOAuth2Flow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer(): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + Private authentication settings for client credentials flow. - :attr str text: The text of the answer. - :attr float confidence: The confidence score for the answer, as returned by the - Discovery service. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param str authorization_code: (optional) The authorization code. """ - def __init__(self, text: str, confidence: float) -> None: + def __init__( + self, + *, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + authorization_code: Optional[str] = None, + ) -> None: """ - Initialize a SearchResultAnswer object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param str authorization_code: (optional) The authorization code. """ - self.text = text - self.confidence = confidence + # pylint: disable=super-init-not-called + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token + self.authorization_code = authorization_code @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' - ) + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token + if (authorization_code := _dict.get('authorization_code')) is not None: + args['authorization_code'] = authorization_code return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token + if hasattr( + self, + 'authorization_code') and self.authorization_code is not None: + _dict['authorization_code'] = self.authorization_code return _dict def _to_dict(self): @@ -5158,191 +21040,200 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultAnswer') -> bool: + def __ne__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultHighlight(): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. + ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials. - :attr List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :attr List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :attr List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. """ - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) - - def __init__(self, - *, - body: List[str] = None, - title: List[str] = None, - url: List[str] = None, - **kwargs) -> None: + def __init__( + self, + *, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + ) -> None: """ - Initialize a SearchResultHighlight object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object. - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param **kwargs: (optional) Any additional properties. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + # pylint: disable=super-init-not-called + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultHighlight') -> bool: + def __ne__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultMetadata(): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - An object containing search result metadata from the Discovery service. - - :attr float confidence: (optional) The confidence score for the given result, as - returned by the Discovery service. - :attr float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + Private authentication settings for resource owner password flow. + + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param ProviderPrivateAuthenticationOAuth2PasswordPassword password: (optional) + The password for oauth2 authentication when the preferred flow is "password". """ - def __init__(self, - *, - confidence: float = None, - score: float = None) -> None: - """ - Initialize a SearchResultMetadata object. - - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + def __init__( + self, + *, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + password: Optional[ + 'ProviderPrivateAuthenticationOAuth2PasswordPassword'] = None, + ) -> None: """ - self.confidence = confidence - self.score = score + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object. + + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param ProviderPrivateAuthenticationOAuth2PasswordPassword password: + (optional) The password for oauth2 authentication when the preferred flow + is "password". + """ + # pylint: disable=super-init-not-called + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token + self.password = password @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token + if (password := _dict.get('password')) is not None: + args[ + 'password'] = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict( + password) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token + if hasattr(self, 'password') and self.password is not None: + if isinstance(self.password, dict): + _dict['password'] = self.password + else: + _dict['password'] = self.password.to_dict() return _dict def _to_dict(self): @@ -5350,57 +21241,146 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultMetadata') -> bool: + def __ne__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SessionResponse(): +class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ - SessionResponse. + RuntimeResponseGenericRuntimeResponseTypeAudio. - :attr str session_id: The session ID. + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before the + response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the audio player cannot be seen. """ - def __init__(self, session_id: str) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ - Initialize a SessionResponse object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. - :param str session_id: The session ID. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the audio player cannot be seen. """ - self.session_id = session_id + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' + ) + if (source := _dict.get('source')) is not None: + args['source'] = source + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: + args['channels'] = [ + ResponseGenericChannel.from_dict(v) for v in channels + ] + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SessionResponse object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): @@ -5408,73 +21388,128 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SessionResponse object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeAudio object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SessionResponse') -> bool: + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceAction(LogMessageSource): +class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( + RuntimeResponseGeneric): """ - An object that identifies the dialog element that generated the error message. + RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. + :param str message_to_user: The message to display to the user when initiating a + channel transfer. + :param ChannelTransferInfo transfer_info: Information used by an integration to + transfer the conversation to a different channel. + :param List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, type: str, action: str) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ - Initialize a LogMessageSourceAction object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. + :param str message_to_user: The message to display to the user when + initiating a channel transfer. + :param ChannelTransferInfo transfer_info: Information used by an + integration to transfer the conversation to a different channel. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action + self.response_type = response_type + self.message_to_user = message_to_user + self.transfer_info = transfer_info + self.channels = channels @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': - """Initialize a LogMessageSourceAction object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'type\' not present in LogMessageSourceAction JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( - 'Required property \'action\' not present in LogMessageSourceAction JSON' + 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) + else: + raise ValueError( + 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if (channels := _dict.get('channels')) is not None: + args['channels'] = [ + ResponseGenericChannel.from_dict(v) for v in channels + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceAction object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'message_to_user') and self.message_to_user is not None: + _dict['message_to_user'] = self.message_to_user + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'channels') and self.channels is not None: + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -5482,73 +21517,170 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceAction object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceAction') -> bool: + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceAction') -> bool: + def __ne__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceDialogNode(LogMessageSource): +class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( + RuntimeResponseGeneric): """ - An object that identifies the dialog element that generated the error message. + RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str dialog_node: The unique identifier of the dialog node that generated - the error message. + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :param str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. + :param AgentAvailabilityMessage agent_available: (optional) An optional message + to be displayed to the user to indicate that the conversation will be + transferred to the next available agent. + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. + :param str topic: (optional) A label identifying the topic of the conversation, + derived from the **title** property of the relevant node or the **topic** + property of the dialog node response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, type: str, dialog_node: str) -> None: + def __init__( + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + topic: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ - Initialize a LogMessageSourceDialogNode object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that - generated the error message. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_human_agent: (optional) A message to be sent to the + human agent who will be taking over the conversation. + :param AgentAvailabilityMessage agent_available: (optional) An optional + message to be displayed to the user to indicate that the conversation will + be transferred to the next available agent. + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. + :param str topic: (optional) A label identifying the topic of the + conversation, derived from the **title** property of the relevant node or + the **topic** property of the dialog node response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called - self.type = type - self.dialog_node = dialog_node + self.response_type = response_type + self.message_to_human_agent = message_to_human_agent + self.agent_available = agent_available + self.agent_unavailable = agent_unavailable + self.transfer_info = transfer_info + self.topic = topic + self.channels = channels @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' - ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: + args['agent_available'] = AgentAvailabilityMessage.from_dict( + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: + args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: + args[ + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( + transfer_info) + if (topic := _dict.get('topic')) is not None: + args['topic'] = topic + if (channels := _dict.get('channels')) is not None: + args['channels'] = [ + ResponseGenericChannel.from_dict(v) for v in channels + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, + 'agent_available') and self.agent_available is not None: + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() + if hasattr(self, + 'agent_unavailable') and self.agent_unavailable is not None: + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'topic') and self.topic is not None: + _dict['topic'] = self.topic + if hasattr(self, 'channels') and self.channels is not None: + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -5556,187 +21688,199 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceDialogNode object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __ne__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceHandler(LogMessageSource): +class RuntimeResponseGenericRuntimeResponseTypeConversationalSearch( + RuntimeResponseGeneric): """ - An object that identifies the dialog element that generated the error message. + RuntimeResponseGenericRuntimeResponseTypeConversationalSearch. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. - :attr str step: (optional) The unique identifier of the step that generated the - error message. - :attr str handler: The unique identifier of the handler that generated the error - message. + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :param str text: The text of the conversational search response. + :param str citations_title: The title of the citations. The default is “How do + we know?”. It can be updated in the conversational search user interface. + :param List[ResponseGenericCitation] citations: The citations for the generated + response. + :param ResponseGenericConfidenceScores confidence_scores: The confidence scores + for determining whether to show the generated response or an “I don't know” + response. + :param str response_length_option: The response length option. It is used to + control the length of the generated response. It is configured either in the + user interface or through the Update skill API. For more information, see + [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#tuning-the-generated-response-length-in-conversational-search). + :param List[SearchResults] search_results: An array of objects containing the + search results. + :param str disclaimer: A disclaimer for the conversational search response. """ - def __init__(self, - type: str, - action: str, - handler: str, - *, - step: str = None) -> None: + def __init__( + self, + response_type: str, + text: str, + citations_title: str, + citations: List['ResponseGenericCitation'], + confidence_scores: 'ResponseGenericConfidenceScores', + response_length_option: str, + search_results: List['SearchResults'], + disclaimer: str, + ) -> None: """ - Initialize a LogMessageSourceHandler object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. - :param str step: (optional) The unique identifier of the step that - generated the error message. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str text: The text of the conversational search response. + :param str citations_title: The title of the citations. The default is “How + do we know?”. It can be updated in the conversational search user + interface. + :param List[ResponseGenericCitation] citations: The citations for the + generated response. + :param ResponseGenericConfidenceScores confidence_scores: The confidence + scores for determining whether to show the generated response or an “I + don't know” response. + :param str response_length_option: The response length option. It is used + to control the length of the generated response. It is configured either in + the user interface or through the Update skill API. For more information, + see [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#tuning-the-generated-response-length-in-conversational-search). + :param List[SearchResults] search_results: An array of objects containing + the search results. + :param str disclaimer: A disclaimer for the conversational search response. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - self.handler = handler + self.response_type = response_type + self.text = text + self.citations_title = citations_title + self.citations = citations + self.confidence_scores = confidence_scores + self.response_length_option = response_length_option + self.search_results = search_results + self.disclaimer = disclaimer @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'type\' not present in LogMessageSourceHandler JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( - 'Required property \'action\' not present in LogMessageSourceHandler JSON' + 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' ) - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'handler' in _dict: - args['handler'] = _dict.get('handler') + if (citations_title := _dict.get('citations_title')) is not None: + args['citations_title'] = citations_title else: raise ValueError( - 'Required property \'handler\' not present in LogMessageSourceHandler JSON' + 'Required property \'citations_title\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogMessageSourceHandler object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'handler') and self.handler is not None: - _dict['handler'] = self.handler - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceHandler object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogMessageSourceHandler') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'LogMessageSourceHandler') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogMessageSourceStep(LogMessageSource): - """ - An object that identifies the dialog element that generated the error message. - - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. - :attr str step: The unique identifier of the step that generated the error - message. - """ - - def __init__(self, type: str, action: str, step: str) -> None: - """ - Initialize a LogMessageSourceStep object. - - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str step: The unique identifier of the step that generated the error - message. - """ - # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': - """Initialize a LogMessageSourceStep object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (citations := _dict.get('citations')) is not None: + args['citations'] = [ + ResponseGenericCitation.from_dict(v) for v in citations + ] else: raise ValueError( - 'Required property \'type\' not present in LogMessageSourceStep JSON' + 'Required property \'citations\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (confidence_scores := _dict.get('confidence_scores')) is not None: + args[ + 'confidence_scores'] = ResponseGenericConfidenceScores.from_dict( + confidence_scores) else: raise ValueError( - 'Required property \'action\' not present in LogMessageSourceStep JSON' + 'Required property \'confidence_scores\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' ) - if 'step' in _dict: - args['step'] = _dict.get('step') + if (response_length_option := + _dict.get('response_length_option')) is not None: + args['response_length_option'] = response_length_option else: raise ValueError( - 'Required property \'step\' not present in LogMessageSourceStep JSON' + 'Required property \'response_length_option\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (search_results := _dict.get('search_results')) is not None: + args['search_results'] = [ + SearchResults.from_dict(v) for v in search_results + ] + else: + raise ValueError( + 'Required property \'search_results\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (disclaimer := _dict.get('disclaimer')) is not None: + args['disclaimer'] = disclaimer + else: + raise ValueError( + 'Required property \'disclaimer\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceStep object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, + 'citations_title') and self.citations_title is not None: + _dict['citations_title'] = self.citations_title + if hasattr(self, 'citations') and self.citations is not None: + citations_list = [] + for v in self.citations: + if isinstance(v, dict): + citations_list.append(v) + else: + citations_list.append(v.to_dict()) + _dict['citations'] = citations_list + if hasattr(self, + 'confidence_scores') and self.confidence_scores is not None: + if isinstance(self.confidence_scores, dict): + _dict['confidence_scores'] = self.confidence_scores + else: + _dict['confidence_scores'] = self.confidence_scores.to_dict() + if hasattr(self, 'response_length_option' + ) and self.response_length_option is not None: + _dict['response_length_option'] = self.response_length_option + if hasattr(self, 'search_results') and self.search_results is not None: + search_results_list = [] + for v in self.search_results: + if isinstance(v, dict): + search_results_list.append(v) + else: + search_results_list.append(v.to_dict()) + _dict['search_results'] = search_results_list + if hasattr(self, 'disclaimer') and self.disclaimer is not None: + _dict['disclaimer'] = self.disclaimer return _dict def _to_dict(self): @@ -5744,112 +21888,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceStep object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceStep') -> bool: + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceStep') -> bool: + def __ne__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): +class RuntimeResponseGenericRuntimeResponseTypeDate(RuntimeResponseGeneric): """ - RuntimeResponseGenericRuntimeResponseTypeAudio. + RuntimeResponseGenericRuntimeResponseTypeDate. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) The title or introductory text to show before the - response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects - specifying channels for which the response is intended. If **channels** is - present, the response is intended for a built-in integration and should not be - handled by an API client. - :attr object channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen - readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + ) -> None: """ - Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str source: The `https:` URL of the audio clip. - :param str title: (optional) The title or introductory text to show before - the response. - :param str description: (optional) The description to show with the the - response. - :param List[ResponseGenericChannel] channels: (optional) An array of - objects specifying channels for which the response is intended. If - **channels** is present, the response is intended for a built-in - integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. - :param str alt_text: (optional) Descriptive text that can be used for - screen readers or other situations where the audio player cannot be seen. """ # pylint: disable=super-init-not-called self.response_type = response_type - self.source = source - self.title = title - self.description = description - self.channels = channels - self.channel_options = channel_options - self.alt_text = alt_text @classmethod def from_dict( cls, - _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': - """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDate': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') - else: - raise ValueError( - 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' - ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDate JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: - args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') - ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -5857,19 +21954,6 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] - if hasattr(self, - 'channel_options') and self.channel_options is not None: - _dict['channel_options'] = self.channel_options - if hasattr(self, 'alt_text') and self.alt_text is not None: - _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): @@ -5877,55 +21961,49 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeAudio object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeDate object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, - other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool: + other: 'RuntimeResponseGenericRuntimeResponseTypeDate') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, - other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool: + other: 'RuntimeResponseGenericRuntimeResponseTypeDate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( - RuntimeResponseGeneric): +class RuntimeResponseGenericRuntimeResponseTypeDtmf(RuntimeResponseGeneric): """ - RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. + RuntimeResponseGenericRuntimeResponseTypeDtmf. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_user: The message to display to the user when initiating a - channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to - transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param DtmfCommandInfo command_info: (optional) + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + *, + command_info: Optional['DtmfCommandInfo'] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ - Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeDtmf object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str message_to_user: The message to display to the user when - initiating a channel transfer. - :param ChannelTransferInfo transfer_info: Information used by an - integration to transfer the conversation to a different channel. + :param DtmfCommandInfo command_info: (optional) :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in @@ -5933,59 +22011,52 @@ def __init__(self, """ # pylint: disable=super-init-not-called self.response_type = response_type - self.message_to_user = message_to_user - self.transfer_info = transfer_info + self.command_info = command_info self.channels = channels @classmethod def from_dict( - cls, _dict: Dict - ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': - """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDtmf': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDtmf object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' - ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') - else: - raise ValueError( - 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' - ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) - else: - raise ValueError( - 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDtmf JSON' ) - if 'channels' in _dict: + if (command_info := _dict.get('command_info')) is not None: + args['command_info'] = DtmfCommandInfo.from_dict(command_info) + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDtmf object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, - 'message_to_user') and self.message_to_user is not None: - _dict['message_to_user'] = self.message_to_user - if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'command_info') and self.command_info is not None: + if isinstance(self.command_info, dict): + _dict['command_info'] = self.command_info + else: + _dict['command_info'] = self.command_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -5993,131 +22064,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeDtmf object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - ) -> bool: + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeDtmf') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__( - self, other: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - ) -> bool: + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeDtmf') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( +class RuntimeResponseGenericRuntimeResponseTypeEndSession( RuntimeResponseGeneric): """ - RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. + RuntimeResponseGenericRuntimeResponseTypeEndSession. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message - to be displayed to the user to indicate that the conversation will be - transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) - Routing or other contextual information to be used by target service desk - systems. - :attr str topic: (optional) A label identifying the topic of the conversation, - derived from the **title** property of the relevant node or the **topic** - property of the dialog node response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects - specifying channels for which the response is intended. If **channels** is - present, the response is intended for a built-in integration and should not be - handled by an API client. + :param dict channel_options: (optional) For internal use only. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + channel_options: Optional[dict] = None, + ) -> None: """ - Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeEndSession object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str message_to_human_agent: (optional) A message to be sent to the - human agent who will be taking over the conversation. - :param AgentAvailabilityMessage agent_available: (optional) An optional - message to be displayed to the user to indicate that the conversation will - be transferred to the next available agent. - :param AgentAvailabilityMessage agent_unavailable: (optional) An optional - message to be displayed to the user to indicate that no online agent is - available to take over the conversation. - :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) - Routing or other contextual information to be used by target service desk - systems. - :param str topic: (optional) A label identifying the topic of the - conversation, derived from the **title** property of the relevant node or - the **topic** property of the dialog node response. - :param List[ResponseGenericChannel] channels: (optional) An array of - objects specifying channels for which the response is intended. If - **channels** is present, the response is intended for a built-in - integration and should not be handled by an API client. + :param dict channel_options: (optional) For internal use only. """ # pylint: disable=super-init-not-called self.response_type = response_type - self.message_to_human_agent = message_to_human_agent - self.agent_available = agent_available - self.agent_unavailable = agent_unavailable - self.transfer_info = transfer_info - self.topic = topic - self.channels = channels + self.channel_options = channel_options @classmethod def from_dict( - cls, _dict: Dict - ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': - """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeEndSession': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeEndSession object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( - 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeEndSession JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: - args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: - args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: - args[ - 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'channels' in _dict: - args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') - ] + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeEndSession object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -6125,21 +22134,9 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, - 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, - 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() - if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() - if hasattr(self, 'topic') and self.topic is not None: - _dict['topic'] = self.topic - if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options return _dict def _to_dict(self): @@ -6147,11 +22144,11 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeEndSession object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + self, other: 'RuntimeResponseGenericRuntimeResponseTypeEndSession' ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): @@ -6159,7 +22156,7 @@ def __eq__( return self.__dict__ == other.__dict__ def __ne__( - self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + self, other: 'RuntimeResponseGenericRuntimeResponseTypeEndSession' ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6169,28 +22166,31 @@ class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before the + response. + :param str description: (optional) The description to show with the the response. - :attr str description: (optional) The description to show with the the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. @@ -6223,28 +22223,27 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -6267,7 +22266,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6297,27 +22302,30 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) The title to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str source: The `https:` URL of the image. + :param str title: (optional) The title to show before the response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -6349,29 +22357,28 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -6391,7 +22398,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -6421,27 +22434,30 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param str title: The title or introductory text to show before the response. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -6474,35 +22490,33 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -6523,9 +22537,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6554,6 +22580,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -6562,23 +22589,25 @@ class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -6605,24 +22634,23 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -6641,7 +22669,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6669,27 +22703,29 @@ class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeSearch. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str header: The title or introductory text to show before the response. + :param str header: The title or introductory text to show before the response. This text is defined in the search skill configuration. - :attr List[SearchResult] primary_results: An array of objects that contains the + :param List[SearchResult] primary_results: An array of objects that contains the search results to be displayed in the initial response to the user. - :attr List[SearchResult] additional_results: An array of objects that contains + :param List[SearchResult] additional_results: An array of objects that contains additional search results that can be displayed to the user upon request. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - header: str, - primary_results: List['SearchResult'], - additional_results: List['SearchResult'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + header: str, + primary_results: List['SearchResult'], + additional_results: List['SearchResult'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object. @@ -6722,39 +22758,37 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeSearch': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'header' in _dict: - args['header'] = _dict.get('header') + if (header := _dict.get('header')) is not None: + args['header'] = header else: raise ValueError( 'Required property \'header\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'primary_results' in _dict: + if (primary_results := _dict.get('primary_results')) is not None: args['primary_results'] = [ - SearchResult.from_dict(x) for x in _dict.get('primary_results') + SearchResult.from_dict(v) for v in primary_results ] else: raise ValueError( 'Required property \'primary_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'additional_results' in _dict: + if (additional_results := _dict.get('additional_results')) is not None: args['additional_results'] = [ - SearchResult.from_dict(x) - for x in _dict.get('additional_results') + SearchResult.from_dict(v) for v in additional_results ] else: raise ValueError( 'Required property \'additional_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -6772,17 +22806,31 @@ def to_dict(self) -> Dict: _dict['header'] = self.header if hasattr(self, 'primary_results') and self.primary_results is not None: - _dict['primary_results'] = [ - x.to_dict() for x in self.primary_results - ] + primary_results_list = [] + for v in self.primary_results: + if isinstance(v, dict): + primary_results_list.append(v) + else: + primary_results_list.append(v.to_dict()) + _dict['primary_results'] = primary_results_list if hasattr( self, 'additional_results') and self.additional_results is not None: - _dict['additional_results'] = [ - x.to_dict() for x in self.additional_results - ] + additional_results_list = [] + for v in self.additional_results: + if isinstance(v, dict): + additional_results_list.append(v) + else: + additional_results_list.append(v.to_dict()) + _dict['additional_results'] = additional_results_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6813,23 +22861,25 @@ class RuntimeResponseGenericRuntimeResponseTypeSuggestion( """ RuntimeResponseGenericRuntimeResponseTypeSuggestion. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr List[DialogSuggestion] suggestions: An array of objects describing the + :param str title: The title or introductory text to show before the response. + :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - suggestions: List['DialogSuggestion'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -6857,30 +22907,29 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'suggestions' in _dict: + if (suggestions := _dict.get('suggestions')) is not None: args['suggestions'] = [ - DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in suggestions ] else: raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -6897,9 +22946,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + suggestions_list = [] + for v in self.suggestions: + if isinstance(v, dict): + suggestions_list.append(v) + else: + suggestions_list.append(v.to_dict()) + _dict['suggestions'] = suggestions_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6929,20 +22990,22 @@ class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str text: The text of the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - text: str, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + text: str, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -6966,22 +23029,21 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -6998,7 +23060,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -7027,21 +23095,23 @@ class RuntimeResponseGenericRuntimeResponseTypeUserDefined( """ RuntimeResponseGenericRuntimeResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. @@ -7066,22 +23136,21 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -7098,7 +23167,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -7128,30 +23203,33 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before the + response. + :param str description: (optional) The description to show with the the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -7167,7 +23245,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -7186,31 +23264,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -7230,7 +23307,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -7257,3 +23340,219 @@ def __ne__(self, other: 'RuntimeResponseGenericRuntimeResponseTypeVideo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + +class StatelessMessageStreamResponseMessageStreamCompleteItem( + StatelessMessageStreamResponse): + """ + A completed response item. A complete item is a composition of every streamed partial + item with the same streaming_metadata.id, and each complete item contains its own + unique streaming_metadata.id. + + :param CompleteItem complete_item: (optional) + """ + + def __init__( + self, + *, + complete_item: Optional['CompleteItem'] = None, + ) -> None: + """ + Initialize a StatelessMessageStreamResponseMessageStreamCompleteItem object. + + :param CompleteItem complete_item: (optional) + """ + # pylint: disable=super-init-not-called + self.complete_item = complete_item + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'StatelessMessageStreamResponseMessageStreamCompleteItem': + """Initialize a StatelessMessageStreamResponseMessageStreamCompleteItem object from a json dictionary.""" + args = {} + if (complete_item := _dict.get('complete_item')) is not None: + args['complete_item'] = CompleteItem.from_dict(complete_item) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageStreamResponseMessageStreamCompleteItem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'complete_item') and self.complete_item is not None: + if isinstance(self.complete_item, dict): + _dict['complete_item'] = self.complete_item + else: + _dict['complete_item'] = self.complete_item.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageStreamResponseMessageStreamCompleteItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'StatelessMessageStreamResponseMessageStreamCompleteItem' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'StatelessMessageStreamResponseMessageStreamCompleteItem' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageStreamResponseMessageStreamPartialItem( + StatelessMessageStreamResponse): + """ + A chunk of the streamed message response. + + :param PartialItem partial_item: (optional) Message response partial item + content. + """ + + def __init__( + self, + *, + partial_item: Optional['PartialItem'] = None, + ) -> None: + """ + Initialize a StatelessMessageStreamResponseMessageStreamPartialItem object. + + :param PartialItem partial_item: (optional) Message response partial item + content. + """ + # pylint: disable=super-init-not-called + self.partial_item = partial_item + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'StatelessMessageStreamResponseMessageStreamPartialItem': + """Initialize a StatelessMessageStreamResponseMessageStreamPartialItem object from a json dictionary.""" + args = {} + if (partial_item := _dict.get('partial_item')) is not None: + args['partial_item'] = PartialItem.from_dict(partial_item) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageStreamResponseMessageStreamPartialItem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'partial_item') and self.partial_item is not None: + if isinstance(self.partial_item, dict): + _dict['partial_item'] = self.partial_item + else: + _dict['partial_item'] = self.partial_item.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageStreamResponseMessageStreamPartialItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'StatelessMessageStreamResponseMessageStreamPartialItem' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'StatelessMessageStreamResponseMessageStreamPartialItem' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageStreamResponseStatelessMessageStreamFinalResponse( + StatelessMessageStreamResponse): + """ + The final and stateless message response. + + :param StatelessFinalResponse final_response: (optional) Message final response + content. + """ + + def __init__( + self, + *, + final_response: Optional['StatelessFinalResponse'] = None, + ) -> None: + """ + Initialize a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object. + + :param StatelessFinalResponse final_response: (optional) Message final + response content. + """ + # pylint: disable=super-init-not-called + self.final_response = final_response + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse': + """Initialize a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object from a json dictionary.""" + args = {} + if (final_response := _dict.get('final_response')) is not None: + args['final_response'] = StatelessFinalResponse.from_dict( + final_response) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'final_response') and self.final_response is not None: + if isinstance(self.final_response, dict): + _dict['final_response'] = self.final_response + else: + _dict['final_response'] = self.final_response.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, + other: 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/ibm_watson/common.py b/ibm_watson/common.py index 81ecc7ec0..a1595d614 100644 --- a/ibm_watson/common.py +++ b/ibm_watson/common.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2019 IBM All Rights Reserved. +# Copyright 2019, 2024 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,7 +15,9 @@ # limitations under the License. import platform +import json from .version import __version__ +from typing import Iterator SDK_ANALYTICS_HEADER = 'X-IBMCloud-SDK-Analytics' USER_AGENT_HEADER = 'User-Agent' @@ -48,3 +50,22 @@ def get_sdk_headers(service_name, service_version, operation_id): operation_id) headers[USER_AGENT_HEADER] = get_user_agent() return headers + + +def parse_sse_stream_data(response) -> Iterator[dict]: + event_message = None # Can be used in the future to return the event message to the user + data_json = None + + for chunk in response.iter_lines(): + decoded_chunk = chunk.decode("utf-8") + + if decoded_chunk.find("event", 0, len("event")) == 0: + event_message = decoded_chunk[len("event") + 2:] + elif decoded_chunk.find("data", 0, len("data")) == 0: + data_json_str = decoded_chunk[len("data") + 2:] + data_json = json.loads(data_json_str) + + if event_message and data_json is not None: + yield data_json + event_message = None + data_json = None diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py deleted file mode 100644 index 08411eb79..000000000 --- a/ibm_watson/discovery_v1.py +++ /dev/null @@ -1,13842 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2022. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 -""" -IBM Watson™ Discovery is a cognitive search and content analytics engine that you -can add to applications to identify patterns, trends and actionable insights to drive -better decision-making. Securely unify structured and unstructured data with pre-enriched -content, and use a simplified query language to eliminate the need for manual filtering of -results. - -API Version: 1.0 -See: https://cloud.ibm.com/docs/discovery -""" - -from datetime import date -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List -import json -import sys - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_list, convert_model, date_to_string, datetime_to_string, string_to_date, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class DiscoveryV1(BaseService): - """The Discovery V1 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'discovery' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Discovery service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2019-04-30`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Environments - ######################### - - def create_environment(self, - name: str, - *, - description: str = None, - size: str = None, - **kwargs) -> DetailedResponse: - """ - Create an environment. - - Creates a new environment for private data. An environment must be created before - collections can be created. - **Note**: You can create only one environment for private data per service - instance. An attempt to create another environment results in an error. - - :param str name: Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Size of the environment. In the Lite plan the - default and only accepted value is `LT`, in all other plans the default is - `S`. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_environment') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'name': name, 'description': description, 'size': size} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/environments' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def list_environments(self, - *, - name: str = None, - **kwargs) -> DetailedResponse: - """ - List environments. - - List existing environments for the service instance. - - :param str name: (optional) Show only the environment with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListEnvironmentsResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_environments') - headers.update(sdk_headers) - - params = {'version': self.version, 'name': name} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/environments' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_environment(self, environment_id: str, - **kwargs) -> DetailedResponse: - """ - Get environment info. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_environment') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_environment(self, - environment_id: str, - *, - name: str = None, - description: str = None, - size: str = None, - **kwargs) -> DetailedResponse: - """ - Update an environment. - - Updates an environment. The environment's **name** and **description** parameters - can be changed. You must specify a **name** for the environment. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Size to change the environment to. **Note:** - Lite plan users cannot change the environment size. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_environment') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'name': name, 'description': description, 'size': size} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_environment(self, environment_id: str, - **kwargs) -> DetailedResponse: - """ - Delete environment. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteEnvironmentResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_environment') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def list_fields(self, environment_id: str, collection_ids: List[str], - **kwargs) -> DetailedResponse: - """ - List fields across collections. - - Gets a list of the unique fields (and their types) stored in the indexes of the - specified collections. - - :param str environment_id: The ID of the environment. - :param List[str] collection_ids: A comma-separated list of collection IDs - to be queried against. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_fields') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids) - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/fields'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Configurations - ######################### - - def create_configuration( - self, - environment_id: str, - name: str, - *, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None, - **kwargs) -> DetailedResponse: - """ - Add configuration. - - Creates a new configuration. - If the input configuration contains the **configuration_id**, **created**, or - **updated** properties, then they are ignored and overridden by the system, and an - error is not returned so that the overridden fields do not need to be removed when - copying a configuration. - The configuration can contain unrecognized JSON fields. Any such fields are - ignored and do not generate an error. This makes it easier to use newer - configuration files with older versions of the API and the service. It also makes - it possible for the tooling to add additional metadata and information to the - configuration. - - :param str environment_id: The ID of the environment. - :param str name: The name of the configuration. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if name is None: - raise ValueError('name must be provided') - if conversions is not None: - conversions = convert_model(conversions) - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] - if normalizations is not None: - normalizations = [convert_model(x) for x in normalizations] - if source is not None: - source = convert_model(source) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_configuration') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'name': name, - 'description': description, - 'conversions': conversions, - 'enrichments': enrichments, - 'normalizations': normalizations, - 'source': source - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def list_configurations(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: - """ - List configurations. - - Lists existing configurations for the service instance. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Find configurations with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListConfigurationsResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_configurations') - headers.update(sdk_headers) - - params = {'version': self.version, 'name': name} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> DetailedResponse: - """ - Get configuration details. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if configuration_id is None: - raise ValueError('configuration_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_configuration') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_configuration( - self, - environment_id: str, - configuration_id: str, - name: str, - *, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None, - **kwargs) -> DetailedResponse: - """ - Update a configuration. - - Replaces an existing configuration. - * Completely replaces the original configuration. - * The **configuration_id**, **updated**, and **created** fields are accepted in - the request, but they are ignored, and an error is not generated. It is also - acceptable for users to submit an updated configuration with none of the three - properties. - * Documents are processed with a snapshot of the configuration as it was at the - time the document was submitted to be ingested. This means that already submitted - documents will not see any updates made to the configuration. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param str name: The name of the configuration. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if configuration_id is None: - raise ValueError('configuration_id must be provided') - if name is None: - raise ValueError('name must be provided') - if conversions is not None: - conversions = convert_model(conversions) - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] - if normalizations is not None: - normalizations = [convert_model(x) for x in normalizations] - if source is not None: - source = convert_model(source) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_configuration') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'name': name, - 'description': description, - 'conversions': conversions, - 'enrichments': enrichments, - 'normalizations': normalizations, - 'source': source - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a configuration. - - The deletion is performed unconditionally. A configuration deletion request - succeeds even if the configuration is referenced by a collection or document - ingestion. However, documents that have already been submitted for processing - continue to use the deleted configuration. Documents are always processed with a - snapshot of the configuration as it existed at the time the document was - submitted. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteConfigurationResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if configuration_id is None: - raise ValueError('configuration_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_configuration') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Collections - ######################### - - def create_collection(self, - environment_id: str, - name: str, - *, - description: str = None, - configuration_id: str = None, - language: str = None, - **kwargs) -> DetailedResponse: - """ - Create a collection. - - :param str environment_id: The ID of the environment. - :param str name: The name of the collection to be created. - :param str description: (optional) A description of the collection. - :param str configuration_id: (optional) The ID of the configuration in - which the collection is to be created. - :param str language: (optional) The language of the documents stored in the - collection, in the form of an ISO 639-1 language code. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'name': name, - 'description': description, - 'configuration_id': configuration_id, - 'language': language - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def list_collections(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: - """ - List collections. - - Lists existing collections for the service instance. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Find collections with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collections') - headers.update(sdk_headers) - - params = {'version': self.version, 'name': name} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_collection(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Get collection details. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_collection(self, - environment_id: str, - collection_id: str, - name: str, - *, - description: str = None, - configuration_id: str = None, - **kwargs) -> DetailedResponse: - """ - Update a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str configuration_id: (optional) The ID of the configuration in - which the collection is to be updated. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'name': name, - 'description': description, - 'configuration_id': configuration_id - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_collection(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteCollectionResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def list_collection_fields(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - List collection fields. - - Gets a list of the unique fields (and their types) stored in the index. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collection_fields') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/fields'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Query modifications - ######################### - - def list_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Get the expansion list. - - Returns the current expansion list for the specified collection. If an expansion - list is not specified, an object with empty expansion arrays is returned. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Expansions` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_expansions') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_expansions(self, environment_id: str, collection_id: str, - expansions: List['Expansion'], - **kwargs) -> DetailedResponse: - """ - Create or update expansion list. - - Create or replace the Expansion list for this collection. The maximum number of - expanded terms per collection is `500`. The current expansion list is replaced - with the uploaded content. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms - that will be expanded into other terms. Each expansion object can be - configured as bidirectional or unidirectional. Bidirectional means that all - terms are expanded to all other terms in the object. Unidirectional means - that a set list of terms can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. - When found in a query, all items in the **expanded_terms** array are then - expanded to the other items in the same array. - To create a uni-directional expansion, specify both an array of - **input_terms** and an array of **expanded_terms**. When items in the - **input_terms** array are present in a query, they are expanded using the - items listed in the **expanded_terms** array. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Expansions` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if expansions is None: - raise ValueError('expansions must be provided') - expansions = [convert_model(x) for x in expansions] - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_expansions') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'expansions': expansions} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Delete the expansion list. - - Remove the expansion information for this collection. The expansion list must be - deleted to disable query expansion for a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_expansions') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_tokenization_dictionary_status(self, environment_id: str, - collection_id: str, - **kwargs) -> DetailedResponse: - """ - Get tokenization dictionary status. - - Returns the current status of the tokenization dictionary for the specified - collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_tokenization_dictionary_status') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - *, - tokenization_rules: List['TokenDictRule'] = None, - **kwargs) -> DetailedResponse: - """ - Create tokenization dictionary. - - Upload a custom tokenization dictionary to use with the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param List[TokenDictRule] tokenization_rules: (optional) An array of - tokenization rules. Each rule contains, the original `text` string, - component `tokens`, any alternate character set `readings`, and which - `part_of_speech` the text is from. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if tokenization_rules is not None: - tokenization_rules = [convert_model(x) for x in tokenization_rules] - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_tokenization_dictionary') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'tokenization_rules': tokenization_rules} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_tokenization_dictionary(self, environment_id: str, - collection_id: str, - **kwargs) -> DetailedResponse: - """ - Delete tokenization dictionary. - - Delete the tokenization dictionary from the collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_tokenization_dictionary') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_stopword_list_status(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Get stopword list status. - - Returns the current status of the stopword list for the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_stopword_list_status') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_stopword_list(self, - environment_id: str, - collection_id: str, - stopword_file: BinaryIO, - *, - stopword_filename: str = None, - **kwargs) -> DetailedResponse: - """ - Create stopword list. - - Upload a custom stopword list to use with the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param BinaryIO stopword_file: The content of the stopword list to ingest. - :param str stopword_filename: (optional) The filename for stopword_file. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if stopword_file is None: - raise ValueError('stopword_file must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_stopword_list') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - if not stopword_filename and hasattr(stopword_file, 'name'): - stopword_filename = basename(stopword_file.name) - if not stopword_filename: - raise ValueError('stopword_filename must be provided') - form_data.append(('stopword_file', (stopword_filename, stopword_file, - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_stopword_list(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a custom stopword list. - - Delete a custom stopword list from the collection. After a custom stopword list is - deleted, the default list is used for the collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_stopword_list') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Documents - ######################### - - def add_document(self, - environment_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: - """ - Add a document. - - Add a document to a collection with optional metadata. - * The **version** query parameter is still required. - * Returns immediately after the system has accepted the document for processing. - * The user must provide document content, metadata, or both. If the request is - missing both document content and metadata, it is rejected. - * The user can set the **Content-Type** parameter on the **file** part to - indicate the media type of the document. If the **Content-Type** parameter is - missing or is one of the generic media types (for example, - `application/octet-stream`), then the service attempts to automatically detect the - document's media type. - * The following field names are reserved and will be filtered out if present - after normalization: `id`, `score`, `highlight`, and any field with the prefix of: - `_`, `+`, or `-` - * Fields with empty name values after normalization are filtered out before - indexing. - * Fields containing the following characters after normalization are filtered - out before indexing: `#` and `,` - **Note:** Documents can be added with a specific **document_id** by using the - **/v1/environments/{environment_id}/collections/{collection_id}/documents** - method. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_document') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def get_document_status(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: - """ - Get document details. - - Fetch status details about a submitted document. **Note:** this operation does not - return the document itself. Instead, it returns only the document's processing - status and any notices (warnings or errors) that were generated when the document - was ingested. Use the query API to retrieve the actual document content. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str document_id: The ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if document_id is None: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_document_status') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_document(self, - environment_id: str, - collection_id: str, - document_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: - """ - Update a document. - - Replace an existing document or add a document with a specified **document_id**. - Starts ingesting a document with optional metadata. - **Note:** When uploading a new document with this method it automatically replaces - any document stored with the same **document_id** if it exists. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str document_id: The ID of the document. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if document_id is None: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_document') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_document(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: - """ - Delete a document. - - If the given document ID is invalid, or if the document is not found, then the a - success response is returned (HTTP status code `200`) with the status set to - 'deleted'. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str document_id: The ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if document_id is None: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_document') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Queries - ######################### - - def query(self, - environment_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: str = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - passages_fields: str = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: str = None, - similar_fields: str = None, - bias: str = None, - spelling_suggestions: bool = None, - x_watson_logging_opt_out: bool = None, - **kwargs) -> DetailedResponse: - """ - Query a collection. - - By using this method, you can construct long queries. For details, see the - [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param str return_: (optional) A comma-separated list of the portion of the - document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. This parameter - cannot be used in the same query as the **bias** parameter. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param str passages_fields: (optional) A comma-separated list of fields - that passages are drawn from. If this parameter not specified, then all - top-level fields are included. - :param int passages_count: (optional) The maximum number of passages to - return. The search returns fewer passages if the requested total is not - found. The default is `10`. The maximum is `100`. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param bool deduplicate: (optional) When `true`, and used with a Watson - Discovery News collection, duplicate results (based on the contents of the - **title** field) are removed. Duplicate comparison is limited to the - current query only; **offset** is not considered. This parameter is - currently Beta functionality. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param str similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param str similar_fields: (optional) A comma-separated list of field names - that are used as a basis for comparison to identify similar documents. If - not specified, the entire document is used for comparison. - :param str bias: (optional) Field which the returned results will be biased - against. The specified field must be either a **date** or **number** - format. When a **date** type field is specified returned results are biased - towards field values closer to the current date. When a **number** type - field is specified, returned results are biased towards higher field - values. This parameter cannot be used in the same query as the **sort** - parameter. - :param bool spelling_suggestions: (optional) When `true` and the - **natural_language_query** parameter is used, the **natural_languge_query** - parameter is spell checked. The most likely correction is returned in the - **suggested_query** field of the response (if one exists). - **Important:** this parameter is only valid when using the Cloud Pak - version of Discovery. - :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not - stored in the Discovery **Logs** endpoint. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'passages.fields': passages_fields, - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate': deduplicate, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': similar_document_ids, - 'similar.fields': similar_fields, - 'bias': bias, - 'spelling_suggestions': spelling_suggestions - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/query'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def query_notices(self, - environment_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: List[str] = None, - highlight: bool = None, - passages_fields: List[str] = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: List[str] = None, - similar_fields: List[str] = None, - **kwargs) -> DetailedResponse: - """ - Query system notices. - - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. See the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) - for more details on the query language. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] return_: (optional) A comma-separated list of the portion - of the document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param List[str] passages_fields: (optional) A comma-separated list of - fields that passages are drawn from. If this parameter not specified, then - all top-level fields are included. - :param int passages_count: (optional) The maximum number of passages to - return. The search returns fewer passages if the requested total is not - found. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param List[str] similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param List[str] similar_fields: (optional) A comma-separated list of field - names that are used as a basis for comparison to identify similar - documents. If not specified, the entire document is used for comparison. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_notices') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': convert_list(return_), - 'offset': offset, - 'sort': convert_list(sort), - 'highlight': highlight, - 'passages.fields': convert_list(passages_fields), - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields) - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/notices'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def federated_query(self, - environment_id: str, - collection_ids: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: str = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - passages_fields: str = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: str = None, - similar_fields: str = None, - bias: str = None, - x_watson_logging_opt_out: bool = None, - **kwargs) -> DetailedResponse: - """ - Query multiple collections. - - By using this method, you can construct long queries that search multiple - collection. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). - - :param str environment_id: The ID of the environment. - :param str collection_ids: A comma-separated list of collection IDs to be - queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param str return_: (optional) A comma-separated list of the portion of the - document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. This parameter - cannot be used in the same query as the **bias** parameter. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param str passages_fields: (optional) A comma-separated list of fields - that passages are drawn from. If this parameter not specified, then all - top-level fields are included. - :param int passages_count: (optional) The maximum number of passages to - return. The search returns fewer passages if the requested total is not - found. The default is `10`. The maximum is `100`. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param bool deduplicate: (optional) When `true`, and used with a Watson - Discovery News collection, duplicate results (based on the contents of the - **title** field) are removed. Duplicate comparison is limited to the - current query only; **offset** is not considered. This parameter is - currently Beta functionality. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param str similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param str similar_fields: (optional) A comma-separated list of field names - that are used as a basis for comparison to identify similar documents. If - not specified, the entire document is used for comparison. - :param str bias: (optional) Field which the returned results will be biased - against. The specified field must be either a **date** or **number** - format. When a **date** type field is specified returned results are biased - towards field values closer to the current date. When a **number** type - field is specified, returned results are biased towards higher field - values. This parameter cannot be used in the same query as the **sort** - parameter. - :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not - stored in the Discovery **Logs** endpoint. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'collection_ids': collection_ids, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'passages.fields': passages_fields, - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate': deduplicate, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': similar_document_ids, - 'similar.fields': similar_fields, - 'bias': bias - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/query'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def federated_query_notices(self, - environment_id: str, - collection_ids: List[str], - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: List[str] = None, - highlight: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: List[str] = None, - similar_fields: List[str] = None, - **kwargs) -> DetailedResponse: - """ - Query multiple collection system notices. - - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. See the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) - for more details on the query language. - - :param str environment_id: The ID of the environment. - :param List[str] collection_ids: A comma-separated list of collection IDs - to be queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] return_: (optional) A comma-separated list of the portion - of the document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param List[str] similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param List[str] similar_fields: (optional) A comma-separated list of field - names that are used as a basis for comparison to identify similar - documents. If not specified, the entire document is used for comparison. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query_notices') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids), - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'aggregation': aggregation, - 'count': count, - 'return': convert_list(return_), - 'offset': offset, - 'sort': convert_list(sort), - 'highlight': highlight, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields) - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/notices'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_autocompletion(self, - environment_id: str, - collection_id: str, - prefix: str, - *, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: - """ - Get Autocomplete Suggestions. - - Returns completion query suggestions for the specified prefix. /n/n - **Important:** this method is only valid when using the Cloud Pak version of - Discovery. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. - :param str field: (optional) The field in the result documents that - autocompletion suggestions are identified from. - :param int count: (optional) The number of autocompletion suggestions to - return. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Completions` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if prefix is None: - raise ValueError('prefix must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_autocompletion') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'prefix': prefix, - 'field': field, - 'count': count - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/autocompletion'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Training data - ######################### - - def list_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - List training data. - - Lists the training data for the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingDataSet` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_data') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def add_training_data(self, - environment_id: str, - collection_id: str, - *, - natural_language_query: str = None, - filter: str = None, - examples: List['TrainingExample'] = None, - **kwargs) -> DetailedResponse: - """ - Add query to training data. - - Adds a query to the training data for this collection. The query can contain a - filter and natural language query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str natural_language_query: (optional) The natural text query for - the new training query. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param List[TrainingExample] examples: (optional) Array of training - examples. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if examples is not None: - examples = [convert_model(x) for x in examples] - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_training_data') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'natural_language_query': natural_language_query, - 'filter': filter, - 'examples': examples - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_all_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Delete all training data. - - Deletes all training data from a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_all_training_data') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: - """ - Get details about a query. - - Gets details for a specific training data query, including the query string and - all examples. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_data') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def delete_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: - """ - Delete a training data query. - - Removes the training data query and all associated examples from the training data - set. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_data') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def list_training_examples(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: - """ - List examples for a training data query. - - List all examples for this training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExampleList` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_examples') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_training_example(self, - environment_id: str, - collection_id: str, - query_id: str, - *, - document_id: str = None, - cross_reference: str = None, - relevance: int = None, - **kwargs) -> DetailedResponse: - """ - Add example to training data query. - - Adds a example to this training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str document_id: (optional) The document ID associated with this - training example. - :param str cross_reference: (optional) The cross reference associated with - this training example. - :param int relevance: (optional) The relevance of the training example. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_training_example') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'document_id': document_id, - 'cross_reference': cross_reference, - 'relevance': relevance - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_training_example(self, environment_id: str, collection_id: str, - query_id: str, example_id: str, - **kwargs) -> DetailedResponse: - """ - Delete example for training data query. - - Deletes the example document with the given ID from the training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - if example_id is None: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_example') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_training_example(self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - *, - cross_reference: str = None, - relevance: int = None, - **kwargs) -> DetailedResponse: - """ - Change label or cross reference for example. - - Changes the label or cross reference query for this training data example. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param str cross_reference: (optional) The example to add. - :param int relevance: (optional) The relevance value for this example. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - if example_id is None: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_training_example') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'cross_reference': cross_reference, 'relevance': relevance} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def get_training_example(self, environment_id: str, collection_id: str, - query_id: str, example_id: str, - **kwargs) -> DetailedResponse: - """ - Get details for training data example. - - Gets the details for this training example. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - if example_id is None: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_example') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # User data - ######################### - - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: - """ - Delete labeled data. - - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - You associate a customer ID with data by passing the **X-Watson-Metadata** header - with a request that passes data. For more information about personal data and - customer IDs, see [Information - security](https://cloud.ibm.com/docs/discovery?topic=discovery-information-security#information-security). - - :param str customer_id: The customer ID for which all data is to be - deleted. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if customer_id is None: - raise ValueError('customer_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') - headers.update(sdk_headers) - - params = {'version': self.version, 'customer_id': customer_id} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Events and feedback - ######################### - - def create_event(self, type: str, data: 'EventData', - **kwargs) -> DetailedResponse: - """ - Create event. - - The **Events** API can be used to create log entries that are associated with - specific queries. For example, you can record which documents in the results set - were "clicked" by a user and when that click occurred. - - :param str type: The event type to be created. - :param EventData data: Query event data object. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CreateEventResponse` object - """ - - if type is None: - raise ValueError('type must be provided') - if data is None: - raise ValueError('data must be provided') - data = convert_model(data) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_event') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'type': type, 'data': data} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/events' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def query_log(self, - *, - filter: str = None, - query: str = None, - count: int = None, - offset: int = None, - sort: List[str] = None, - **kwargs) -> DetailedResponse: - """ - Search the query and event log. - - Searches the query and event log to find query sessions that match the specified - criteria. Searching the **logs** endpoint uses the standard Discovery query syntax - for the parameters that are supported. - - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `LogQueryResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_log') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'count': count, - 'offset': offset, - 'sort': convert_list(sort) - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/logs' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: - """ - Number of queries over time. - - Total number of queries using the **natural_language_query** parameter over a - specific time window. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_event(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: - """ - Number of queries with an event over time. - - Total number of queries using the **natural_language_query** parameter that have a - corresponding "click" event over a specified time window. This metric requires - having integrated event tracking in your application using the **Events** API. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_event') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries_with_event' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_no_results(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: - """ - Number of queries with no search results over time. - - Total number of queries using the **natural_language_query** parameter that have - no results returned over a specified time window. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_no_results') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries_with_no_search_results' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_metrics_event_rate(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: - """ - Percentage of queries with an associated event. - - The percentage of queries using the **natural_language_query** parameter that have - a corresponding "click" event over a specified time window. This metric requires - having integrated event tracking in your application using the **Events** API. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_event_rate') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/metrics/event_rate' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_token_event(self, - *, - count: int = None, - **kwargs) -> DetailedResponse: - """ - Most frequent query tokens with an event. - - The most frequent query tokens parsed from the **natural_language_query** - parameter and their corresponding "click" event rate within the recording period - (queries and events are stored for 30 days). A query token is an individual word - or unigram within the query string. - - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricTokenResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_token_event') - headers.update(sdk_headers) - - params = {'version': self.version, 'count': count} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/metrics/top_query_tokens_with_event_rate' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Credentials - ######################### - - def list_credentials(self, environment_id: str, - **kwargs) -> DetailedResponse: - """ - List credentials. - - List all the source credentials that have been created for this service instance. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CredentialsList` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_credentials') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_credentials(self, - environment_id: str, - *, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None, - **kwargs) -> DetailedResponse: - """ - Create credentials. - - Creates a set of credentials to connect to a remote source. Created credentials - are used in a configuration to associate a collection with the remote source. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if credential_details is not None: - credential_details = convert_model(credential_details) - if status is not None: - status = convert_model(status) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_credentials') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'source_type': source_type, - 'credential_details': credential_details, - 'status': status - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def get_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> DetailedResponse: - """ - View Credentials. - - Returns details about the specified credentials. - **Note:** Secure credential information such as a password or SSH key is never - returned and must be obtained from the source system. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if credential_id is None: - raise ValueError('credential_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_credentials') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_credentials(self, - environment_id: str, - credential_id: str, - *, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None, - **kwargs) -> DetailedResponse: - """ - Update credentials. - - Updates an existing set of source credentials. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if credential_id is None: - raise ValueError('credential_id must be provided') - if credential_details is not None: - credential_details = convert_model(credential_details) - if status is not None: - status = convert_model(status) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_credentials') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'source_type': source_type, - 'credential_details': credential_details, - 'status': status - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> DetailedResponse: - """ - Delete credentials. - - Deletes a set of stored credentials from your Discovery instance. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteCredentials` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if credential_id is None: - raise ValueError('credential_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_credentials') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # gatewayConfiguration - ######################### - - def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: - """ - List Gateways. - - List the currently configured gateways. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GatewayList` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_gateways') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_gateway(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: - """ - Create Gateway. - - Create a gateway configuration to use with a remotely installed gateway. - - :param str environment_id: The ID of the environment. - :param str name: (optional) User-defined name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Gateway` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_gateway') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'name': name} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def get_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> DetailedResponse: - """ - List Gateway Details. - - List information about the specified gateway. - - :param str environment_id: The ID of the environment. - :param str gateway_id: The requested gateway ID. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Gateway` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if gateway_id is None: - raise ValueError('gateway_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_gateway') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'gateway_id'] - path_param_values = self.encode_path_vars(environment_id, gateway_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def delete_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> DetailedResponse: - """ - Delete Gateway. - - Delete the specified gateway configuration. - - :param str environment_id: The ID of the environment. - :param str gateway_id: The requested gateway ID. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GatewayDelete` object - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if gateway_id is None: - raise ValueError('gateway_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_gateway') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'gateway_id'] - path_param_values = self.encode_path_vars(environment_id, gateway_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - -class AddDocumentEnums: - """ - Enums for add_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - -class UpdateDocumentEnums: - """ - Enums for update_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - -class GetMetricsQueryEnums: - """ - Enums for get_metrics_query parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - DOCUMENT = 'document' - - -class GetMetricsQueryEventEnums: - """ - Enums for get_metrics_query_event parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - DOCUMENT = 'document' - - -class GetMetricsQueryNoResultsEnums: - """ - Enums for get_metrics_query_no_results parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - DOCUMENT = 'document' - - -class GetMetricsEventRateEnums: - """ - Enums for get_metrics_event_rate parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - DOCUMENT = 'document' - - -############################################################################## -# Models -############################################################################## - - -class Collection(): - """ - A collection for storing documents. - - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. - :attr str description: (optional) The description of the collection. - :attr datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the collection was last - updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str status: (optional) The status of the collection. - :attr str configuration_id: (optional) The unique identifier of the collection's - configuration. - :attr str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and `es` - (Spanish). - :attr DocumentCounts document_counts: (optional) Object containing collection - document count information. - :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. - :attr TrainingStatus training_status: (optional) Training status details. - :attr CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :attr SduStatus smart_document_understanding: (optional) Object containing smart - document understanding information for this collection. - """ - - def __init__(self, - *, - collection_id: str = None, - name: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - configuration_id: str = None, - language: str = None, - document_counts: 'DocumentCounts' = None, - disk_usage: 'CollectionDiskUsage' = None, - training_status: 'TrainingStatus' = None, - crawl_status: 'CollectionCrawlStatus' = None, - smart_document_understanding: 'SduStatus' = None) -> None: - """ - Initialize a Collection object. - - :param str name: (optional) The name of the collection. - :param str description: (optional) The description of the collection. - :param str configuration_id: (optional) The unique identifier of the - collection's configuration. - :param str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and - `es` (Spanish). - :param DocumentCounts document_counts: (optional) Object containing - collection document count information. - :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. - :param TrainingStatus training_status: (optional) Training status details. - :param CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :param SduStatus smart_document_understanding: (optional) Object containing - smart document understanding information for this collection. - """ - self.collection_id = collection_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.status = status - self.configuration_id = configuration_id - self.language = language - self.document_counts = document_counts - self.disk_usage = disk_usage - self.training_status = training_status - self.crawl_status = crawl_status - self.smart_document_understanding = smart_document_understanding - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" - args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'document_counts' in _dict: - args['document_counts'] = DocumentCounts.from_dict( - _dict.get('document_counts')) - if 'disk_usage' in _dict: - args['disk_usage'] = CollectionDiskUsage.from_dict( - _dict.get('disk_usage')) - if 'training_status' in _dict: - args['training_status'] = TrainingStatus.from_dict( - _dict.get('training_status')) - if 'crawl_status' in _dict: - args['crawl_status'] = CollectionCrawlStatus.from_dict( - _dict.get('crawl_status')) - if 'smart_document_understanding' in _dict: - args['smart_document_understanding'] = SduStatus.from_dict( - _dict.get('smart_document_understanding')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Collection object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, - 'document_counts') and self.document_counts is not None: - _dict['document_counts'] = self.document_counts.to_dict() - if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage.to_dict() - if hasattr(self, - 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status.to_dict() - if hasattr(self, 'crawl_status') and self.crawl_status is not None: - _dict['crawl_status'] = self.crawl_status.to_dict() - if hasattr(self, 'smart_document_understanding' - ) and self.smart_document_understanding is not None: - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding.to_dict( - ) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Collection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Collection') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Collection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the collection. - """ - ACTIVE = 'active' - PENDING = 'pending' - MAINTENANCE = 'maintenance' - - -class CollectionCrawlStatus(): - """ - Object containing information about the crawl status of this collection. - - :attr SourceStatus source_crawl: (optional) Object containing source crawl - status information. - """ - - def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: - """ - Initialize a CollectionCrawlStatus object. - - :param SourceStatus source_crawl: (optional) Object containing source crawl - status information. - """ - self.source_crawl = source_crawl - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': - """Initialize a CollectionCrawlStatus object from a json dictionary.""" - args = {} - if 'source_crawl' in _dict: - args['source_crawl'] = SourceStatus.from_dict( - _dict.get('source_crawl')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionCrawlStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'source_crawl') and self.source_crawl is not None: - _dict['source_crawl'] = self.source_crawl.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CollectionCrawlStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionCrawlStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'CollectionCrawlStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionDiskUsage(): - """ - Summary of the disk usage statistics for this collection. - - :attr int used_bytes: (optional) Number of bytes used by the collection. - """ - - def __init__(self, *, used_bytes: int = None) -> None: - """ - Initialize a CollectionDiskUsage object. - - """ - self.used_bytes = used_bytes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': - """Initialize a CollectionDiskUsage object from a json dictionary.""" - args = {} - if 'used_bytes' in _dict: - args['used_bytes'] = _dict.get('used_bytes') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionDiskUsage object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'used_bytes') and getattr(self, - 'used_bytes') is not None: - _dict['used_bytes'] = getattr(self, 'used_bytes') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CollectionDiskUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionDiskUsage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'CollectionDiskUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionUsage(): - """ - Summary of the collection usage in the environment. - - :attr int available: (optional) Number of active collections in the environment. - :attr int maximum_allowed: (optional) Total number of collections allowed in the - environment. - """ - - def __init__(self, - *, - available: int = None, - maximum_allowed: int = None) -> None: - """ - Initialize a CollectionUsage object. - - """ - self.available = available - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionUsage': - """Initialize a CollectionUsage object from a json dictionary.""" - args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionUsage object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'maximum_allowed') and getattr( - self, 'maximum_allowed') is not None: - _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CollectionUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionUsage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'CollectionUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Completions(): - """ - An object containing an array of autocompletion suggestions. - - :attr List[str] completions: (optional) Array of autcomplete suggestion based on - the provided prefix. - """ - - def __init__(self, *, completions: List[str] = None) -> None: - """ - Initialize a Completions object. - - :param List[str] completions: (optional) Array of autcomplete suggestion - based on the provided prefix. - """ - self.completions = completions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" - args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Completions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'completions') and self.completions is not None: - _dict['completions'] = self.completions - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Completions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Completions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Completions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Configuration(): - """ - A custom configuration for the environment. - - :attr str configuration_id: (optional) The unique identifier of the - configuration. - :attr str name: The name of the configuration. - :attr datetime created: (optional) The creation date of the configuration in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the configuration was - last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str description: (optional) The description of the configuration, if - available. - :attr Conversions conversions: (optional) Document conversion settings. - :attr List[Enrichment] enrichments: (optional) An array of document enrichment - settings for the configuration. - :attr List[NormalizationOperation] normalizations: (optional) Defines operations - that can be used to transform the final output JSON into a normalized form. - Operations are executed in the order that they appear in the array. - :attr Source source: (optional) Object containing source parameters for the - configuration. - """ - - def __init__(self, - name: str, - *, - configuration_id: str = None, - created: datetime = None, - updated: datetime = None, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None) -> None: - """ - Initialize a Configuration object. - - :param str name: The name of the configuration. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - """ - self.configuration_id = configuration_id - self.name = name - self.created = created - self.updated = updated - self.description = description - self.conversions = conversions - self.enrichments = enrichments - self.normalizations = normalizations - self.source = source - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Configuration': - """Initialize a Configuration object from a json dictionary.""" - args = {} - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in Configuration JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'conversions' in _dict: - args['conversions'] = Conversions.from_dict( - _dict.get('conversions')) - if 'enrichments' in _dict: - args['enrichments'] = [ - Enrichment.from_dict(x) for x in _dict.get('enrichments') - ] - if 'normalizations' in _dict: - args['normalizations'] = [ - NormalizationOperation.from_dict(x) - for x in _dict.get('normalizations') - ] - if 'source' in _dict: - args['source'] = Source.from_dict(_dict.get('source')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Configuration object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'configuration_id') and getattr( - self, 'configuration_id') is not None: - _dict['configuration_id'] = getattr(self, 'configuration_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'conversions') and self.conversions is not None: - _dict['conversions'] = self.conversions.to_dict() - if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] - if hasattr(self, 'normalizations') and self.normalizations is not None: - _dict['normalizations'] = [x.to_dict() for x in self.normalizations] - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Configuration object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Configuration') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Configuration') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Conversions(): - """ - Document conversion settings. - - :attr PdfSettings pdf: (optional) A list of PDF conversion settings. - :attr WordSettings word: (optional) A list of Word conversion settings. - :attr HtmlSettings html: (optional) A list of HTML conversion settings. - :attr SegmentSettings segment: (optional) A list of Document Segmentation - settings. - :attr List[NormalizationOperation] json_normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a normalized - form. Operations are executed in the order that they appear in the array. - :attr bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) is - performed on documents uploaded to the collection. This field is supported on - **Advanced** and higher plans only. **Lite** plans do not support image text - recognition. - """ - - def __init__(self, - *, - pdf: 'PdfSettings' = None, - word: 'WordSettings' = None, - html: 'HtmlSettings' = None, - segment: 'SegmentSettings' = None, - json_normalizations: List['NormalizationOperation'] = None, - image_text_recognition: bool = None) -> None: - """ - Initialize a Conversions object. - - :param PdfSettings pdf: (optional) A list of PDF conversion settings. - :param WordSettings word: (optional) A list of Word conversion settings. - :param HtmlSettings html: (optional) A list of HTML conversion settings. - :param SegmentSettings segment: (optional) A list of Document Segmentation - settings. - :param List[NormalizationOperation] json_normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) - is performed on documents uploaded to the collection. This field is - supported on **Advanced** and higher plans only. **Lite** plans do not - support image text recognition. - """ - self.pdf = pdf - self.word = word - self.html = html - self.segment = segment - self.json_normalizations = json_normalizations - self.image_text_recognition = image_text_recognition - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Conversions': - """Initialize a Conversions object from a json dictionary.""" - args = {} - if 'pdf' in _dict: - args['pdf'] = PdfSettings.from_dict(_dict.get('pdf')) - if 'word' in _dict: - args['word'] = WordSettings.from_dict(_dict.get('word')) - if 'html' in _dict: - args['html'] = HtmlSettings.from_dict(_dict.get('html')) - if 'segment' in _dict: - args['segment'] = SegmentSettings.from_dict(_dict.get('segment')) - if 'json_normalizations' in _dict: - args['json_normalizations'] = [ - NormalizationOperation.from_dict(x) - for x in _dict.get('json_normalizations') - ] - if 'image_text_recognition' in _dict: - args['image_text_recognition'] = _dict.get('image_text_recognition') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Conversions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'pdf') and self.pdf is not None: - _dict['pdf'] = self.pdf.to_dict() - if hasattr(self, 'word') and self.word is not None: - _dict['word'] = self.word.to_dict() - if hasattr(self, 'html') and self.html is not None: - _dict['html'] = self.html.to_dict() - if hasattr(self, 'segment') and self.segment is not None: - _dict['segment'] = self.segment.to_dict() - if hasattr( - self, - 'json_normalizations') and self.json_normalizations is not None: - _dict['json_normalizations'] = [ - x.to_dict() for x in self.json_normalizations - ] - if hasattr(self, 'image_text_recognition' - ) and self.image_text_recognition is not None: - _dict['image_text_recognition'] = self.image_text_recognition - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Conversions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Conversions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Conversions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CreateEventResponse(): - """ - An object defining the event being created. - - :attr str type: (optional) The event type that was created. - :attr EventData data: (optional) Query event data object. - """ - - def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: - """ - Initialize a CreateEventResponse object. - - :param str type: (optional) The event type that was created. - :param EventData data: (optional) Query event data object. - """ - self.type = type - self.data = data - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': - """Initialize a CreateEventResponse object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'data' in _dict: - args['data'] = EventData.from_dict(_dict.get('data')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CreateEventResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CreateEventResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CreateEventResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'CreateEventResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The event type that was created. - """ - CLICK = 'click' - - -class CredentialDetails(): - """ - Object containing details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - - :attr str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be supported by - the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: - `aws4_hmac`. - :attr str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. - :attr str enterprise_id: (optional) The **enterprise_id** of the Box site that - these credentials connect to. Only valid, and required, with a **source_type** - of `box`. - :attr str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. - :attr str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - :attr str organization_url: (optional) The **organization_url** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :attr str site_collection_path: (optional) The **site_collection.path** of the - source that these credentials connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - :attr str client_secret: (optional) The **client_secret** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only used - when creating or modifying **credentials**. - :attr str public_key_id: (optional) The **public_key_id** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only used - when creating or modifying **credentials**. - :attr str private_key: (optional) The **private_key** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :attr str passphrase: (optional) The **passphrase** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :attr str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password - consists of the Salesforce password and a valid Salesforce security token - concatenated. This value is never returned and is only used when creating or - modifying **credentials**. - :attr str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a - **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created - using the `/v1/environments/{environment_id}/gateways` methods. - :attr str source_version: (optional) The type of Sharepoint repository to - connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :attr str web_application_url: (optional) SharePoint OnPrem WebApplication URL. - Only valid, and required, with a **source_version** of `2016`. If a port is not - supplied, the default to port `80` for http and port `443` for https connections - are used. - :attr str domain: (optional) The domain used to log in to your OnPrem SharePoint - account. Only valid, and required, with a **source_version** of `2016`. - :attr str endpoint: (optional) The endpoint associated with the cloud object - store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :attr str access_key_id: (optional) The access key ID associated with the cloud - object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :attr str secret_access_key: (optional) The secret access key associated with - the cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - """ - - def __init__(self, - *, - credential_type: str = None, - client_id: str = None, - enterprise_id: str = None, - url: str = None, - username: str = None, - organization_url: str = None, - site_collection_path: str = None, - client_secret: str = None, - public_key_id: str = None, - private_key: str = None, - passphrase: str = None, - password: str = None, - gateway_id: str = None, - source_version: str = None, - web_application_url: str = None, - domain: str = None, - endpoint: str = None, - access_key_id: str = None, - secret_access_key: str = None) -> None: - """ - Initialize a CredentialDetails object. - - :param str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be - supported by the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: - `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of - `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or - `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: - `aws4_hmac`. - :param str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. - :param str enterprise_id: (optional) The **enterprise_id** of the Box site - that these credentials connect to. Only valid, and required, with a - **source_type** of `box`. - :param str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. - :param str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a - **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. - :param str organization_url: (optional) The **organization_url** of the - source that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :param str site_collection_path: (optional) The **site_collection.path** of - the source that these credentials connect to. Only valid, and required, - with a **source_type** of `sharepoint`. - :param str client_secret: (optional) The **client_secret** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str public_key_id: (optional) The **public_key_id** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str private_key: (optional) The **private_key** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str passphrase: (optional) The **passphrase** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s - of `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password - consists of the Salesforce password and a valid Salesforce security token - concatenated. This value is never returned and is only used when creating - or modifying **credentials**. - :param str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a - **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are - created using the `/v1/environments/{environment_id}/gateways` methods. - :param str source_version: (optional) The type of Sharepoint repository to - connect to. Only valid, and required, with a **source_type** of - `sharepoint`. - :param str web_application_url: (optional) SharePoint OnPrem WebApplication - URL. Only valid, and required, with a **source_version** of `2016`. If a - port is not supplied, the default to port `80` for http and port `443` for - https connections are used. - :param str domain: (optional) The domain used to log in to your OnPrem - SharePoint account. Only valid, and required, with a **source_version** of - `2016`. - :param str endpoint: (optional) The endpoint associated with the cloud - object store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :param str access_key_id: (optional) The access key ID associated with the - cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :param str secret_access_key: (optional) The secret access key associated - with the cloud object store. Only valid, and required, with a - **credential_type** of `aws4_hmac`. This value is never returned and is - only used when creating or modifying **credentials**. For more infomation, - see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - """ - self.credential_type = credential_type - self.client_id = client_id - self.enterprise_id = enterprise_id - self.url = url - self.username = username - self.organization_url = organization_url - self.site_collection_path = site_collection_path - self.client_secret = client_secret - self.public_key_id = public_key_id - self.private_key = private_key - self.passphrase = passphrase - self.password = password - self.gateway_id = gateway_id - self.source_version = source_version - self.web_application_url = web_application_url - self.domain = domain - self.endpoint = endpoint - self.access_key_id = access_key_id - self.secret_access_key = secret_access_key - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CredentialDetails': - """Initialize a CredentialDetails object from a json dictionary.""" - args = {} - if 'credential_type' in _dict: - args['credential_type'] = _dict.get('credential_type') - if 'client_id' in _dict: - args['client_id'] = _dict.get('client_id') - if 'enterprise_id' in _dict: - args['enterprise_id'] = _dict.get('enterprise_id') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'username' in _dict: - args['username'] = _dict.get('username') - if 'organization_url' in _dict: - args['organization_url'] = _dict.get('organization_url') - if 'site_collection.path' in _dict: - args['site_collection_path'] = _dict.get('site_collection.path') - if 'client_secret' in _dict: - args['client_secret'] = _dict.get('client_secret') - if 'public_key_id' in _dict: - args['public_key_id'] = _dict.get('public_key_id') - if 'private_key' in _dict: - args['private_key'] = _dict.get('private_key') - if 'passphrase' in _dict: - args['passphrase'] = _dict.get('passphrase') - if 'password' in _dict: - args['password'] = _dict.get('password') - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'source_version' in _dict: - args['source_version'] = _dict.get('source_version') - if 'web_application_url' in _dict: - args['web_application_url'] = _dict.get('web_application_url') - if 'domain' in _dict: - args['domain'] = _dict.get('domain') - if 'endpoint' in _dict: - args['endpoint'] = _dict.get('endpoint') - if 'access_key_id' in _dict: - args['access_key_id'] = _dict.get('access_key_id') - if 'secret_access_key' in _dict: - args['secret_access_key'] = _dict.get('secret_access_key') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CredentialDetails object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'credential_type') and self.credential_type is not None: - _dict['credential_type'] = self.credential_type - if hasattr(self, 'client_id') and self.client_id is not None: - _dict['client_id'] = self.client_id - if hasattr(self, 'enterprise_id') and self.enterprise_id is not None: - _dict['enterprise_id'] = self.enterprise_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'username') and self.username is not None: - _dict['username'] = self.username - if hasattr(self, - 'organization_url') and self.organization_url is not None: - _dict['organization_url'] = self.organization_url - if hasattr(self, 'site_collection_path' - ) and self.site_collection_path is not None: - _dict['site_collection.path'] = self.site_collection_path - if hasattr(self, 'client_secret') and self.client_secret is not None: - _dict['client_secret'] = self.client_secret - if hasattr(self, 'public_key_id') and self.public_key_id is not None: - _dict['public_key_id'] = self.public_key_id - if hasattr(self, 'private_key') and self.private_key is not None: - _dict['private_key'] = self.private_key - if hasattr(self, 'passphrase') and self.passphrase is not None: - _dict['passphrase'] = self.passphrase - if hasattr(self, 'password') and self.password is not None: - _dict['password'] = self.password - if hasattr(self, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'source_version') and self.source_version is not None: - _dict['source_version'] = self.source_version - if hasattr( - self, - 'web_application_url') and self.web_application_url is not None: - _dict['web_application_url'] = self.web_application_url - if hasattr(self, 'domain') and self.domain is not None: - _dict['domain'] = self.domain - if hasattr(self, 'endpoint') and self.endpoint is not None: - _dict['endpoint'] = self.endpoint - if hasattr(self, 'access_key_id') and self.access_key_id is not None: - _dict['access_key_id'] = self.access_key_id - if hasattr(self, - 'secret_access_key') and self.secret_access_key is not None: - _dict['secret_access_key'] = self.secret_access_key - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CredentialDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CredentialDetails') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'CredentialDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CredentialTypeEnum(str, Enum): - """ - The authentication method for this credentials definition. The - **credential_type** specified must be supported by the **source_type**. The - following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - """ - OAUTH2 = 'oauth2' - SAML = 'saml' - USERNAME_PASSWORD = 'username_password' - NOAUTH = 'noauth' - BASIC = 'basic' - NTLM_V1 = 'ntlm_v1' - AWS4_HMAC = 'aws4_hmac' - - class SourceVersionEnum(str, Enum): - """ - The type of Sharepoint repository to connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - """ - ONLINE = 'online' - - -class Credentials(): - """ - Object containing credential information. - - :attr str credential_id: (optional) Unique identifier for this set of - credentials. - :attr str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an - IBM Cloud Object Store. - :attr CredentialDetails credential_details: (optional) Object containing details - of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :attr StatusDetails status: (optional) Object that contains details about the - status of the authentication process. - """ - - def __init__(self, - *, - credential_id: str = None, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None) -> None: - """ - Initialize a Credentials object. - - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - """ - self.credential_id = credential_id - self.source_type = source_type - self.credential_details = credential_details - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Credentials': - """Initialize a Credentials object from a json dictionary.""" - args = {} - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'source_type' in _dict: - args['source_type'] = _dict.get('source_type') - if 'credential_details' in _dict: - args['credential_details'] = CredentialDetails.from_dict( - _dict.get('credential_details')) - if 'status' in _dict: - args['status'] = StatusDetails.from_dict(_dict.get('status')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Credentials object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'credential_id') and getattr( - self, 'credential_id') is not None: - _dict['credential_id'] = getattr(self, 'credential_id') - if hasattr(self, 'source_type') and self.source_type is not None: - _dict['source_type'] = self.source_type - if hasattr( - self, - 'credential_details') and self.credential_details is not None: - _dict['credential_details'] = self.credential_details.to_dict() - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Credentials object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Credentials') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Credentials') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SourceTypeEnum(str, Enum): - """ - The source that this credentials object connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - """ - BOX = 'box' - SALESFORCE = 'salesforce' - SHAREPOINT = 'sharepoint' - WEB_CRAWL = 'web_crawl' - CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - - -class CredentialsList(): - """ - Object containing array of credential definitions. - - :attr List[Credentials] credentials: (optional) An array of credential - definitions that were created for this instance. - """ - - def __init__(self, *, credentials: List['Credentials'] = None) -> None: - """ - Initialize a CredentialsList object. - - :param List[Credentials] credentials: (optional) An array of credential - definitions that were created for this instance. - """ - self.credentials = credentials - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CredentialsList': - """Initialize a CredentialsList object from a json dictionary.""" - args = {} - if 'credentials' in _dict: - args['credentials'] = [ - Credentials.from_dict(x) for x in _dict.get('credentials') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CredentialsList object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = [x.to_dict() for x in self.credentials] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CredentialsList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CredentialsList') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'CredentialsList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DeleteCollectionResponse(): - """ - Response object returned when deleting a colleciton. - - :attr str collection_id: The unique identifier of the collection that is being - deleted. - :attr str status: The status of the collection. The status of a successful - deletion operation is `deleted`. - """ - - def __init__(self, collection_id: str, status: str) -> None: - """ - Initialize a DeleteCollectionResponse object. - - :param str collection_id: The unique identifier of the collection that is - being deleted. - :param str status: The status of the collection. The status of a successful - deletion operation is `deleted`. - """ - self.collection_id = collection_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': - """Initialize a DeleteCollectionResponse object from a json dictionary.""" - args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - else: - raise ValueError( - 'Required property \'collection_id\' not present in DeleteCollectionResponse JSON' - ) - if 'status' in _dict: - args['status'] = _dict.get('status') - else: - raise ValueError( - 'Required property \'status\' not present in DeleteCollectionResponse JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteCollectionResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteCollectionResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteCollectionResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DeleteCollectionResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the collection. The status of a successful deletion operation is - `deleted`. - """ - DELETED = 'deleted' - - -class DeleteConfigurationResponse(): - """ - Information returned when a configuration is deleted. - - :attr str configuration_id: The unique identifier for the configuration. - :attr str status: Status of the configuration. A deleted configuration has the - status deleted. - :attr List[Notice] notices: (optional) An array of notice messages, if any. - """ - - def __init__(self, - configuration_id: str, - status: str, - *, - notices: List['Notice'] = None) -> None: - """ - Initialize a DeleteConfigurationResponse object. - - :param str configuration_id: The unique identifier for the configuration. - :param str status: Status of the configuration. A deleted configuration has - the status deleted. - :param List[Notice] notices: (optional) An array of notice messages, if - any. - """ - self.configuration_id = configuration_id - self.status = status - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': - """Initialize a DeleteConfigurationResponse object from a json dictionary.""" - args = {} - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - else: - raise ValueError( - 'Required property \'configuration_id\' not present in DeleteConfigurationResponse JSON' - ) - if 'status' in _dict: - args['status'] = _dict.get('status') - else: - raise ValueError( - 'Required property \'status\' not present in DeleteConfigurationResponse JSON' - ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteConfigurationResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteConfigurationResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteConfigurationResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DeleteConfigurationResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the configuration. A deleted configuration has the status deleted. - """ - DELETED = 'deleted' - - -class DeleteCredentials(): - """ - Object returned after credentials are deleted. - - :attr str credential_id: (optional) The unique identifier of the credentials - that have been deleted. - :attr str status: (optional) The status of the deletion request. - """ - - def __init__(self, - *, - credential_id: str = None, - status: str = None) -> None: - """ - Initialize a DeleteCredentials object. - - :param str credential_id: (optional) The unique identifier of the - credentials that have been deleted. - :param str status: (optional) The status of the deletion request. - """ - self.credential_id = credential_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': - """Initialize a DeleteCredentials object from a json dictionary.""" - args = {} - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteCredentials object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'credential_id') and self.credential_id is not None: - _dict['credential_id'] = self.credential_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteCredentials object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteCredentials') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DeleteCredentials') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the deletion request. - """ - DELETED = 'deleted' - - -class DeleteDocumentResponse(): - """ - Information returned when a document is deleted. - - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the - status deleted. - """ - - def __init__(self, *, document_id: str = None, status: str = None) -> None: - """ - Initialize a DeleteDocumentResponse object. - - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. - """ - self.document_id = document_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" - args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteDocumentResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteDocumentResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DeleteDocumentResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - DELETED = 'deleted' - - -class DeleteEnvironmentResponse(): - """ - Response object returned when deleting an environment. - - :attr str environment_id: The unique identifier for the environment. - :attr str status: Status of the environment. - """ - - def __init__(self, environment_id: str, status: str) -> None: - """ - Initialize a DeleteEnvironmentResponse object. - - :param str environment_id: The unique identifier for the environment. - :param str status: Status of the environment. - """ - self.environment_id = environment_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': - """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" - args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - else: - raise ValueError( - 'Required property \'environment_id\' not present in DeleteEnvironmentResponse JSON' - ) - if 'status' in _dict: - args['status'] = _dict.get('status') - else: - raise ValueError( - 'Required property \'status\' not present in DeleteEnvironmentResponse JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteEnvironmentResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteEnvironmentResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DeleteEnvironmentResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the environment. - """ - DELETED = 'deleted' - - -class DiskUsage(): - """ - Summary of the disk usage statistics for the environment. - - :attr int used_bytes: (optional) Number of bytes within the environment's disk - capacity that are currently used to store data. - :attr int maximum_allowed_bytes: (optional) Total number of bytes available in - the environment's disk capacity. - """ - - def __init__(self, - *, - used_bytes: int = None, - maximum_allowed_bytes: int = None) -> None: - """ - Initialize a DiskUsage object. - - """ - self.used_bytes = used_bytes - self.maximum_allowed_bytes = maximum_allowed_bytes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DiskUsage': - """Initialize a DiskUsage object from a json dictionary.""" - args = {} - if 'used_bytes' in _dict: - args['used_bytes'] = _dict.get('used_bytes') - if 'maximum_allowed_bytes' in _dict: - args['maximum_allowed_bytes'] = _dict.get('maximum_allowed_bytes') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DiskUsage object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'used_bytes') and getattr(self, - 'used_bytes') is not None: - _dict['used_bytes'] = getattr(self, 'used_bytes') - if hasattr(self, 'maximum_allowed_bytes') and getattr( - self, 'maximum_allowed_bytes') is not None: - _dict['maximum_allowed_bytes'] = getattr(self, - 'maximum_allowed_bytes') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DiskUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DiskUsage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DiskUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentAccepted(): - """ - Information returned after an uploaded document is accepted. - - :attr str document_id: (optional) The unique identifier of the ingested - document. - :attr str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. - :attr List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - - def __init__(self, - *, - document_id: str = None, - status: str = None, - notices: List['Notice'] = None) -> None: - """ - Initialize a DocumentAccepted object. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - self.document_id = document_id - self.status = status - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" - args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentAccepted object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentAccepted') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DocumentAccepted') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. - """ - PROCESSING = 'processing' - PENDING = 'pending' - - -class DocumentCounts(): - """ - Object containing collection document count information. - - :attr int available: (optional) The total number of available documents in the - collection. - :attr int processing: (optional) The number of documents in the collection that - are currently being processed. - :attr int failed: (optional) The number of documents in the collection that - failed to be ingested. - :attr int pending: (optional) The number of documents that have been uploaded to - the collection, but have not yet started processing. - """ - - def __init__(self, - *, - available: int = None, - processing: int = None, - failed: int = None, - pending: int = None) -> None: - """ - Initialize a DocumentCounts object. - - """ - self.available = available - self.processing = processing - self.failed = failed - self.pending = pending - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentCounts': - """Initialize a DocumentCounts object from a json dictionary.""" - args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'failed' in _dict: - args['failed'] = _dict.get('failed') - if 'pending' in _dict: - args['pending'] = _dict.get('pending') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentCounts object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'processing') and getattr(self, - 'processing') is not None: - _dict['processing'] = getattr(self, 'processing') - if hasattr(self, 'failed') and getattr(self, 'failed') is not None: - _dict['failed'] = getattr(self, 'failed') - if hasattr(self, 'pending') and getattr(self, 'pending') is not None: - _dict['pending'] = getattr(self, 'pending') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentCounts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentCounts') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DocumentCounts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentStatus(): - """ - Status information about a submitted document. - - :attr str document_id: (optional) The unique identifier of the document. - :attr str configuration_id: (optional) The unique identifier for the - configuration. - :attr str status: (optional) Status of the document in the ingestion process. - :attr str status_description: (optional) Description of the document status. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - - def __init__(self, - *, - document_id: str = None, - configuration_id: str = None, - status: str = None, - status_description: str = None, - filename: str = None, - file_type: str = None, - sha1: str = None, - notices: List['Notice'] = None) -> None: - """ - Initialize a DocumentStatus object. - - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - """ - self.document_id = document_id - self.configuration_id = configuration_id - self.status = status - self.status_description = status_description - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentStatus': - """Initialize a DocumentStatus object from a json dictionary.""" - args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and getattr(self, - 'document_id') is not None: - _dict['document_id'] = getattr(self, 'document_id') - if hasattr(self, 'configuration_id') and getattr( - self, 'configuration_id') is not None: - _dict['configuration_id'] = getattr(self, 'configuration_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and getattr(self, 'notices') is not None: - _dict['notices'] = [x.to_dict() for x in getattr(self, 'notices')] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DocumentStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document in the ingestion process. - """ - AVAILABLE = 'available' - AVAILABLE_WITH_NOTICES = 'available with notices' - FAILED = 'failed' - PROCESSING = 'processing' - PENDING = 'pending' - - class FileTypeEnum(str, Enum): - """ - The type of the original source file. - """ - PDF = 'pdf' - HTML = 'html' - WORD = 'word' - JSON = 'json' - - -class Enrichment(): - """ - Enrichment step to perform on the document. Each enrichment is performed on the - specified field in the order that they are listed in the configuration. - - :attr str description: (optional) Describes what the enrichment step does. - :attr str destination_field: Field where enrichments will be stored. This field - must already exist or be at most 1 level deeper than an existing field. For - example, if `text` is a top-level field with no sub-fields, `text.foo` is a - valid destination but `text.foo.bar` is not. - :attr str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** service - for this enrichment is set to `natural_language_undstanding`. - :attr bool overwrite: (optional) Indicates that the enrichments will overwrite - the destination_field field if it already exists. - :attr str enrichment: Name of the enrichment service to call. The only supported - option is `natural_language_understanding`. The `elements` option is deprecated - and support ended on 10 July 2020. - The **options** object must contain Natural Language Understanding options. - :attr bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and will not - cause the document to fail processing. - :attr EnrichmentOptions options: (optional) Options that are specific to a - particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of - the Discovery v2 API to create a `content_intelligence` project type instead. - """ - - def __init__(self, - destination_field: str, - source_field: str, - enrichment: str, - *, - description: str = None, - overwrite: bool = None, - ignore_downstream_errors: bool = None, - options: 'EnrichmentOptions' = None) -> None: - """ - Initialize a Enrichment object. - - :param str destination_field: Field where enrichments will be stored. This - field must already exist or be at most 1 level deeper than an existing - field. For example, if `text` is a top-level field with no sub-fields, - `text.foo` is a valid destination but `text.foo.bar` is not. - :param str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** - service for this enrichment is set to `natural_language_undstanding`. - :param str enrichment: Name of the enrichment service to call. The only - supported option is `natural_language_understanding`. The `elements` option - is deprecated and support ended on 10 July 2020. - The **options** object must contain Natural Language Understanding - options. - :param str description: (optional) Describes what the enrichment step does. - :param bool overwrite: (optional) Indicates that the enrichments will - overwrite the destination_field field if it already exists. - :param bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and - will not cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options that are specific to a - particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method - of the Discovery v2 API to create a `content_intelligence` project type - instead. - """ - self.description = description - self.destination_field = destination_field - self.source_field = source_field - self.overwrite = overwrite - self.enrichment = enrichment - self.ignore_downstream_errors = ignore_downstream_errors - self.options = options - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Enrichment': - """Initialize a Enrichment object from a json dictionary.""" - args = {} - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'destination_field' in _dict: - args['destination_field'] = _dict.get('destination_field') - else: - raise ValueError( - 'Required property \'destination_field\' not present in Enrichment JSON' - ) - if 'source_field' in _dict: - args['source_field'] = _dict.get('source_field') - else: - raise ValueError( - 'Required property \'source_field\' not present in Enrichment JSON' - ) - if 'overwrite' in _dict: - args['overwrite'] = _dict.get('overwrite') - if 'enrichment' in _dict: - args['enrichment'] = _dict.get('enrichment') - else: - raise ValueError( - 'Required property \'enrichment\' not present in Enrichment JSON' - ) - if 'ignore_downstream_errors' in _dict: - args['ignore_downstream_errors'] = _dict.get( - 'ignore_downstream_errors') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Enrichment object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, - 'destination_field') and self.destination_field is not None: - _dict['destination_field'] = self.destination_field - if hasattr(self, 'source_field') and self.source_field is not None: - _dict['source_field'] = self.source_field - if hasattr(self, 'overwrite') and self.overwrite is not None: - _dict['overwrite'] = self.overwrite - if hasattr(self, 'enrichment') and self.enrichment is not None: - _dict['enrichment'] = self.enrichment - if hasattr(self, 'ignore_downstream_errors' - ) and self.ignore_downstream_errors is not None: - _dict['ignore_downstream_errors'] = self.ignore_downstream_errors - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Enrichment object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Enrichment') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Enrichment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EnrichmentOptions(): - """ - Options that are specific to a particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the - Discovery v2 API to create a `content_intelligence` project type instead. - - :attr NluEnrichmentFeatures features: (optional) Object containing Natural - Language Understanding features to be used. - :attr str language: (optional) ISO 639-1 code indicating the language to use for - the analysis. This code overrides the automatic language detection performed by - the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` - (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and - `sv` (Swedish). **Note:** Not all features support all languages, automatic - detection is recommended. - :attr str model: (optional) The element extraction model to use, which can be - `contract` only. The `elements` enrichment is deprecated. - """ - - def __init__(self, - *, - features: 'NluEnrichmentFeatures' = None, - language: str = None, - model: str = None) -> None: - """ - Initialize a EnrichmentOptions object. - - :param NluEnrichmentFeatures features: (optional) Object containing Natural - Language Understanding features to be used. - :param str language: (optional) ISO 639-1 code indicating the language to - use for the analysis. This code overrides the automatic language detection - performed by the service. Valid codes are `ar` (Arabic), `en` (English), - `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` - (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features - support all languages, automatic detection is recommended. - :param str model: (optional) The element extraction model to use, which can - be `contract` only. The `elements` enrichment is deprecated. - """ - self.features = features - self.language = language - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': - """Initialize a EnrichmentOptions object from a json dictionary.""" - args = {} - if 'features' in _dict: - args['features'] = NluEnrichmentFeatures.from_dict( - _dict.get('features')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'model' in _dict: - args['model'] = _dict.get('model') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EnrichmentOptions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'features') and self.features is not None: - _dict['features'] = self.features.to_dict() - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this EnrichmentOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EnrichmentOptions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'EnrichmentOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class LanguageEnum(str, Enum): - """ - ISO 639-1 code indicating the language to use for the analysis. This code - overrides the automatic language detection performed by the service. Valid codes - are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), - `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** - Not all features support all languages, automatic detection is recommended. - """ - AR = 'ar' - EN = 'en' - FR = 'fr' - DE = 'de' - IT = 'it' - PT = 'pt' - RU = 'ru' - ES = 'es' - SV = 'sv' - - -class Environment(): - """ - Details about an environment. - - :attr str environment_id: (optional) Unique identifier for the environment. - :attr str name: (optional) Name that identifies the environment. - :attr str description: (optional) Description of the environment. - :attr datetime created: (optional) Creation date of the environment, in the - format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr datetime updated: (optional) Date of most recent environment update, in - the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr str status: (optional) Current status of the environment. `resizing` is - displayed when a request to increase the environment size has been made, but is - still in the process of being completed. - :attr bool read_only: (optional) If `true`, the environment contains read-only - collections that are maintained by IBM. - :attr str size: (optional) Current size of the environment. - :attr str requested_size: (optional) The new size requested for this - environment. Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment - upsize. - :attr IndexCapacity index_capacity: (optional) Details about the resource usage - and capacity of the environment. - :attr SearchStatus search_status: (optional) Information about the Continuous - Relevancy Training for this environment. - """ - - def __init__(self, - *, - environment_id: str = None, - name: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - read_only: bool = None, - size: str = None, - requested_size: str = None, - index_capacity: 'IndexCapacity' = None, - search_status: 'SearchStatus' = None) -> None: - """ - Initialize a Environment object. - - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Current size of the environment. - :param str requested_size: (optional) The new size requested for this - environment. Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment - upsize. - :param IndexCapacity index_capacity: (optional) Details about the resource - usage and capacity of the environment. - :param SearchStatus search_status: (optional) Information about the - Continuous Relevancy Training for this environment. - """ - self.environment_id = environment_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.status = status - self.read_only = read_only - self.size = size - self.requested_size = requested_size - self.index_capacity = index_capacity - self.search_status = search_status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Environment': - """Initialize a Environment object from a json dictionary.""" - args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'read_only' in _dict: - args['read_only'] = _dict.get('read_only') - if 'size' in _dict: - args['size'] = _dict.get('size') - if 'requested_size' in _dict: - args['requested_size'] = _dict.get('requested_size') - if 'index_capacity' in _dict: - args['index_capacity'] = IndexCapacity.from_dict( - _dict.get('index_capacity')) - if 'search_status' in _dict: - args['search_status'] = SearchStatus.from_dict( - _dict.get('search_status')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Environment object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'read_only') and getattr(self, - 'read_only') is not None: - _dict['read_only'] = getattr(self, 'read_only') - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'requested_size') and self.requested_size is not None: - _dict['requested_size'] = self.requested_size - if hasattr(self, 'index_capacity') and self.index_capacity is not None: - _dict['index_capacity'] = self.index_capacity.to_dict() - if hasattr(self, 'search_status') and self.search_status is not None: - _dict['search_status'] = self.search_status.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Environment object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Environment') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Environment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Current status of the environment. `resizing` is displayed when a request to - increase the environment size has been made, but is still in the process of being - completed. - """ - ACTIVE = 'active' - PENDING = 'pending' - MAINTENANCE = 'maintenance' - RESIZING = 'resizing' - - class SizeEnum(str, Enum): - """ - Current size of the environment. - """ - LT = 'LT' - XS = 'XS' - S = 'S' - MS = 'MS' - M = 'M' - ML = 'ML' - L = 'L' - XL = 'XL' - XXL = 'XXL' - XXXL = 'XXXL' - - -class EnvironmentDocuments(): - """ - Summary of the document usage statistics for the environment. - - :attr int available: (optional) Number of documents indexed for the environment. - :attr int maximum_allowed: (optional) Total number of documents allowed in the - environment's capacity. - """ - - def __init__(self, - *, - available: int = None, - maximum_allowed: int = None) -> None: - """ - Initialize a EnvironmentDocuments object. - - """ - self.available = available - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': - """Initialize a EnvironmentDocuments object from a json dictionary.""" - args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EnvironmentDocuments object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'maximum_allowed') and getattr( - self, 'maximum_allowed') is not None: - _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this EnvironmentDocuments object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EnvironmentDocuments') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'EnvironmentDocuments') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EventData(): - """ - Query event data object. - - :attr str environment_id: The **environment_id** associated with the query that - the event is associated with. - :attr str session_token: The session token that was returned as part of the - query results that this event is associated with. - :attr datetime client_timestamp: (optional) The optional timestamp for the event - that was created. If not provided, the time that the event was created in the - log was used. - :attr int display_rank: (optional) The rank of the result item which the event - is associated with. - :attr str collection_id: The **collection_id** of the document that this event - is associated with. - :attr str document_id: The **document_id** of the document that this event is - associated with. - :attr str query_id: (optional) The query identifier stored in the log. The query - and any events associated with that query are stored with the same **query_id**. - """ - - def __init__(self, - environment_id: str, - session_token: str, - collection_id: str, - document_id: str, - *, - client_timestamp: datetime = None, - display_rank: int = None, - query_id: str = None) -> None: - """ - Initialize a EventData object. - - :param str environment_id: The **environment_id** associated with the query - that the event is associated with. - :param str session_token: The session token that was returned as part of - the query results that this event is associated with. - :param str collection_id: The **collection_id** of the document that this - event is associated with. - :param str document_id: The **document_id** of the document that this event - is associated with. - :param datetime client_timestamp: (optional) The optional timestamp for the - event that was created. If not provided, the time that the event was - created in the log was used. - :param int display_rank: (optional) The rank of the result item which the - event is associated with. - """ - self.environment_id = environment_id - self.session_token = session_token - self.client_timestamp = client_timestamp - self.display_rank = display_rank - self.collection_id = collection_id - self.document_id = document_id - self.query_id = query_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EventData': - """Initialize a EventData object from a json dictionary.""" - args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - else: - raise ValueError( - 'Required property \'environment_id\' not present in EventData JSON' - ) - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - else: - raise ValueError( - 'Required property \'session_token\' not present in EventData JSON' - ) - if 'client_timestamp' in _dict: - args['client_timestamp'] = string_to_datetime( - _dict.get('client_timestamp')) - if 'display_rank' in _dict: - args['display_rank'] = _dict.get('display_rank') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - else: - raise ValueError( - 'Required property \'collection_id\' not present in EventData JSON' - ) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - else: - raise ValueError( - 'Required property \'document_id\' not present in EventData JSON' - ) - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EventData object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, - 'client_timestamp') and self.client_timestamp is not None: - _dict['client_timestamp'] = datetime_to_string( - self.client_timestamp) - if hasattr(self, 'display_rank') and self.display_rank is not None: - _dict['display_rank'] = self.display_rank - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: - _dict['query_id'] = getattr(self, 'query_id') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this EventData object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EventData') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'EventData') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Expansion(): - """ - An expansion definition. Each object respresents one set of expandable strings. For - example, you could have expansions for the word `hot` in one object, and expansions - for the word `cold` in another. - - :attr List[str] input_terms: (optional) A list of terms that will be expanded - for this expansion. If specified, only the items in this list are expanded. - :attr List[str] expanded_terms: A list of terms that this expansion will be - expanded to. If specified without **input_terms**, it also functions as the - input term list. - """ - - def __init__(self, - expanded_terms: List[str], - *, - input_terms: List[str] = None) -> None: - """ - Initialize a Expansion object. - - :param List[str] expanded_terms: A list of terms that this expansion will - be expanded to. If specified without **input_terms**, it also functions as - the input term list. - :param List[str] input_terms: (optional) A list of terms that will be - expanded for this expansion. If specified, only the items in this list are - expanded. - """ - self.input_terms = input_terms - self.expanded_terms = expanded_terms - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Expansion': - """Initialize a Expansion object from a json dictionary.""" - args = {} - if 'input_terms' in _dict: - args['input_terms'] = _dict.get('input_terms') - if 'expanded_terms' in _dict: - args['expanded_terms'] = _dict.get('expanded_terms') - else: - raise ValueError( - 'Required property \'expanded_terms\' not present in Expansion JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Expansion object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'input_terms') and self.input_terms is not None: - _dict['input_terms'] = self.input_terms - if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: - _dict['expanded_terms'] = self.expanded_terms - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Expansion object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Expansion') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Expansion') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Expansions(): - """ - The query expansion definitions for the specified collection. - - :attr List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms that - will be expanded into other terms. Each expansion object can be configured as - bidirectional or unidirectional. Bidirectional means that all terms are expanded - to all other terms in the object. Unidirectional means that a set list of terms - can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. When - found in a query, all items in the **expanded_terms** array are then expanded to - the other items in the same array. - To create a uni-directional expansion, specify both an array of **input_terms** - and an array of **expanded_terms**. When items in the **input_terms** array are - present in a query, they are expanded using the items listed in the - **expanded_terms** array. - """ - - def __init__(self, expansions: List['Expansion']) -> None: - """ - Initialize a Expansions object. - - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms - that will be expanded into other terms. Each expansion object can be - configured as bidirectional or unidirectional. Bidirectional means that all - terms are expanded to all other terms in the object. Unidirectional means - that a set list of terms can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. - When found in a query, all items in the **expanded_terms** array are then - expanded to the other items in the same array. - To create a uni-directional expansion, specify both an array of - **input_terms** and an array of **expanded_terms**. When items in the - **input_terms** array are present in a query, they are expanded using the - items listed in the **expanded_terms** array. - """ - self.expansions = expansions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Expansions': - """Initialize a Expansions object from a json dictionary.""" - args = {} - if 'expansions' in _dict: - args['expansions'] = [ - Expansion.from_dict(x) for x in _dict.get('expansions') - ] - else: - raise ValueError( - 'Required property \'expansions\' not present in Expansions JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Expansions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'expansions') and self.expansions is not None: - _dict['expansions'] = [x.to_dict() for x in self.expansions] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Expansions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Expansions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Expansions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Field(): - """ - Object containing field details. - - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. - """ - - def __init__(self, *, field: str = None, type: str = None) -> None: - """ - Initialize a Field object. - - """ - self.field = field - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Field': - """Initialize a Field object from a json dictionary.""" - args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Field object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and getattr(self, 'field') is not None: - _dict['field'] = getattr(self, 'field') - if hasattr(self, 'type') and getattr(self, 'type') is not None: - _dict['type'] = getattr(self, 'type') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Field object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Field') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Field') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of the field. - """ - NESTED = 'nested' - STRING = 'string' - DATE = 'date' - LONG = 'long' - INTEGER = 'integer' - SHORT = 'short' - BYTE = 'byte' - DOUBLE = 'double' - FLOAT = 'float' - BOOLEAN = 'boolean' - BINARY = 'binary' - - -class FontSetting(): - """ - Font matching configuration. - - :attr int level: (optional) The HTML heading level that any content with the - matching font is converted to. - :attr int min_size: (optional) The minimum size of the font to match. - :attr int max_size: (optional) The maximum size of the font to match. - :attr bool bold: (optional) When `true`, the font is matched if it is bold. - :attr bool italic: (optional) When `true`, the font is matched if it is italic. - :attr str name: (optional) The name of the font. - """ - - def __init__(self, - *, - level: int = None, - min_size: int = None, - max_size: int = None, - bold: bool = None, - italic: bool = None, - name: str = None) -> None: - """ - Initialize a FontSetting object. - - :param int level: (optional) The HTML heading level that any content with - the matching font is converted to. - :param int min_size: (optional) The minimum size of the font to match. - :param int max_size: (optional) The maximum size of the font to match. - :param bool bold: (optional) When `true`, the font is matched if it is - bold. - :param bool italic: (optional) When `true`, the font is matched if it is - italic. - :param str name: (optional) The name of the font. - """ - self.level = level - self.min_size = min_size - self.max_size = max_size - self.bold = bold - self.italic = italic - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FontSetting': - """Initialize a FontSetting object from a json dictionary.""" - args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'min_size' in _dict: - args['min_size'] = _dict.get('min_size') - if 'max_size' in _dict: - args['max_size'] = _dict.get('max_size') - if 'bold' in _dict: - args['bold'] = _dict.get('bold') - if 'italic' in _dict: - args['italic'] = _dict.get('italic') - if 'name' in _dict: - args['name'] = _dict.get('name') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FontSetting object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'min_size') and self.min_size is not None: - _dict['min_size'] = self.min_size - if hasattr(self, 'max_size') and self.max_size is not None: - _dict['max_size'] = self.max_size - if hasattr(self, 'bold') and self.bold is not None: - _dict['bold'] = self.bold - if hasattr(self, 'italic') and self.italic is not None: - _dict['italic'] = self.italic - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this FontSetting object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FontSetting') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'FontSetting') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Gateway(): - """ - Object describing a specific gateway. - - :attr str gateway_id: (optional) The gateway ID of the gateway. - :attr str name: (optional) The user defined name of the gateway. - :attr str status: (optional) The current status of the gateway. `connected` - means the gateway is connected to the remotly installed gateway. `idle` means - this gateway is not currently in use. - :attr str token: (optional) The generated **token** for this gateway. The value - of this field is used when configuring the remotly installed gateway. - :attr str token_id: (optional) The generated **token_id** for this gateway. The - value of this field is used when configuring the remotly installed gateway. - """ - - def __init__(self, - *, - gateway_id: str = None, - name: str = None, - status: str = None, - token: str = None, - token_id: str = None) -> None: - """ - Initialize a Gateway object. - - :param str gateway_id: (optional) The gateway ID of the gateway. - :param str name: (optional) The user defined name of the gateway. - :param str status: (optional) The current status of the gateway. - `connected` means the gateway is connected to the remotly installed - gateway. `idle` means this gateway is not currently in use. - :param str token: (optional) The generated **token** for this gateway. The - value of this field is used when configuring the remotly installed gateway. - :param str token_id: (optional) The generated **token_id** for this - gateway. The value of this field is used when configuring the remotly - installed gateway. - """ - self.gateway_id = gateway_id - self.name = name - self.status = status - self.token = token - self.token_id = token_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Gateway': - """Initialize a Gateway object from a json dictionary.""" - args = {} - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'token' in _dict: - args['token'] = _dict.get('token') - if 'token_id' in _dict: - args['token_id'] = _dict.get('token_id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Gateway object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'token') and self.token is not None: - _dict['token'] = self.token - if hasattr(self, 'token_id') and self.token_id is not None: - _dict['token_id'] = self.token_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Gateway object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Gateway') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Gateway') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the gateway. `connected` means the gateway is connected to - the remotly installed gateway. `idle` means this gateway is not currently in use. - """ - CONNECTED = 'connected' - IDLE = 'idle' - - -class GatewayDelete(): - """ - Gatway deletion confirmation. - - :attr str gateway_id: (optional) The gateway ID of the deleted gateway. - :attr str status: (optional) The status of the request. - """ - - def __init__(self, *, gateway_id: str = None, status: str = None) -> None: - """ - Initialize a GatewayDelete object. - - :param str gateway_id: (optional) The gateway ID of the deleted gateway. - :param str status: (optional) The status of the request. - """ - self.gateway_id = gateway_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GatewayDelete': - """Initialize a GatewayDelete object from a json dictionary.""" - args = {} - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a GatewayDelete object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this GatewayDelete object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'GatewayDelete') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'GatewayDelete') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class GatewayList(): - """ - Object containing gateways array. - - :attr List[Gateway] gateways: (optional) Array of configured gateway - connections. - """ - - def __init__(self, *, gateways: List['Gateway'] = None) -> None: - """ - Initialize a GatewayList object. - - :param List[Gateway] gateways: (optional) Array of configured gateway - connections. - """ - self.gateways = gateways - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GatewayList': - """Initialize a GatewayList object from a json dictionary.""" - args = {} - if 'gateways' in _dict: - args['gateways'] = [ - Gateway.from_dict(x) for x in _dict.get('gateways') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a GatewayList object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'gateways') and self.gateways is not None: - _dict['gateways'] = [x.to_dict() for x in self.gateways] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this GatewayList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'GatewayList') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'GatewayList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class HtmlSettings(): - """ - A list of HTML conversion settings. - - :attr List[str] exclude_tags_completely: (optional) Array of HTML tags that are - excluded completely. - :attr List[str] exclude_tags_keep_content: (optional) Array of HTML tags which - are excluded but still retain content. - :attr XPathPatterns keep_content: (optional) Object containing an array of - XPaths. - :attr XPathPatterns exclude_content: (optional) Object containing an array of - XPaths. - :attr List[str] keep_tag_attributes: (optional) An array of HTML tag attributes - to keep in the converted document. - :attr List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes - to exclude. - """ - - def __init__(self, - *, - exclude_tags_completely: List[str] = None, - exclude_tags_keep_content: List[str] = None, - keep_content: 'XPathPatterns' = None, - exclude_content: 'XPathPatterns' = None, - keep_tag_attributes: List[str] = None, - exclude_tag_attributes: List[str] = None) -> None: - """ - Initialize a HtmlSettings object. - - :param List[str] exclude_tags_completely: (optional) Array of HTML tags - that are excluded completely. - :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags - which are excluded but still retain content. - :param XPathPatterns keep_content: (optional) Object containing an array of - XPaths. - :param XPathPatterns exclude_content: (optional) Object containing an array - of XPaths. - :param List[str] keep_tag_attributes: (optional) An array of HTML tag - attributes to keep in the converted document. - :param List[str] exclude_tag_attributes: (optional) Array of HTML tag - attributes to exclude. - """ - self.exclude_tags_completely = exclude_tags_completely - self.exclude_tags_keep_content = exclude_tags_keep_content - self.keep_content = keep_content - self.exclude_content = exclude_content - self.keep_tag_attributes = keep_tag_attributes - self.exclude_tag_attributes = exclude_tag_attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'HtmlSettings': - """Initialize a HtmlSettings object from a json dictionary.""" - args = {} - if 'exclude_tags_completely' in _dict: - args['exclude_tags_completely'] = _dict.get( - 'exclude_tags_completely') - if 'exclude_tags_keep_content' in _dict: - args['exclude_tags_keep_content'] = _dict.get( - 'exclude_tags_keep_content') - if 'keep_content' in _dict: - args['keep_content'] = XPathPatterns.from_dict( - _dict.get('keep_content')) - if 'exclude_content' in _dict: - args['exclude_content'] = XPathPatterns.from_dict( - _dict.get('exclude_content')) - if 'keep_tag_attributes' in _dict: - args['keep_tag_attributes'] = _dict.get('keep_tag_attributes') - if 'exclude_tag_attributes' in _dict: - args['exclude_tag_attributes'] = _dict.get('exclude_tag_attributes') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a HtmlSettings object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'exclude_tags_completely' - ) and self.exclude_tags_completely is not None: - _dict['exclude_tags_completely'] = self.exclude_tags_completely - if hasattr(self, 'exclude_tags_keep_content' - ) and self.exclude_tags_keep_content is not None: - _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content - if hasattr(self, 'keep_content') and self.keep_content is not None: - _dict['keep_content'] = self.keep_content.to_dict() - if hasattr(self, - 'exclude_content') and self.exclude_content is not None: - _dict['exclude_content'] = self.exclude_content.to_dict() - if hasattr( - self, - 'keep_tag_attributes') and self.keep_tag_attributes is not None: - _dict['keep_tag_attributes'] = self.keep_tag_attributes - if hasattr(self, 'exclude_tag_attributes' - ) and self.exclude_tag_attributes is not None: - _dict['exclude_tag_attributes'] = self.exclude_tag_attributes - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this HtmlSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'HtmlSettings') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'HtmlSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IndexCapacity(): - """ - Details about the resource usage and capacity of the environment. - - :attr EnvironmentDocuments documents: (optional) Summary of the document usage - statistics for the environment. - :attr DiskUsage disk_usage: (optional) Summary of the disk usage statistics for - the environment. - :attr CollectionUsage collections: (optional) Summary of the collection usage in - the environment. - """ - - def __init__(self, - *, - documents: 'EnvironmentDocuments' = None, - disk_usage: 'DiskUsage' = None, - collections: 'CollectionUsage' = None) -> None: - """ - Initialize a IndexCapacity object. - - :param EnvironmentDocuments documents: (optional) Summary of the document - usage statistics for the environment. - :param DiskUsage disk_usage: (optional) Summary of the disk usage - statistics for the environment. - :param CollectionUsage collections: (optional) Summary of the collection - usage in the environment. - """ - self.documents = documents - self.disk_usage = disk_usage - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IndexCapacity': - """Initialize a IndexCapacity object from a json dictionary.""" - args = {} - if 'documents' in _dict: - args['documents'] = EnvironmentDocuments.from_dict( - _dict.get('documents')) - if 'disk_usage' in _dict: - args['disk_usage'] = DiskUsage.from_dict(_dict.get('disk_usage')) - if 'collections' in _dict: - args['collections'] = CollectionUsage.from_dict( - _dict.get('collections')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IndexCapacity object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = self.documents.to_dict() - if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage.to_dict() - if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = self.collections.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IndexCapacity object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IndexCapacity') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'IndexCapacity') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListCollectionFieldsResponse(): - """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested JSON objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). - * Fields returned from the News collection are prefixed with - `v{N}-fullnews-t3-{YEAR}.mappings` (for example, - `v5-fullnews-t3-2016.mappings.text.properties.author`). - - :attr List[Field] fields: (optional) An array containing information about each - field in the collections. - """ - - def __init__(self, *, fields: List['Field'] = None) -> None: - """ - Initialize a ListCollectionFieldsResponse object. - - :param List[Field] fields: (optional) An array containing information about - each field in the collections. - """ - self.fields = fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': - """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" - args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListCollectionFieldsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListCollectionFieldsResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'ListCollectionFieldsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListCollectionsResponse(): - """ - Response object containing an array of collection details. - - :attr List[Collection] collections: (optional) An array containing information - about each collection in the environment. - """ - - def __init__(self, *, collections: List['Collection'] = None) -> None: - """ - Initialize a ListCollectionsResponse object. - - :param List[Collection] collections: (optional) An array containing - information about each collection in the environment. - """ - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" - args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListCollectionsResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListCollectionsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListCollectionsResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'ListCollectionsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListConfigurationsResponse(): - """ - Object containing an array of available configurations. - - :attr List[Configuration] configurations: (optional) An array of configurations - that are available for the service instance. - """ - - def __init__(self, *, configurations: List['Configuration'] = None) -> None: - """ - Initialize a ListConfigurationsResponse object. - - :param List[Configuration] configurations: (optional) An array of - configurations that are available for the service instance. - """ - self.configurations = configurations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': - """Initialize a ListConfigurationsResponse object from a json dictionary.""" - args = {} - if 'configurations' in _dict: - args['configurations'] = [ - Configuration.from_dict(x) for x in _dict.get('configurations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListConfigurationsResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'configurations') and self.configurations is not None: - _dict['configurations'] = [x.to_dict() for x in self.configurations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListConfigurationsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListConfigurationsResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'ListConfigurationsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListEnvironmentsResponse(): - """ - Response object containing an array of configured environments. - - :attr List[Environment] environments: (optional) An array of [environments] that - are available for the service instance. - """ - - def __init__(self, *, environments: List['Environment'] = None) -> None: - """ - Initialize a ListEnvironmentsResponse object. - - :param List[Environment] environments: (optional) An array of - [environments] that are available for the service instance. - """ - self.environments = environments - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': - """Initialize a ListEnvironmentsResponse object from a json dictionary.""" - args = {} - if 'environments' in _dict: - args['environments'] = [ - Environment.from_dict(x) for x in _dict.get('environments') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListEnvironmentsResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'environments') and self.environments is not None: - _dict['environments'] = [x.to_dict() for x in self.environments] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListEnvironmentsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListEnvironmentsResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'ListEnvironmentsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponse(): - """ - Object containing results that match the requested **logs** query. - - :attr int matching_results: (optional) Number of matching results. - :attr List[LogQueryResponseResult] results: (optional) Array of log query - response results. - """ - - def __init__(self, - *, - matching_results: int = None, - results: List['LogQueryResponseResult'] = None) -> None: - """ - Initialize a LogQueryResponse object. - - :param int matching_results: (optional) Number of matching results. - :param List[LogQueryResponseResult] results: (optional) Array of log query - response results. - """ - self.matching_results = matching_results - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': - """Initialize a LogQueryResponse object from a json dictionary.""" - args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - LogQueryResponseResult.from_dict(x) - for x in _dict.get('results') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogQueryResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'LogQueryResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponseResult(): - """ - Individual result object for a **logs** query. Each object represents either a query - to a Discovery collection or an event that is associated with a query. - - :attr str environment_id: (optional) The environment ID that is associated with - this log entry. - :attr str customer_id: (optional) The **customer_id** label that was specified - in the header of the query or event API call that corresponds to this log entry. - :attr str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. - :attr str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these - results. Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) might - have been used with this query, but are not recorded. - :attr LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create this - log entry. Only returned with logs of type `query`. - :attr datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :attr datetime client_timestamp: (optional) Date specified by the user when - recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned - with logs of type **event**. - :attr str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. All - **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This field - can be used to recall all **event** and **query** log results that have the same - original query (**event** logs do not contain the original - **natural_language_query** field). - :attr str session_token: (optional) Unique identifier (within a 24-hour period) - that identifies a single `query` log and any `event` logs that were created for - it. - **Note:** If the exact same query is run at the exact same time on different - days, the **session_token** for those queries might be identical. However, the - **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session tokens - that are identical except for case, use the exact match operator (`::`) when you - query for a specific session token. - :attr str collection_id: (optional) The collection ID of the document associated - with this event. Only returned with logs of type `event`. - :attr int display_rank: (optional) The original display rank of the document - associated with this event. Only returned with logs of type `event`. - :attr str document_id: (optional) The document ID of the document associated - with this event. Only returned with logs of type `event`. - :attr str event_type: (optional) The type of event that this object respresents. - Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :attr str result_type: (optional) The type of result that this **event** is - associated with. Only returned with logs of type `event`. - """ - - def __init__(self, - *, - environment_id: str = None, - customer_id: str = None, - document_type: str = None, - natural_language_query: str = None, - document_results: 'LogQueryResponseResultDocuments' = None, - created_timestamp: datetime = None, - client_timestamp: datetime = None, - query_id: str = None, - session_token: str = None, - collection_id: str = None, - display_rank: int = None, - document_id: str = None, - event_type: str = None, - result_type: str = None) -> None: - """ - Initialize a LogQueryResponseResult object. - - :param str environment_id: (optional) The environment ID that is associated - with this log entry. - :param str customer_id: (optional) The **customer_id** label that was - specified in the header of the query or event API call that corresponds to - this log entry. - :param str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the - single collection **query** method. - **event** indicates that the log represents a call to the **events** API. - :param str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these - results. Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) - might have been used with this query, but are not recorded. - :param LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create - this log entry. Only returned with logs of type `query`. - :param datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime client_timestamp: (optional) Date specified by the user - when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only - returned with logs of type **event**. - :param str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. - All **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This - field can be used to recall all **event** and **query** log results that - have the same original query (**event** logs do not contain the original - **natural_language_query** field). - :param str session_token: (optional) Unique identifier (within a 24-hour - period) that identifies a single `query` log and any `event` logs that were - created for it. - **Note:** If the exact same query is run at the exact same time on - different days, the **session_token** for those queries might be identical. - However, the **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session - tokens that are identical except for case, use the exact match operator - (`::`) when you query for a specific session token. - :param str collection_id: (optional) The collection ID of the document - associated with this event. Only returned with logs of type `event`. - :param int display_rank: (optional) The original display rank of the - document associated with this event. Only returned with logs of type - `event`. - :param str document_id: (optional) The document ID of the document - associated with this event. Only returned with logs of type `event`. - :param str event_type: (optional) The type of event that this object - respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :param str result_type: (optional) The type of result that this **event** - is associated with. Only returned with logs of type `event`. - """ - self.environment_id = environment_id - self.customer_id = customer_id - self.document_type = document_type - self.natural_language_query = natural_language_query - self.document_results = document_results - self.created_timestamp = created_timestamp - self.client_timestamp = client_timestamp - self.query_id = query_id - self.session_token = session_token - self.collection_id = collection_id - self.display_rank = display_rank - self.document_id = document_id - self.event_type = event_type - self.result_type = result_type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': - """Initialize a LogQueryResponseResult object from a json dictionary.""" - args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') - if 'document_type' in _dict: - args['document_type'] = _dict.get('document_type') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') - if 'document_results' in _dict: - args[ - 'document_results'] = LogQueryResponseResultDocuments.from_dict( - _dict.get('document_results')) - if 'created_timestamp' in _dict: - args['created_timestamp'] = string_to_datetime( - _dict.get('created_timestamp')) - if 'client_timestamp' in _dict: - args['client_timestamp'] = string_to_datetime( - _dict.get('client_timestamp')) - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'display_rank' in _dict: - args['display_rank'] = _dict.get('display_rank') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'result_type' in _dict: - args['result_type'] = _dict.get('result_type') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponseResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id - if hasattr(self, 'document_type') and self.document_type is not None: - _dict['document_type'] = self.document_type - if hasattr(self, 'natural_language_query' - ) and self.natural_language_query is not None: - _dict['natural_language_query'] = self.natural_language_query - if hasattr(self, - 'document_results') and self.document_results is not None: - _dict['document_results'] = self.document_results.to_dict() - if hasattr(self, - 'created_timestamp') and self.created_timestamp is not None: - _dict['created_timestamp'] = datetime_to_string( - self.created_timestamp) - if hasattr(self, - 'client_timestamp') and self.client_timestamp is not None: - _dict['client_timestamp'] = datetime_to_string( - self.client_timestamp) - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'display_rank') and self.display_rank is not None: - _dict['display_rank'] = self.display_rank - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'result_type') and self.result_type is not None: - _dict['result_type'] = self.result_type - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogQueryResponseResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponseResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'LogQueryResponseResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DocumentTypeEnum(str, Enum): - """ - The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. - """ - QUERY = 'query' - EVENT = 'event' - - class EventTypeEnum(str, Enum): - """ - The type of event that this object respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - """ - CLICK = 'click' - QUERY = 'query' - - class ResultTypeEnum(str, Enum): - """ - The type of result that this **event** is associated with. Only returned with logs - of type `event`. - """ - DOCUMENT = 'document' - - -class LogQueryResponseResultDocuments(): - """ - Object containing result information that was returned by the query used to create - this log entry. Only returned with logs of type `query`. - - :attr List[LogQueryResponseResultDocumentsResult] results: (optional) Array of - log query response results. - :attr int count: (optional) The number of results returned in the query - associate with this log. - """ - - def __init__(self, - *, - results: List['LogQueryResponseResultDocumentsResult'] = None, - count: int = None) -> None: - """ - Initialize a LogQueryResponseResultDocuments object. - - :param List[LogQueryResponseResultDocumentsResult] results: (optional) - Array of log query response results. - :param int count: (optional) The number of results returned in the query - associate with this log. - """ - self.results = results - self.count = count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': - """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" - args = {} - if 'results' in _dict: - args['results'] = [ - LogQueryResponseResultDocumentsResult.from_dict(x) - for x in _dict.get('results') - ] - if 'count' in _dict: - args['count'] = _dict.get('count') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogQueryResponseResultDocuments object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponseResultDocuments') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'LogQueryResponseResultDocuments') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponseResultDocumentsResult(): - """ - Each object in the **results** array corresponds to an individual document returned by - the original query. - - :attr int position: (optional) The result rank of this document. A position of - `1` indicates that it was the first returned result. - :attr str document_id: (optional) The **document_id** of the document that this - result represents. - :attr float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :attr float confidence: (optional) The confidence score of the result's - analysis. A higher score indicating greater confidence. - :attr str collection_id: (optional) The **collection_id** of the document - represented by this result. - """ - - def __init__(self, - *, - position: int = None, - document_id: str = None, - score: float = None, - confidence: float = None, - collection_id: str = None) -> None: - """ - Initialize a LogQueryResponseResultDocumentsResult object. - - :param int position: (optional) The result rank of this document. A - position of `1` indicates that it was the first returned result. - :param str document_id: (optional) The **document_id** of the document that - this result represents. - :param float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score of the result's - analysis. A higher score indicating greater confidence. - :param str collection_id: (optional) The **collection_id** of the document - represented by this result. - """ - self.position = position - self.document_id = document_id - self.score = score - self.confidence = confidence - self.collection_id = collection_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': - """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" - args = {} - if 'position' in _dict: - args['position'] = _dict.get('position') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'position') and self.position is not None: - _dict['position'] = self.position - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogQueryResponseResultDocumentsResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricAggregation(): - """ - An aggregation analyzing log information for queries and events. - - :attr str interval: (optional) The measurement interval for this metric. Metric - intervals are always 1 day (`1d`). - :attr str event_type: (optional) The event type associated with this metric - result. This field, when present, will always be `click`. - :attr List[MetricAggregationResult] results: (optional) Array of metric - aggregation query results. - """ - - def __init__(self, - *, - interval: str = None, - event_type: str = None, - results: List['MetricAggregationResult'] = None) -> None: - """ - Initialize a MetricAggregation object. - - :param str interval: (optional) The measurement interval for this metric. - Metric intervals are always 1 day (`1d`). - :param str event_type: (optional) The event type associated with this - metric result. This field, when present, will always be `click`. - :param List[MetricAggregationResult] results: (optional) Array of metric - aggregation query results. - """ - self.interval = interval - self.event_type = event_type - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricAggregation': - """Initialize a MetricAggregation object from a json dictionary.""" - args = {} - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'results' in _dict: - args['results'] = [ - MetricAggregationResult.from_dict(x) - for x in _dict.get('results') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MetricAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricAggregationResult(): - """ - Aggregation result data for the requested metric. - - :attr datetime key_as_string: (optional) Date in string form representing the - start of this interval. - :attr int key: (optional) Unix epoch time equivalent of the **key_as_string**, - that represents the start of this interval. - :attr int matching_results: (optional) Number of matching results. - :attr float event_rate: (optional) The number of queries with associated events - divided by the total number of queries for the interval. Only returned with - **event_rate** metrics. - """ - - def __init__(self, - *, - key_as_string: datetime = None, - key: int = None, - matching_results: int = None, - event_rate: float = None) -> None: - """ - Initialize a MetricAggregationResult object. - - :param datetime key_as_string: (optional) Date in string form representing - the start of this interval. - :param int key: (optional) Unix epoch time equivalent of the - **key_as_string**, that represents the start of this interval. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated - events divided by the total number of queries for the interval. Only - returned with **event_rate** metrics. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.event_rate = event_rate - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': - """Initialize a MetricAggregationResult object from a json dictionary.""" - args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = string_to_datetime( - _dict.get('key_as_string')) - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'event_rate' in _dict: - args['event_rate'] = _dict.get('event_rate') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricAggregationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key_as_string') and self.key_as_string is not None: - _dict['key_as_string'] = datetime_to_string(self.key_as_string) - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'event_rate') and self.event_rate is not None: - _dict['event_rate'] = self.event_rate - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricAggregationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MetricAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricResponse(): - """ - The response generated from a call to a **metrics** method. - - :attr List[MetricAggregation] aggregations: (optional) Array of metric - aggregations. - """ - - def __init__(self, - *, - aggregations: List['MetricAggregation'] = None) -> None: - """ - Initialize a MetricResponse object. - - :param List[MetricAggregation] aggregations: (optional) Array of metric - aggregations. - """ - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricResponse': - """Initialize a MetricResponse object from a json dictionary.""" - args = {} - if 'aggregations' in _dict: - args['aggregations'] = [ - MetricAggregation.from_dict(x) - for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MetricResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenAggregation(): - """ - An aggregation analyzing log information for queries and events. - - :attr str event_type: (optional) The event type associated with this metric - result. This field, when present, will always be `click`. - :attr List[MetricTokenAggregationResult] results: (optional) Array of results - for the metric token aggregation. - """ - - def __init__(self, - *, - event_type: str = None, - results: List['MetricTokenAggregationResult'] = None) -> None: - """ - Initialize a MetricTokenAggregation object. - - :param str event_type: (optional) The event type associated with this - metric result. This field, when present, will always be `click`. - :param List[MetricTokenAggregationResult] results: (optional) Array of - results for the metric token aggregation. - """ - self.event_type = event_type - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': - """Initialize a MetricTokenAggregation object from a json dictionary.""" - args = {} - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'results' in _dict: - args['results'] = [ - MetricTokenAggregationResult.from_dict(x) - for x in _dict.get('results') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricTokenAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricTokenAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricTokenAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MetricTokenAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenAggregationResult(): - """ - Aggregation result data for the requested metric. - - :attr str key: (optional) The content of the **natural_language_query** - parameter used in the query that this result represents. - :attr int matching_results: (optional) Number of matching results. - :attr float event_rate: (optional) The number of queries with associated events - divided by the total number of queries currently stored (queries and events are - stored in the log for 30 days). - """ - - def __init__(self, - *, - key: str = None, - matching_results: int = None, - event_rate: float = None) -> None: - """ - Initialize a MetricTokenAggregationResult object. - - :param str key: (optional) The content of the **natural_language_query** - parameter used in the query that this result represents. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated - events divided by the total number of queries currently stored (queries and - events are stored in the log for 30 days). - """ - self.key = key - self.matching_results = matching_results - self.event_rate = event_rate - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': - """Initialize a MetricTokenAggregationResult object from a json dictionary.""" - args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'event_rate' in _dict: - args['event_rate'] = _dict.get('event_rate') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricTokenAggregationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'event_rate') and self.event_rate is not None: - _dict['event_rate'] = self.event_rate - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricTokenAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricTokenAggregationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MetricTokenAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenResponse(): - """ - The response generated from a call to a **metrics** method that evaluates tokens. - - :attr List[MetricTokenAggregation] aggregations: (optional) Array of metric - token aggregations. - """ - - def __init__(self, - *, - aggregations: List['MetricTokenAggregation'] = None) -> None: - """ - Initialize a MetricTokenResponse object. - - :param List[MetricTokenAggregation] aggregations: (optional) Array of - metric token aggregations. - """ - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': - """Initialize a MetricTokenResponse object from a json dictionary.""" - args = {} - if 'aggregations' in _dict: - args['aggregations'] = [ - MetricTokenAggregation.from_dict(x) - for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricTokenResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricTokenResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricTokenResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'MetricTokenResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentConcepts(): - """ - An object specifiying the concepts enrichment and related parameters. - - :attr int limit: (optional) The maximum number of concepts enrichments to extact - from each instance of the specified field. - """ - - def __init__(self, *, limit: int = None) -> None: - """ - Initialize a NluEnrichmentConcepts object. - - :param int limit: (optional) The maximum number of concepts enrichments to - extact from each instance of the specified field. - """ - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': - """Initialize a NluEnrichmentConcepts object from a json dictionary.""" - args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentConcepts object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentConcepts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentConcepts') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentConcepts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentEmotion(): - """ - An object specifying the emotion detection enrichment and related parameters. - - :attr bool document: (optional) When `true`, emotion detection is performed on - the entire field. - :attr List[str] targets: (optional) A comma-separated list of target strings - that will have any associated emotions detected. - """ - - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: - """ - Initialize a NluEnrichmentEmotion object. - - :param bool document: (optional) When `true`, emotion detection is - performed on the entire field. - :param List[str] targets: (optional) A comma-separated list of target - strings that will have any associated emotions detected. - """ - self.document = document - self.targets = targets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': - """Initialize a NluEnrichmentEmotion object from a json dictionary.""" - args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentEmotion object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document - if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = self.targets - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentEmotion object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentEmotion') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentEmotion') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentEntities(): - """ - An object speficying the Entities enrichment and related parameters. - - :attr bool sentiment: (optional) When `true`, sentiment analysis of entities - will be performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of entities will - be performed on the specified field. - :attr int limit: (optional) The maximum number of entities to extract for each - instance of the specified field. - :attr bool mentions: (optional) When `true`, the number of mentions of each - identified entity is recorded. The default is `false`. - :attr bool mention_types: (optional) When `true`, the types of mentions for each - idetifieid entity is recorded. The default is `false`. - :attr bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The default - is `false`. - :attr str model: (optional) The enrichement model to use with entity extraction. - May be a custom model provided by Watson Knowledge Studio, or the default public - model `alchemy`. - """ - - def __init__(self, - *, - sentiment: bool = None, - emotion: bool = None, - limit: int = None, - mentions: bool = None, - mention_types: bool = None, - sentence_locations: bool = None, - model: str = None) -> None: - """ - Initialize a NluEnrichmentEntities object. - - :param bool sentiment: (optional) When `true`, sentiment analysis of - entities will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of entities - will be performed on the specified field. - :param int limit: (optional) The maximum number of entities to extract for - each instance of the specified field. - :param bool mentions: (optional) When `true`, the number of mentions of - each identified entity is recorded. The default is `false`. - :param bool mention_types: (optional) When `true`, the types of mentions - for each idetifieid entity is recorded. The default is `false`. - :param bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The - default is `false`. - :param str model: (optional) The enrichement model to use with entity - extraction. May be a custom model provided by Watson Knowledge Studio, or - the default public model `alchemy`. - """ - self.sentiment = sentiment - self.emotion = emotion - self.limit = limit - self.mentions = mentions - self.mention_types = mention_types - self.sentence_locations = sentence_locations - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': - """Initialize a NluEnrichmentEntities object from a json dictionary.""" - args = {} - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'mentions' in _dict: - args['mentions'] = _dict.get('mentions') - if 'mention_types' in _dict: - args['mention_types'] = _dict.get('mention_types') - if 'sentence_locations' in _dict: - args['sentence_locations'] = _dict.get('sentence_locations') - if 'model' in _dict: - args['model'] = _dict.get('model') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentEntities object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = self.mentions - if hasattr(self, 'mention_types') and self.mention_types is not None: - _dict['mention_types'] = self.mention_types - if hasattr( - self, - 'sentence_locations') and self.sentence_locations is not None: - _dict['sentence_locations'] = self.sentence_locations - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentEntities object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentEntities') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentEntities') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentFeatures(): - """ - Object containing Natural Language Understanding features to be used. - - :attr NluEnrichmentKeywords keywords: (optional) An object specifying the - Keyword enrichment and related parameters. - :attr NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :attr NluEnrichmentSentiment sentiment: (optional) An object specifying the - sentiment extraction enrichment and related parameters. - :attr NluEnrichmentEmotion emotion: (optional) An object specifying the emotion - detection enrichment and related parameters. - :attr dict categories: (optional) An object that indicates the Categories - enrichment will be applied to the specified field. - :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object - specifiying the semantic roles enrichment and related parameters. - :attr NluEnrichmentRelations relations: (optional) An object specifying the - relations enrichment and related parameters. - :attr NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. - """ - - def __init__(self, - *, - keywords: 'NluEnrichmentKeywords' = None, - entities: 'NluEnrichmentEntities' = None, - sentiment: 'NluEnrichmentSentiment' = None, - emotion: 'NluEnrichmentEmotion' = None, - categories: dict = None, - semantic_roles: 'NluEnrichmentSemanticRoles' = None, - relations: 'NluEnrichmentRelations' = None, - concepts: 'NluEnrichmentConcepts' = None) -> None: - """ - Initialize a NluEnrichmentFeatures object. - - :param NluEnrichmentKeywords keywords: (optional) An object specifying the - Keyword enrichment and related parameters. - :param NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :param NluEnrichmentSentiment sentiment: (optional) An object specifying - the sentiment extraction enrichment and related parameters. - :param NluEnrichmentEmotion emotion: (optional) An object specifying the - emotion detection enrichment and related parameters. - :param dict categories: (optional) An object that indicates the Categories - enrichment will be applied to the specified field. - :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object - specifiying the semantic roles enrichment and related parameters. - :param NluEnrichmentRelations relations: (optional) An object specifying - the relations enrichment and related parameters. - :param NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. - """ - self.keywords = keywords - self.entities = entities - self.sentiment = sentiment - self.emotion = emotion - self.categories = categories - self.semantic_roles = semantic_roles - self.relations = relations - self.concepts = concepts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': - """Initialize a NluEnrichmentFeatures object from a json dictionary.""" - args = {} - if 'keywords' in _dict: - args['keywords'] = NluEnrichmentKeywords.from_dict( - _dict.get('keywords')) - if 'entities' in _dict: - args['entities'] = NluEnrichmentEntities.from_dict( - _dict.get('entities')) - if 'sentiment' in _dict: - args['sentiment'] = NluEnrichmentSentiment.from_dict( - _dict.get('sentiment')) - if 'emotion' in _dict: - args['emotion'] = NluEnrichmentEmotion.from_dict( - _dict.get('emotion')) - if 'categories' in _dict: - args['categories'] = _dict.get('categories') - if 'semantic_roles' in _dict: - args['semantic_roles'] = NluEnrichmentSemanticRoles.from_dict( - _dict.get('semantic_roles')) - if 'relations' in _dict: - args['relations'] = NluEnrichmentRelations.from_dict( - _dict.get('relations')) - if 'concepts' in _dict: - args['concepts'] = NluEnrichmentConcepts.from_dict( - _dict.get('concepts')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentFeatures object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords.to_dict() - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities.to_dict() - if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories - if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles.to_dict() - if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations.to_dict() - if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentFeatures object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentFeatures') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentFeatures') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentKeywords(): - """ - An object specifying the Keyword enrichment and related parameters. - - :attr bool sentiment: (optional) When `true`, sentiment analysis of keywords - will be performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of keywords will - be performed on the specified field. - :attr int limit: (optional) The maximum number of keywords to extract for each - instance of the specified field. - """ - - def __init__(self, - *, - sentiment: bool = None, - emotion: bool = None, - limit: int = None) -> None: - """ - Initialize a NluEnrichmentKeywords object. - - :param bool sentiment: (optional) When `true`, sentiment analysis of - keywords will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of keywords - will be performed on the specified field. - :param int limit: (optional) The maximum number of keywords to extract for - each instance of the specified field. - """ - self.sentiment = sentiment - self.emotion = emotion - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': - """Initialize a NluEnrichmentKeywords object from a json dictionary.""" - args = {} - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentKeywords object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentKeywords object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentKeywords') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentKeywords') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentRelations(): - """ - An object specifying the relations enrichment and related parameters. - - :attr str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship extraction. - May be a custom model provided by Watson Knowledge Studio, the default public - model is`en-news`. - """ - - def __init__(self, *, model: str = None) -> None: - """ - Initialize a NluEnrichmentRelations object. - - :param str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship - extraction. May be a custom model provided by Watson Knowledge Studio, the - default public model is`en-news`. - """ - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': - """Initialize a NluEnrichmentRelations object from a json dictionary.""" - args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentRelations object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentRelations object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentRelations') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentRelations') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentSemanticRoles(): - """ - An object specifiying the semantic roles enrichment and related parameters. - - :attr bool entities: (optional) When `true`, entities are extracted from the - identified sentence parts. - :attr bool keywords: (optional) When `true`, keywords are extracted from the - identified sentence parts. - :attr int limit: (optional) The maximum number of semantic roles enrichments to - extact from each instance of the specified field. - """ - - def __init__(self, - *, - entities: bool = None, - keywords: bool = None, - limit: int = None) -> None: - """ - Initialize a NluEnrichmentSemanticRoles object. - - :param bool entities: (optional) When `true`, entities are extracted from - the identified sentence parts. - :param bool keywords: (optional) When `true`, keywords are extracted from - the identified sentence parts. - :param int limit: (optional) The maximum number of semantic roles - enrichments to extact from each instance of the specified field. - """ - self.entities = entities - self.keywords = keywords - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': - """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" - args = {} - if 'entities' in _dict: - args['entities'] = _dict.get('entities') - if 'keywords' in _dict: - args['keywords'] = _dict.get('keywords') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities - if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentSemanticRoles object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentSemanticRoles') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentSemanticRoles') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentSentiment(): - """ - An object specifying the sentiment extraction enrichment and related parameters. - - :attr bool document: (optional) When `true`, sentiment analysis is performed on - the entire field. - :attr List[str] targets: (optional) A comma-separated list of target strings - that will have any associated sentiment analyzed. - """ - - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: - """ - Initialize a NluEnrichmentSentiment object. - - :param bool document: (optional) When `true`, sentiment analysis is - performed on the entire field. - :param List[str] targets: (optional) A comma-separated list of target - strings that will have any associated sentiment analyzed. - """ - self.document = document - self.targets = targets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': - """Initialize a NluEnrichmentSentiment object from a json dictionary.""" - args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentSentiment object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document - if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = self.targets - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentSentiment object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentSentiment') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NluEnrichmentSentiment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NormalizationOperation(): - """ - Object containing normalization operations. - - :attr str operation: (optional) Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical - to copy, except that the **source_field** is removed after the value has been - copied to the **destination_field** (it is the same as a _copy_ followed by a - _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if - it is not already an array, and the value of the **source_field** is appended to - the array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is - consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the - ingested document. **source_field** and **destination_field** are ignored by - this operation because _remove_nulls_ operates on the entire ingested document. - Typically, **remove_nulls** is invoked as the last normalization operation (if - it is invoked at all, it can be time-expensive). - :attr str source_field: (optional) The source field for the operation. - :attr str destination_field: (optional) The destination field for the operation. - """ - - def __init__(self, - *, - operation: str = None, - source_field: str = None, - destination_field: str = None) -> None: - """ - Initialize a NormalizationOperation object. - - :param str operation: (optional) Identifies what type of operation to - perform. - **copy** - Copies the value of the **source_field** to the - **destination_field** field. If the **destination_field** already exists, - then the value of the **source_field** overwrites the original value of the - **destination_field**. - **move** - Renames (moves) the **source_field** to the - **destination_field**. If the **destination_field** already exists, then - the value of the **source_field** overwrites the original value of the - **destination_field**. Rename is identical to copy, except that the - **source_field** is removed after the value has been copied to the - **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array - if it is not already an array, and the value of the **source_field** is - appended to the array. This operation removes the **source_field** after - the merge. If the **source_field** does not exist in the current document, - then the **destination_field** is still converted into an array (if it is - not an array already). This conversion ensures the type for - **destination_field** is consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** - is ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the - ingested document. **source_field** and **destination_field** are ignored - by this operation because _remove_nulls_ operates on the entire ingested - document. Typically, **remove_nulls** is invoked as the last normalization - operation (if it is invoked at all, it can be time-expensive). - :param str source_field: (optional) The source field for the operation. - :param str destination_field: (optional) The destination field for the - operation. - """ - self.operation = operation - self.source_field = source_field - self.destination_field = destination_field - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': - """Initialize a NormalizationOperation object from a json dictionary.""" - args = {} - if 'operation' in _dict: - args['operation'] = _dict.get('operation') - if 'source_field' in _dict: - args['source_field'] = _dict.get('source_field') - if 'destination_field' in _dict: - args['destination_field'] = _dict.get('destination_field') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NormalizationOperation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'operation') and self.operation is not None: - _dict['operation'] = self.operation - if hasattr(self, 'source_field') and self.source_field is not None: - _dict['source_field'] = self.source_field - if hasattr(self, - 'destination_field') and self.destination_field is not None: - _dict['destination_field'] = self.destination_field - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this NormalizationOperation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NormalizationOperation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'NormalizationOperation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class OperationEnum(str, Enum): - """ - Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical to - copy, except that the **source_field** is removed after the value has been copied - to the **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if it - is not already an array, and the value of the **source_field** is appended to the - array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is consistent - across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the ingested - document. **source_field** and **destination_field** are ignored by this operation - because _remove_nulls_ operates on the entire ingested document. Typically, - **remove_nulls** is invoked as the last normalization operation (if it is invoked - at all, it can be time-expensive). - """ - COPY = 'copy' - MOVE = 'move' - MERGE = 'merge' - REMOVE = 'remove' - REMOVE_NULLS = 'remove_nulls' - - -class Notice(): - """ - A notice produced for the collection. - - :attr str notice_id: (optional) Identifies the notice. Many notices might have - the same ID. This field exists so that user applications can programmatically - identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, - `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, - `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, - `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete - list; other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice - occurred. Typical step values include: `smartDocumentUnderstanding`, - `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list; other - values might be returned. - :attr str description: (optional) The description of the notice. - """ - - def __init__(self, - *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: - """ - Initialize a Notice object. - - """ - self.notice_id = notice_id - self.created = created - self.document_id = document_id - self.query_id = query_id - self.severity = severity - self.step = step - self.description = description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Notice': - """Initialize a Notice object from a json dictionary.""" - args = {} - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Notice object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'notice_id') and getattr(self, - 'notice_id') is not None: - _dict['notice_id'] = getattr(self, 'notice_id') - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'document_id') and getattr(self, - 'document_id') is not None: - _dict['document_id'] = getattr(self, 'document_id') - if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: - _dict['query_id'] = getattr(self, 'query_id') - if hasattr(self, 'severity') and getattr(self, 'severity') is not None: - _dict['severity'] = getattr(self, 'severity') - if hasattr(self, 'step') and getattr(self, 'step') is not None: - _dict['step'] = getattr(self, 'step') - if hasattr(self, 'description') and getattr(self, - 'description') is not None: - _dict['description'] = getattr(self, 'description') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Notice object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Notice') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Notice') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SeverityEnum(str, Enum): - """ - Severity level of the notice. - """ - WARNING = 'warning' - ERROR = 'error' - - -class PdfHeadingDetection(): - """ - Object containing heading detection conversion settings for PDF documents. - - :attr List[FontSetting] fonts: (optional) Array of font matching configurations. - """ - - def __init__(self, *, fonts: List['FontSetting'] = None) -> None: - """ - Initialize a PdfHeadingDetection object. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - """ - self.fonts = fonts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': - """Initialize a PdfHeadingDetection object from a json dictionary.""" - args = {} - if 'fonts' in _dict: - args['fonts'] = [ - FontSetting.from_dict(x) for x in _dict.get('fonts') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a PdfHeadingDetection object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x.to_dict() for x in self.fonts] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this PdfHeadingDetection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'PdfHeadingDetection') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'PdfHeadingDetection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class PdfSettings(): - """ - A list of PDF conversion settings. - - :attr PdfHeadingDetection heading: (optional) Object containing heading - detection conversion settings for PDF documents. - """ - - def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: - """ - Initialize a PdfSettings object. - - :param PdfHeadingDetection heading: (optional) Object containing heading - detection conversion settings for PDF documents. - """ - self.heading = heading - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PdfSettings': - """Initialize a PdfSettings object from a json dictionary.""" - args = {} - if 'heading' in _dict: - args['heading'] = PdfHeadingDetection.from_dict( - _dict.get('heading')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a PdfSettings object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this PdfSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'PdfSettings') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'PdfSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryAggregation(): - """ - An aggregation produced by Discovery to analyze the input provided. - - :attr str type: The type of aggregation command used. For example: term, filter, - max, min, etc. - """ - - def __init__(self, type: str) -> None: - """ - Initialize a QueryAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - """ - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryAggregation': - """Initialize a QueryAggregation object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryAggregation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['histogram'] = 'QueryHistogramAggregation' - mapping['max'] = 'QueryCalculationAggregation' - mapping['min'] = 'QueryCalculationAggregation' - mapping['average'] = 'QueryCalculationAggregation' - mapping['sum'] = 'QueryCalculationAggregation' - mapping['unique_count'] = 'QueryCalculationAggregation' - mapping['term'] = 'QueryTermAggregation' - mapping['filter'] = 'QueryFilterAggregation' - mapping['nested'] = 'QueryNestedAggregation' - mapping['timeslice'] = 'QueryTimesliceAggregation' - mapping['top_hits'] = 'QueryTopHitsAggregation' - disc_value = _dict.get('type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'type\' not found in QueryAggregation JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class QueryHistogramAggregationResult(): - """ - Histogram numeric interval result. - - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the - upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__(self, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: - """ - Initialize a QueryHistogramAggregationResult object. - - :param int key: The value of the upper bound for the numeric segment. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': - """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" - args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') - else: - raise ValueError( - 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryHistogramAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryHistogramAggregationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResponse(): - """ - Object containing notice query results. - - :attr int matching_results: (optional) The number of matching results. - :attr List[QueryNoticesResult] results: (optional) Array of document results - that match the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :attr List[QueryPassages] passages: (optional) Array of passage results that - match the query. - :attr int duplicates_removed: (optional) The number of duplicates removed from - this notices query. - """ - - def __init__(self, - *, - matching_results: int = None, - results: List['QueryNoticesResult'] = None, - aggregations: List['QueryAggregation'] = None, - passages: List['QueryPassages'] = None, - duplicates_removed: int = None) -> None: - """ - Initialize a QueryNoticesResponse object. - - :param int matching_results: (optional) The number of matching results. - :param List[QueryNoticesResult] results: (optional) Array of document - results that match the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :param List[QueryPassages] passages: (optional) Array of passage results - that match the query. - :param int duplicates_removed: (optional) The number of duplicates removed - from this notices query. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': - """Initialize a QueryNoticesResponse object from a json dictionary.""" - args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryNoticesResult.from_dict(x) for x in _dict.get('results') - ] - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages.from_dict(x) for x in _dict.get('passages') - ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNoticesResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryNoticesResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryNoticesResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryNoticesResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResult(): - """ - Query result object. - - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :attr int code: (optional) The internal status code returned by the ingestion - subsystem indicating the overall result of ingesting the source document. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr List[Notice] notices: (optional) Array of notices for the document. - """ - - # The set of defined properties for the class - _properties = frozenset([ - 'id', 'metadata', 'collection_id', 'result_metadata', 'code', - 'filename', 'file_type', 'sha1', 'notices' - ]) - - def __init__(self, - *, - id: str = None, - metadata: dict = None, - collection_id: str = None, - result_metadata: 'QueryResultMetadata' = None, - code: int = None, - filename: str = None, - file_type: str = None, - sha1: str = None, - notices: List['Notice'] = None, - **kwargs) -> None: - """ - Initialize a QueryNoticesResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param int code: (optional) The internal status code returned by the - ingestion subsystem indicating the overall result of ingesting the source - document. - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices for the document. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - self.code = code - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': - """Initialize a QueryNoticesResult object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'result_metadata' in _dict: - args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) - if 'code' in _dict: - args['code'] = _dict.get('code') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNoticesResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryNoticesResult""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryNoticesResult""" - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryNoticesResult._properties: - setattr(self, _key, _value) - - def __str__(self) -> str: - """Return a `str` version of this QueryNoticesResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryNoticesResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryNoticesResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FileTypeEnum(str, Enum): - """ - The type of the original source file. - """ - PDF = 'pdf' - HTML = 'html' - WORD = 'word' - JSON = 'json' - - -class QueryPassages(): - """ - A passage query result. - - :attr str document_id: (optional) The unique identifier of the document from - which the passage has been extracted. - :attr float passage_score: (optional) The confidence score of the passages's - analysis. A higher score indicates greater confidence. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the - extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has - been extracted. - """ - - def __init__(self, - *, - document_id: str = None, - passage_score: float = None, - passage_text: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None) -> None: - """ - Initialize a QueryPassages object. - - :param str document_id: (optional) The unique identifier of the document - from which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the - passages's analysis. A higher score indicates greater confidence. - :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of - the extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage - has been extracted. - """ - self.document_id = document_id - self.passage_score = passage_score - self.passage_text = passage_text - self.start_offset = start_offset - self.end_offset = end_offset - self.field = field - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryPassages': - """Initialize a QueryPassages object from a json dictionary.""" - args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryPassages object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'passage_score') and self.passage_score is not None: - _dict['passage_score'] = self.passage_score - if hasattr(self, 'passage_text') and self.passage_text is not None: - _dict['passage_text'] = self.passage_text - if hasattr(self, 'start_offset') and self.start_offset is not None: - _dict['start_offset'] = self.start_offset - if hasattr(self, 'end_offset') and self.end_offset is not None: - _dict['end_offset'] = self.end_offset - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryPassages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryPassages') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryPassages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResponse(): - """ - A response containing the documents and aggregations for the query. - - :attr int matching_results: (optional) The number of matching results for the - query. - :attr List[QueryResult] results: (optional) Array of document results for the - query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :attr List[QueryPassages] passages: (optional) Array of passage results for the - query. - :attr int duplicates_removed: (optional) The number of duplicate results - removed. - :attr str session_token: (optional) The session token for this query. The - session token can be used to add events associated with this query to the query - and event log. - **Important:** Session tokens are case sensitive. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. - :attr str suggested_query: (optional) The suggestions for a misspelled natural - language query. - """ - - def __init__(self, - *, - matching_results: int = None, - results: List['QueryResult'] = None, - aggregations: List['QueryAggregation'] = None, - passages: List['QueryPassages'] = None, - duplicates_removed: int = None, - session_token: str = None, - retrieval_details: 'RetrievalDetails' = None, - suggested_query: str = None) -> None: - """ - Initialize a QueryResponse object. - - :param int matching_results: (optional) The number of matching results for - the query. - :param List[QueryResult] results: (optional) Array of document results for - the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :param List[QueryPassages] passages: (optional) Array of passage results - for the query. - :param int duplicates_removed: (optional) The number of duplicate results - removed. - :param str session_token: (optional) The session token for this query. The - session token can be used to add events associated with this query to the - query and event log. - **Important:** Session tokens are case sensitive. - :param RetrievalDetails retrieval_details: (optional) An object contain - retrieval type information. - :param str suggested_query: (optional) The suggestions for a misspelled - natural language query. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - self.session_token = session_token - self.retrieval_details = retrieval_details - self.suggested_query = suggested_query - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResponse': - """Initialize a QueryResponse object from a json dictionary.""" - args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryResult.from_dict(x) for x in _dict.get('results') - ] - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages.from_dict(x) for x in _dict.get('passages') - ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - if 'retrieval_details' in _dict: - args['retrieval_details'] = RetrievalDetails.from_dict( - _dict.get('retrieval_details')) - if 'suggested_query' in _dict: - args['suggested_query'] = _dict.get('suggested_query') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, - 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details.to_dict() - if hasattr(self, - 'suggested_query') and self.suggested_query is not None: - _dict['suggested_query'] = self.suggested_query - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResult(): - """ - Query result object. - - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - """ - - # The set of defined properties for the class - _properties = frozenset( - ['id', 'metadata', 'collection_id', 'result_metadata']) - - def __init__(self, - *, - id: str = None, - metadata: dict = None, - collection_id: str = None, - result_metadata: 'QueryResultMetadata' = None, - **kwargs) -> None: - """ - Initialize a QueryResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResult': - """Initialize a QueryResult object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'result_metadata' in _dict: - args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryResult""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryResult""" - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryResult._properties: - setattr(self, _key, _value) - - def __str__(self) -> str: - """Return a `str` version of this QueryResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResultMetadata(): - """ - Metadata of a query result. - - :attr float score: An unbounded measure of the relevance of a particular result, - dependent on the query and matching document. A higher score indicates a greater - match to the query parameters. - :attr float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can - range from `0.0` to `1.0`. The higher the number, the more relevant the - document. The `confidence` value for a result was calculated using the model - specified in the `document_retrieval_strategy` field of the result set. - """ - - def __init__(self, score: float, *, confidence: float = None) -> None: - """ - Initialize a QueryResultMetadata object. - - :param float score: An unbounded measure of the relevance of a particular - result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score for the given - result. Calculated based on how relevant the result is estimated to be. - confidence can range from `0.0` to `1.0`. The higher the number, the more - relevant the document. The `confidence` value for a result was calculated - using the model specified in the `document_retrieval_strategy` field of the - result set. - """ - self.score = score - self.confidence = confidence - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': - """Initialize a QueryResultMetadata object from a json dictionary.""" - args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in QueryResultMetadata JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryResultMetadata object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryResultMetadata object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryResultMetadata') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryResultMetadata') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregationResult(): - """ - Top value result for the term aggregation. - - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this term. - :attr int total_matching_documents: (optional) The number of documents which - have the term as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: - """ - Initialize a QueryTermAggregationResult object. - - :param str key: Value of the field with a non-zero frequency in the - document set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents - which have the term as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key = key - self.matching_results = matching_results - self.relevancy = relevancy - self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': - """Initialize a QueryTermAggregationResult object from a json dictionary.""" - args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') - else: - raise ValueError( - 'Required property \'key\' not present in QueryTermAggregationResult JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' - ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTermAggregationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'relevancy') and self.relevancy is not None: - _dict['relevancy'] = self.relevancy - if hasattr(self, 'total_matching_documents' - ) and self.total_matching_documents is not None: - _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: - _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTermAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTermAggregationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryTermAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregationResult(): - """ - A timeslice interval segment. - - :attr str key_as_string: String date value of the upper bound for the timeslice - interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval - in UNIX milliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the - upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__(self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: - """ - Initialize a QueryTimesliceAggregationResult object. - - :param str key_as_string: String date value of the upper bound for the - timeslice interval in ISO-8601 format. - :param int key: Numeric date value of the upper bound for the timeslice - interval in UNIX milliseconds since epoch. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': - """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" - args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = _dict.get('key_as_string') - else: - raise ValueError( - 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' - ) - if 'key' in _dict: - args['key'] = _dict.get('key') - else: - raise ValueError( - 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key_as_string') and self.key_as_string is not None: - _dict['key_as_string'] = self.key_as_string - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTimesliceAggregationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregationResult(): - """ - A query response that contains the matching documents for the preceding aggregations. - - :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results. - """ - - def __init__(self, - matching_results: int, - *, - hits: List[dict] = None) -> None: - """ - Initialize a QueryTopHitsAggregationResult object. - - :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. - """ - self.matching_results = matching_results - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': - """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" - args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' - ) - if 'hits' in _dict: - args['hits'] = _dict.get('hits') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTopHitsAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTopHitsAggregationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class RetrievalDetails(): - """ - An object contain retrieval type information. - - :attr str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that the - results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned using - the continuous relevancy training model created by result feedback analysis. - `untrained` means the results were returned using the standard untrained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. - """ - - def __init__(self, *, document_retrieval_strategy: str = None) -> None: - """ - Initialize a RetrievalDetails object. - - :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that - the results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned - using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard - untrained model. - **Note**: In the event of trained collections being queried, but the - trained model is not used to return results, the - **document_retrieval_strategy** will be listed as `untrained`. - """ - self.document_retrieval_strategy = document_retrieval_strategy - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': - """Initialize a RetrievalDetails object from a json dictionary.""" - args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a RetrievalDetails object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_retrieval_strategy' - ) and self.document_retrieval_strategy is not None: - _dict[ - 'document_retrieval_strategy'] = self.document_retrieval_strategy - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this RetrievalDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'RetrievalDetails') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'RetrievalDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DocumentRetrievalStrategyEnum(str, Enum): - """ - Indentifies the document retrieval strategy used for this query. - `relevancy_training` indicates that the results were returned using a relevancy - trained model. `continuous_relevancy_training` indicates that the results were - returned using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard untrained - model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. - """ - UNTRAINED = 'untrained' - RELEVANCY_TRAINING = 'relevancy_training' - CONTINUOUS_RELEVANCY_TRAINING = 'continuous_relevancy_training' - - -class SduStatus(): - """ - Object containing smart document understanding information for this collection. - - :attr bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a - version date after `2019-04-30` have smart document understanding enabled. If - `false`, documents added to the collection are converted using the - **conversion** settings specified in the configuration associated with the - collection. - :attr int total_annotated_pages: (optional) The total number of pages annotated - using smart document understanding in this collection. - :attr int total_pages: (optional) The current number of pages that can be used - for training smart document understanding. The `total_pages` number is - calculated as the total number of pages identified from the documents listed in - the **total_documents** field. - :attr int total_documents: (optional) The total number of documents in this - collection that can be used to train smart document understanding. For **lite** - plan collections, the maximum is the first 20 uploaded documents (not including - HTML or JSON documents). For other plans, the maximum is the first 40 uploaded - documents (not including HTML or JSON documents). When the maximum is reached, - additional documents uploaded to the collection are not considered for training - smart document understanding. - :attr SduStatusCustomFields custom_fields: (optional) Information about custom - smart document understanding fields that exist in this collection. - """ - - def __init__(self, - *, - enabled: bool = None, - total_annotated_pages: int = None, - total_pages: int = None, - total_documents: int = None, - custom_fields: 'SduStatusCustomFields' = None) -> None: - """ - Initialize a SduStatus object. - - :param bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a - version date after `2019-04-30` have smart document understanding enabled. - If `false`, documents added to the collection are converted using the - **conversion** settings specified in the configuration associated with the - collection. - :param int total_annotated_pages: (optional) The total number of pages - annotated using smart document understanding in this collection. - :param int total_pages: (optional) The current number of pages that can be - used for training smart document understanding. The `total_pages` number is - calculated as the total number of pages identified from the documents - listed in the **total_documents** field. - :param int total_documents: (optional) The total number of documents in - this collection that can be used to train smart document understanding. For - **lite** plan collections, the maximum is the first 20 uploaded documents - (not including HTML or JSON documents). For other plans, the maximum is the - first 40 uploaded documents (not including HTML or JSON documents). When - the maximum is reached, additional documents uploaded to the collection are - not considered for training smart document understanding. - :param SduStatusCustomFields custom_fields: (optional) Information about - custom smart document understanding fields that exist in this collection. - """ - self.enabled = enabled - self.total_annotated_pages = total_annotated_pages - self.total_pages = total_pages - self.total_documents = total_documents - self.custom_fields = custom_fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SduStatus': - """Initialize a SduStatus object from a json dictionary.""" - args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'total_annotated_pages' in _dict: - args['total_annotated_pages'] = _dict.get('total_annotated_pages') - if 'total_pages' in _dict: - args['total_pages'] = _dict.get('total_pages') - if 'total_documents' in _dict: - args['total_documents'] = _dict.get('total_documents') - if 'custom_fields' in _dict: - args['custom_fields'] = SduStatusCustomFields.from_dict( - _dict.get('custom_fields')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SduStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'total_annotated_pages' - ) and self.total_annotated_pages is not None: - _dict['total_annotated_pages'] = self.total_annotated_pages - if hasattr(self, 'total_pages') and self.total_pages is not None: - _dict['total_pages'] = self.total_pages - if hasattr(self, - 'total_documents') and self.total_documents is not None: - _dict['total_documents'] = self.total_documents - if hasattr(self, 'custom_fields') and self.custom_fields is not None: - _dict['custom_fields'] = self.custom_fields.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SduStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SduStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SduStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SduStatusCustomFields(): - """ - Information about custom smart document understanding fields that exist in this - collection. - - :attr int defined: (optional) The number of custom fields defined for this - collection. - :attr int maximum_allowed: (optional) The maximum number of custom fields that - are allowed in this collection. - """ - - def __init__(self, - *, - defined: int = None, - maximum_allowed: int = None) -> None: - """ - Initialize a SduStatusCustomFields object. - - :param int defined: (optional) The number of custom fields defined for this - collection. - :param int maximum_allowed: (optional) The maximum number of custom fields - that are allowed in this collection. - """ - self.defined = defined - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': - """Initialize a SduStatusCustomFields object from a json dictionary.""" - args = {} - if 'defined' in _dict: - args['defined'] = _dict.get('defined') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SduStatusCustomFields object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'defined') and self.defined is not None: - _dict['defined'] = self.defined - if hasattr(self, - 'maximum_allowed') and self.maximum_allowed is not None: - _dict['maximum_allowed'] = self.maximum_allowed - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SduStatusCustomFields object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SduStatusCustomFields') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SduStatusCustomFields') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SearchStatus(): - """ - Information about the Continuous Relevancy Training for this environment. - - :attr str scope: (optional) Current scope of the training. Always returned as - `environment`. - :attr str status: (optional) The current status of Continuous Relevancy Training - for this environment. - :attr str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :attr date last_trained: (optional) The date stamp of the most recent completed - training for this environment. - """ - - def __init__(self, - *, - scope: str = None, - status: str = None, - status_description: str = None, - last_trained: date = None) -> None: - """ - Initialize a SearchStatus object. - - :param str scope: (optional) Current scope of the training. Always returned - as `environment`. - :param str status: (optional) The current status of Continuous Relevancy - Training for this environment. - :param str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :param date last_trained: (optional) The date stamp of the most recent - completed training for this environment. - """ - self.scope = scope - self.status = status - self.status_description = status_description - self.last_trained = last_trained - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchStatus': - """Initialize a SearchStatus object from a json dictionary.""" - args = {} - if 'scope' in _dict: - args['scope'] = _dict.get('scope') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'last_trained' in _dict: - args['last_trained'] = string_to_date(_dict.get('last_trained')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SearchStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'scope') and self.scope is not None: - _dict['scope'] = self.scope - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr( - self, - 'status_description') and self.status_description is not None: - _dict['status_description'] = self.status_description - if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = date_to_string(self.last_trained) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SearchStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SearchStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SearchStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of Continuous Relevancy Training for this environment. - """ - NO_DATA = 'NO_DATA' - INSUFFICENT_DATA = 'INSUFFICENT_DATA' - TRAINING = 'TRAINING' - TRAINED = 'TRAINED' - NOT_APPLICABLE = 'NOT_APPLICABLE' - - -class SegmentSettings(): - """ - A list of Document Segmentation settings. - - :attr bool enabled: (optional) Enables/disables the Document Segmentation - feature. - :attr List[str] selector_tags: (optional) Defines the heading level that splits - into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of - the header field that the segmentation splits at is used as the **title** field - for that segmented result. Only valid if used with a collection that has - **enabled** set to `false` in the **smart_document_understanding** object. - :attr List[str] annotated_fields: (optional) Defines the annotated smart - document understanding fields that the document is split on. The content of the - annotated field that the segmentation splits at is used as the **title** field - for that segmented result. For example, if the field `sub-title` is specified, - when a document is uploaded each time the smart documement understanding - conversion encounters a field of type `sub-title` the document is split at that - point and the content of the field used as the title of the remaining content. - Thnis split is performed for all instances of the listed fields in the uploaded - document. Only valid if used with a collection that has **enabled** set to - `true` in the **smart_document_understanding** object. - """ - - def __init__(self, - *, - enabled: bool = None, - selector_tags: List[str] = None, - annotated_fields: List[str] = None) -> None: - """ - Initialize a SegmentSettings object. - - :param bool enabled: (optional) Enables/disables the Document Segmentation - feature. - :param List[str] selector_tags: (optional) Defines the heading level that - splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The - content of the header field that the segmentation splits at is used as the - **title** field for that segmented result. Only valid if used with a - collection that has **enabled** set to `false` in the - **smart_document_understanding** object. - :param List[str] annotated_fields: (optional) Defines the annotated smart - document understanding fields that the document is split on. The content of - the annotated field that the segmentation splits at is used as the - **title** field for that segmented result. For example, if the field - `sub-title` is specified, when a document is uploaded each time the smart - documement understanding conversion encounters a field of type `sub-title` - the document is split at that point and the content of the field used as - the title of the remaining content. Thnis split is performed for all - instances of the listed fields in the uploaded document. Only valid if used - with a collection that has **enabled** set to `true` in the - **smart_document_understanding** object. - """ - self.enabled = enabled - self.selector_tags = selector_tags - self.annotated_fields = annotated_fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SegmentSettings': - """Initialize a SegmentSettings object from a json dictionary.""" - args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'selector_tags' in _dict: - args['selector_tags'] = _dict.get('selector_tags') - if 'annotated_fields' in _dict: - args['annotated_fields'] = _dict.get('annotated_fields') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SegmentSettings object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'selector_tags') and self.selector_tags is not None: - _dict['selector_tags'] = self.selector_tags - if hasattr(self, - 'annotated_fields') and self.annotated_fields is not None: - _dict['annotated_fields'] = self.annotated_fields - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SegmentSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SegmentSettings') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SegmentSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Source(): - """ - Object containing source parameters for the configuration. - - :attr str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise - Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - :attr str credential_id: (optional) The **credential_id** of the credentials to - use to connect to the source. Credentials are defined using the **credentials** - method. The **source_type** of the credentials used must match the **type** - field specified in this object. - :attr SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :attr SourceOptions options: (optional) The **options** object defines which - items to crawl from the source system. - """ - - def __init__(self, - *, - type: str = None, - credential_id: str = None, - schedule: 'SourceSchedule' = None, - options: 'SourceOptions' = None) -> None: - """ - Initialize a Source object. - - :param str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of - Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a - cloud object store. - :param str credential_id: (optional) The **credential_id** of the - credentials to use to connect to the source. Credentials are defined using - the **credentials** method. The **source_type** of the credentials used - must match the **type** field specified in this object. - :param SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :param SourceOptions options: (optional) The **options** object defines - which items to crawl from the source system. - """ - self.type = type - self.credential_id = credential_id - self.schedule = schedule - self.options = options - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Source': - """Initialize a Source object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'schedule' in _dict: - args['schedule'] = SourceSchedule.from_dict(_dict.get('schedule')) - if 'options' in _dict: - args['options'] = SourceOptions.from_dict(_dict.get('options')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Source object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'credential_id') and self.credential_id is not None: - _dict['credential_id'] = self.credential_id - if hasattr(self, 'schedule') and self.schedule is not None: - _dict['schedule'] = self.schedule.to_dict() - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Source object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Source') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Source') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint - Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - """ - BOX = 'box' - SALESFORCE = 'salesforce' - SHAREPOINT = 'sharepoint' - WEB_CRAWL = 'web_crawl' - CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - - -class SourceOptions(): - """ - The **options** object defines which items to crawl from the source system. - - :attr List[SourceOptionsFolder] folders: (optional) Array of folders to crawl - from the Box source. Only valid, and required, when the **type** field of the - **source** object is set to `box`. - :attr List[SourceOptionsObject] objects: (optional) Array of Salesforce document - object types to crawl from the Salesforce source. Only valid, and required, when - the **type** field of the **source** object is set to `salesforce`. - :attr List[SourceOptionsSiteColl] site_collections: (optional) Array of - Microsoft SharePointoint Online site collections to crawl from the SharePoint - source. Only valid and required when the **type** field of the **source** object - is set to `sharepoint`. - :attr List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to - begin crawling the web from. Only valid and required when the **type** field of - the **source** object is set to `web_crawl`. - :attr List[SourceOptionsBuckets] buckets: (optional) Array of cloud object store - buckets to begin crawling. Only valid and required when the **type** field of - the **source** object is set to `cloud_object_store`, and the - **crawl_all_buckets** field is `false` or not specified. - :attr bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** - array must not be specified. - """ - - def __init__(self, - *, - folders: List['SourceOptionsFolder'] = None, - objects: List['SourceOptionsObject'] = None, - site_collections: List['SourceOptionsSiteColl'] = None, - urls: List['SourceOptionsWebCrawl'] = None, - buckets: List['SourceOptionsBuckets'] = None, - crawl_all_buckets: bool = None) -> None: - """ - Initialize a SourceOptions object. - - :param List[SourceOptionsFolder] folders: (optional) Array of folders to - crawl from the Box source. Only valid, and required, when the **type** - field of the **source** object is set to `box`. - :param List[SourceOptionsObject] objects: (optional) Array of Salesforce - document object types to crawl from the Salesforce source. Only valid, and - required, when the **type** field of the **source** object is set to - `salesforce`. - :param List[SourceOptionsSiteColl] site_collections: (optional) Array of - Microsoft SharePointoint Online site collections to crawl from the - SharePoint source. Only valid and required when the **type** field of the - **source** object is set to `sharepoint`. - :param List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs - to begin crawling the web from. Only valid and required when the **type** - field of the **source** object is set to `web_crawl`. - :param List[SourceOptionsBuckets] buckets: (optional) Array of cloud object - store buckets to begin crawling. Only valid and required when the **type** - field of the **source** object is set to `cloud_object_store`, and the - **crawl_all_buckets** field is `false` or not specified. - :param bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** - array must not be specified. - """ - self.folders = folders - self.objects = objects - self.site_collections = site_collections - self.urls = urls - self.buckets = buckets - self.crawl_all_buckets = crawl_all_buckets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptions': - """Initialize a SourceOptions object from a json dictionary.""" - args = {} - if 'folders' in _dict: - args['folders'] = [ - SourceOptionsFolder.from_dict(x) for x in _dict.get('folders') - ] - if 'objects' in _dict: - args['objects'] = [ - SourceOptionsObject.from_dict(x) for x in _dict.get('objects') - ] - if 'site_collections' in _dict: - args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(x) - for x in _dict.get('site_collections') - ] - if 'urls' in _dict: - args['urls'] = [ - SourceOptionsWebCrawl.from_dict(x) for x in _dict.get('urls') - ] - if 'buckets' in _dict: - args['buckets'] = [ - SourceOptionsBuckets.from_dict(x) for x in _dict.get('buckets') - ] - if 'crawl_all_buckets' in _dict: - args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'folders') and self.folders is not None: - _dict['folders'] = [x.to_dict() for x in self.folders] - if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x.to_dict() for x in self.objects] - if hasattr(self, - 'site_collections') and self.site_collections is not None: - _dict['site_collections'] = [ - x.to_dict() for x in self.site_collections - ] - if hasattr(self, 'urls') and self.urls is not None: - _dict['urls'] = [x.to_dict() for x in self.urls] - if hasattr(self, 'buckets') and self.buckets is not None: - _dict['buckets'] = [x.to_dict() for x in self.buckets] - if hasattr(self, - 'crawl_all_buckets') and self.crawl_all_buckets is not None: - _dict['crawl_all_buckets'] = self.crawl_all_buckets - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsBuckets(): - """ - Object defining a cloud object store bucket to crawl. - - :attr str name: The name of the cloud object store bucket to crawl. - :attr int limit: (optional) The number of documents to crawl from this cloud - object store bucket. If not specified, all documents in the bucket are crawled. - """ - - def __init__(self, name: str, *, limit: int = None) -> None: - """ - Initialize a SourceOptionsBuckets object. - - :param str name: The name of the cloud object store bucket to crawl. - :param int limit: (optional) The number of documents to crawl from this - cloud object store bucket. If not specified, all documents in the bucket - are crawled. - """ - self.name = name - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': - """Initialize a SourceOptionsBuckets object from a json dictionary.""" - args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in SourceOptionsBuckets JSON' - ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsBuckets object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceOptionsBuckets object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsBuckets') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceOptionsBuckets') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsFolder(): - """ - Object that defines a box folder to crawl with this configuration. - - :attr str owner_user_id: The Box user ID of the user who owns the folder to - crawl. - :attr str folder_id: The Box folder ID of the folder to crawl. - :attr int limit: (optional) The maximum number of documents to crawl for this - folder. By default, all documents in the folder are crawled. - """ - - def __init__(self, - owner_user_id: str, - folder_id: str, - *, - limit: int = None) -> None: - """ - Initialize a SourceOptionsFolder object. - - :param str owner_user_id: The Box user ID of the user who owns the folder - to crawl. - :param str folder_id: The Box folder ID of the folder to crawl. - :param int limit: (optional) The maximum number of documents to crawl for - this folder. By default, all documents in the folder are crawled. - """ - self.owner_user_id = owner_user_id - self.folder_id = folder_id - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': - """Initialize a SourceOptionsFolder object from a json dictionary.""" - args = {} - if 'owner_user_id' in _dict: - args['owner_user_id'] = _dict.get('owner_user_id') - else: - raise ValueError( - 'Required property \'owner_user_id\' not present in SourceOptionsFolder JSON' - ) - if 'folder_id' in _dict: - args['folder_id'] = _dict.get('folder_id') - else: - raise ValueError( - 'Required property \'folder_id\' not present in SourceOptionsFolder JSON' - ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsFolder object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'owner_user_id') and self.owner_user_id is not None: - _dict['owner_user_id'] = self.owner_user_id - if hasattr(self, 'folder_id') and self.folder_id is not None: - _dict['folder_id'] = self.folder_id - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceOptionsFolder object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsFolder') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceOptionsFolder') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsObject(): - """ - Object that defines a Salesforce document object type crawl with this configuration. - - :attr str name: The name of the Salesforce document object to crawl. For - example, `case`. - :attr int limit: (optional) The maximum number of documents to crawl for this - document object. By default, all documents in the document object are crawled. - """ - - def __init__(self, name: str, *, limit: int = None) -> None: - """ - Initialize a SourceOptionsObject object. - - :param str name: The name of the Salesforce document object to crawl. For - example, `case`. - :param int limit: (optional) The maximum number of documents to crawl for - this document object. By default, all documents in the document object are - crawled. - """ - self.name = name - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': - """Initialize a SourceOptionsObject object from a json dictionary.""" - args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in SourceOptionsObject JSON' - ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsObject object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceOptionsObject object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsObject') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceOptionsObject') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsSiteColl(): - """ - Object that defines a Microsoft SharePoint site collection to crawl with this - configuration. - - :attr str site_collection_path: The Microsoft SharePoint Online site collection - path to crawl. The path must be be relative to the **organization_url** that was - specified in the credentials associated with this source configuration. - :attr int limit: (optional) The maximum number of documents to crawl for this - site collection. By default, all documents in the site collection are crawled. - """ - - def __init__(self, site_collection_path: str, *, limit: int = None) -> None: - """ - Initialize a SourceOptionsSiteColl object. - - :param str site_collection_path: The Microsoft SharePoint Online site - collection path to crawl. The path must be be relative to the - **organization_url** that was specified in the credentials associated with - this source configuration. - :param int limit: (optional) The maximum number of documents to crawl for - this site collection. By default, all documents in the site collection are - crawled. - """ - self.site_collection_path = site_collection_path - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': - """Initialize a SourceOptionsSiteColl object from a json dictionary.""" - args = {} - if 'site_collection_path' in _dict: - args['site_collection_path'] = _dict.get('site_collection_path') - else: - raise ValueError( - 'Required property \'site_collection_path\' not present in SourceOptionsSiteColl JSON' - ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsSiteColl object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'site_collection_path' - ) and self.site_collection_path is not None: - _dict['site_collection_path'] = self.site_collection_path - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceOptionsSiteColl object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsSiteColl') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceOptionsSiteColl') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsWebCrawl(): - """ - Object defining which URL to crawl and how to crawl it. - - :attr str url: The starting URL to crawl. - :attr bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. - :attr str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short delay - between fetch calls. `aggressive` means that up to ten URLs are fetched - concurrently with a short delay between fetch calls. - :attr bool allow_untrusted_certificate: (optional) When `true`, allows the crawl - to interact with HTTPS sites with SSL certificates with untrusted signers. - :attr int maximum_hops: (optional) The maximum number of hops to make from the - initial URL. When a page is crawled each link on that page will also be crawled - if it is within the **maximum_hops** from the initial URL. The first page - crawled is 0 hops, each link crawled from the first page is 1 hop, each link - crawled from those pages is 2 hops, and so on. - :attr int request_timeout: (optional) The maximum milliseconds to wait for a - response from the web server. - :attr bool override_robots_txt: (optional) When `true`, the crawler will ignore - any `robots.txt` encountered by the crawler. This should only ever be done when - crawling a web site the user owns. This must be be set to `true` when a - **gateway_id** is specied in the **credentials**. - :attr List[str] blacklist: (optional) Array of URL's to be excluded while - crawling. The crawler will not follow links which contains this string. For - example, listing `https://ibm.com/watson` also excludes - `https://ibm.com/watson/discovery`. - """ - - def __init__(self, - url: str, - *, - limit_to_starting_hosts: bool = None, - crawl_speed: str = None, - allow_untrusted_certificate: bool = None, - maximum_hops: int = None, - request_timeout: int = None, - override_robots_txt: bool = None, - blacklist: List[str] = None) -> None: - """ - Initialize a SourceOptionsWebCrawl object. - - :param str url: The starting URL to crawl. - :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. - :param str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short - delay between fetch calls. `aggressive` means that up to ten URLs are - fetched concurrently with a short delay between fetch calls. - :param bool allow_untrusted_certificate: (optional) When `true`, allows the - crawl to interact with HTTPS sites with SSL certificates with untrusted - signers. - :param int maximum_hops: (optional) The maximum number of hops to make from - the initial URL. When a page is crawled each link on that page will also be - crawled if it is within the **maximum_hops** from the initial URL. The - first page crawled is 0 hops, each link crawled from the first page is 1 - hop, each link crawled from those pages is 2 hops, and so on. - :param int request_timeout: (optional) The maximum milliseconds to wait for - a response from the web server. - :param bool override_robots_txt: (optional) When `true`, the crawler will - ignore any `robots.txt` encountered by the crawler. This should only ever - be done when crawling a web site the user owns. This must be be set to - `true` when a **gateway_id** is specied in the **credentials**. - :param List[str] blacklist: (optional) Array of URL's to be excluded while - crawling. The crawler will not follow links which contains this string. For - example, listing `https://ibm.com/watson` also excludes - `https://ibm.com/watson/discovery`. - """ - self.url = url - self.limit_to_starting_hosts = limit_to_starting_hosts - self.crawl_speed = crawl_speed - self.allow_untrusted_certificate = allow_untrusted_certificate - self.maximum_hops = maximum_hops - self.request_timeout = request_timeout - self.override_robots_txt = override_robots_txt - self.blacklist = blacklist - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': - """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" - args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') - else: - raise ValueError( - 'Required property \'url\' not present in SourceOptionsWebCrawl JSON' - ) - if 'limit_to_starting_hosts' in _dict: - args['limit_to_starting_hosts'] = _dict.get( - 'limit_to_starting_hosts') - if 'crawl_speed' in _dict: - args['crawl_speed'] = _dict.get('crawl_speed') - if 'allow_untrusted_certificate' in _dict: - args['allow_untrusted_certificate'] = _dict.get( - 'allow_untrusted_certificate') - if 'maximum_hops' in _dict: - args['maximum_hops'] = _dict.get('maximum_hops') - if 'request_timeout' in _dict: - args['request_timeout'] = _dict.get('request_timeout') - if 'override_robots_txt' in _dict: - args['override_robots_txt'] = _dict.get('override_robots_txt') - if 'blacklist' in _dict: - args['blacklist'] = _dict.get('blacklist') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'limit_to_starting_hosts' - ) and self.limit_to_starting_hosts is not None: - _dict['limit_to_starting_hosts'] = self.limit_to_starting_hosts - if hasattr(self, 'crawl_speed') and self.crawl_speed is not None: - _dict['crawl_speed'] = self.crawl_speed - if hasattr(self, 'allow_untrusted_certificate' - ) and self.allow_untrusted_certificate is not None: - _dict[ - 'allow_untrusted_certificate'] = self.allow_untrusted_certificate - if hasattr(self, 'maximum_hops') and self.maximum_hops is not None: - _dict['maximum_hops'] = self.maximum_hops - if hasattr(self, - 'request_timeout') and self.request_timeout is not None: - _dict['request_timeout'] = self.request_timeout - if hasattr( - self, - 'override_robots_txt') and self.override_robots_txt is not None: - _dict['override_robots_txt'] = self.override_robots_txt - if hasattr(self, 'blacklist') and self.blacklist is not None: - _dict['blacklist'] = self.blacklist - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceOptionsWebCrawl object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsWebCrawl') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceOptionsWebCrawl') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CrawlSpeedEnum(str, Enum): - """ - The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a - time with a delay between each call. `normal` means as many as two URLs are - fectched concurrently with a short delay between fetch calls. `aggressive` means - that up to ten URLs are fetched concurrently with a short delay between fetch - calls. - """ - GENTLE = 'gentle' - NORMAL = 'normal' - AGGRESSIVE = 'aggressive' - - -class SourceSchedule(): - """ - Object containing the schedule information for the source. - - :attr bool enabled: (optional) When `true`, the source is re-crawled based on - the **frequency** field in this object. When `false` the source is not - re-crawled; When `false` and connecting to Salesforce the source is crawled - annually. - :attr str time_zone: (optional) The time zone to base source crawl times on. - Possible values correspond to the IANA (Internet Assigned Numbers Authority) - time zones list. - :attr str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and - 06:00. - """ - - def __init__(self, - *, - enabled: bool = None, - time_zone: str = None, - frequency: str = None) -> None: - """ - Initialize a SourceSchedule object. - - :param bool enabled: (optional) When `true`, the source is re-crawled based - on the **frequency** field in this object. When `false` the source is not - re-crawled; When `false` and connecting to Salesforce the source is crawled - annually. - :param str time_zone: (optional) The time zone to base source crawl times - on. Possible values correspond to the IANA (Internet Assigned Numbers - Authority) time zones list. - :param str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and - 06:00. - """ - self.enabled = enabled - self.time_zone = time_zone - self.frequency = frequency - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceSchedule': - """Initialize a SourceSchedule object from a json dictionary.""" - args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'time_zone' in _dict: - args['time_zone'] = _dict.get('time_zone') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceSchedule object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'time_zone') and self.time_zone is not None: - _dict['time_zone'] = self.time_zone - if hasattr(self, 'frequency') and self.frequency is not None: - _dict['frequency'] = self.frequency - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceSchedule object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceSchedule') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceSchedule') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FrequencyEnum(str, Enum): - """ - The crawl schedule in the specified **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. - """ - DAILY = 'daily' - WEEKLY = 'weekly' - MONTHLY = 'monthly' - FIVE_MINUTES = 'five_minutes' - HOURLY = 'hourly' - - -class SourceStatus(): - """ - Object containing source crawl status information. - - :attr str status: (optional) The current status of the source crawl for this - collection. This field returns `not_configured` if the default configuration for - this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - :attr datetime next_crawl: (optional) Date in `RFC 3339` format indicating the - time of the next crawl attempt. - """ - - def __init__(self, - *, - status: str = None, - next_crawl: datetime = None) -> None: - """ - Initialize a SourceStatus object. - - :param str status: (optional) The current status of the source crawl for - this collection. This field returns `not_configured` if the default - configuration for this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the - service. - :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating - the time of the next crawl attempt. - """ - self.status = status - self.next_crawl = next_crawl - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceStatus': - """Initialize a SourceStatus object from a json dictionary.""" - args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'next_crawl' in _dict: - args['next_crawl'] = string_to_datetime(_dict.get('next_crawl')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'next_crawl') and self.next_crawl is not None: - _dict['next_crawl'] = datetime_to_string(self.next_crawl) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SourceStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SourceStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the source crawl for this collection. This field returns - `not_configured` if the default configuration for this source does not have a - **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - """ - RUNNING = 'running' - COMPLETE = 'complete' - NOT_CONFIGURED = 'not_configured' - QUEUED = 'queued' - UNKNOWN = 'unknown' - - -class StatusDetails(): - """ - Object that contains details about the status of the authentication process. - - :attr bool authenticated: (optional) Indicates whether the credential is - accepted by the target data source. - :attr str error_message: (optional) If `authenticated` is `false`, a message - describes why authentication is unsuccessful. - """ - - def __init__(self, - *, - authenticated: bool = None, - error_message: str = None) -> None: - """ - Initialize a StatusDetails object. - - :param bool authenticated: (optional) Indicates whether the credential is - accepted by the target data source. - :param str error_message: (optional) If `authenticated` is `false`, a - message describes why authentication is unsuccessful. - """ - self.authenticated = authenticated - self.error_message = error_message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'StatusDetails': - """Initialize a StatusDetails object from a json dictionary.""" - args = {} - if 'authenticated' in _dict: - args['authenticated'] = _dict.get('authenticated') - if 'error_message' in _dict: - args['error_message'] = _dict.get('error_message') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a StatusDetails object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'authenticated') and self.authenticated is not None: - _dict['authenticated'] = self.authenticated - if hasattr(self, 'error_message') and self.error_message is not None: - _dict['error_message'] = self.error_message - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this StatusDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'StatusDetails') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'StatusDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TokenDictRule(): - """ - An object defining a single tokenizaion rule. - - :attr str text: The string to tokenize. - :attr List[str] tokens: Array of tokens that the `text` field is split into when - found. - :attr List[str] readings: (optional) Array of tokens that represent the content - of the `text` field in an alternate character set. - :attr str part_of_speech: The part of speech that the `text` string belongs to. - For example `noun`. Custom parts of speech can be specified. - """ - - def __init__(self, - text: str, - tokens: List[str], - part_of_speech: str, - *, - readings: List[str] = None) -> None: - """ - Initialize a TokenDictRule object. - - :param str text: The string to tokenize. - :param List[str] tokens: Array of tokens that the `text` field is split - into when found. - :param str part_of_speech: The part of speech that the `text` string - belongs to. For example `noun`. Custom parts of speech can be specified. - :param List[str] readings: (optional) Array of tokens that represent the - content of the `text` field in an alternate character set. - """ - self.text = text - self.tokens = tokens - self.readings = readings - self.part_of_speech = part_of_speech - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TokenDictRule': - """Initialize a TokenDictRule object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in TokenDictRule JSON') - if 'tokens' in _dict: - args['tokens'] = _dict.get('tokens') - else: - raise ValueError( - 'Required property \'tokens\' not present in TokenDictRule JSON' - ) - if 'readings' in _dict: - args['readings'] = _dict.get('readings') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') - else: - raise ValueError( - 'Required property \'part_of_speech\' not present in TokenDictRule JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TokenDictRule object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens - if hasattr(self, 'readings') and self.readings is not None: - _dict['readings'] = self.readings - if hasattr(self, 'part_of_speech') and self.part_of_speech is not None: - _dict['part_of_speech'] = self.part_of_speech - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TokenDictRule object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TokenDictRule') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TokenDictRule') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TokenDictStatusResponse(): - """ - Object describing the current status of the wordlist. - - :attr str status: (optional) Current wordlist status for the specified - collection. - :attr str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. - """ - - def __init__(self, *, status: str = None, type: str = None) -> None: - """ - Initialize a TokenDictStatusResponse object. - - :param str status: (optional) Current wordlist status for the specified - collection. - :param str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. - """ - self.status = status - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': - """Initialize a TokenDictStatusResponse object from a json dictionary.""" - args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'type' in _dict: - args['type'] = _dict.get('type') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TokenDictStatusResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TokenDictStatusResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TokenDictStatusResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TokenDictStatusResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Current wordlist status for the specified collection. - """ - ACTIVE = 'active' - PENDING = 'pending' - NOT_FOUND = 'not found' - - -class TrainingDataSet(): - """ - Training information for a specific collection. - - :attr str environment_id: (optional) The environment id associated with this - training data set. - :attr str collection_id: (optional) The collection id associated with this - training data set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. - """ - - def __init__(self, - *, - environment_id: str = None, - collection_id: str = None, - queries: List['TrainingQuery'] = None) -> None: - """ - Initialize a TrainingDataSet object. - - :param str environment_id: (optional) The environment id associated with - this training data set. - :param str collection_id: (optional) The collection id associated with this - training data set. - :param List[TrainingQuery] queries: (optional) Array of training queries. - """ - self.environment_id = environment_id - self.collection_id = collection_id - self.queries = queries - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': - """Initialize a TrainingDataSet object from a json dictionary.""" - args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(x) for x in _dict.get('queries') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingDataSet object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x.to_dict() for x in self.queries] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingDataSet object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingDataSet') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TrainingDataSet') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingExample(): - """ - Training example details. - - :attr str document_id: (optional) The document ID associated with this training - example. - :attr str cross_reference: (optional) The cross reference associated with this - training example. - :attr int relevance: (optional) The relevance of the training example. - """ - - def __init__(self, - *, - document_id: str = None, - cross_reference: str = None, - relevance: int = None) -> None: - """ - Initialize a TrainingExample object. - - :param str document_id: (optional) The document ID associated with this - training example. - :param str cross_reference: (optional) The cross reference associated with - this training example. - :param int relevance: (optional) The relevance of the training example. - """ - self.document_id = document_id - self.cross_reference = cross_reference - self.relevance = relevance - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingExample': - """Initialize a TrainingExample object from a json dictionary.""" - args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'cross_reference' in _dict: - args['cross_reference'] = _dict.get('cross_reference') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingExample object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, - 'cross_reference') and self.cross_reference is not None: - _dict['cross_reference'] = self.cross_reference - if hasattr(self, 'relevance') and self.relevance is not None: - _dict['relevance'] = self.relevance - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingExample object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingExample') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TrainingExample') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingExampleList(): - """ - Object containing an array of training examples. - - :attr List[TrainingExample] examples: (optional) Array of training examples. - """ - - def __init__(self, *, examples: List['TrainingExample'] = None) -> None: - """ - Initialize a TrainingExampleList object. - - :param List[TrainingExample] examples: (optional) Array of training - examples. - """ - self.examples = examples - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': - """Initialize a TrainingExampleList object from a json dictionary.""" - args = {} - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingExampleList object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingExampleList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingExampleList') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TrainingExampleList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingQuery(): - """ - Training query details. - - :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: (optional) The natural text query for the - training query. - :attr str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :attr List[TrainingExample] examples: (optional) Array of training examples. - """ - - def __init__(self, - *, - query_id: str = None, - natural_language_query: str = None, - filter: str = None, - examples: List['TrainingExample'] = None) -> None: - """ - Initialize a TrainingQuery object. - - :param str query_id: (optional) The query ID associated with the training - query. - :param str natural_language_query: (optional) The natural text query for - the training query. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param List[TrainingExample] examples: (optional) Array of training - examples. - """ - self.query_id = query_id - self.natural_language_query = natural_language_query - self.filter = filter - self.examples = examples - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingQuery': - """Initialize a TrainingQuery object from a json dictionary.""" - args = {} - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingQuery object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'natural_language_query' - ) and self.natural_language_query is not None: - _dict['natural_language_query'] = self.natural_language_query - if hasattr(self, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingQuery object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingQuery') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TrainingQuery') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingStatus(): - """ - Training status details. - - :attr int total_examples: (optional) The total number of training examples - uploaded to this collection. - :attr bool available: (optional) When `true`, the collection has been - successfully trained. - :attr bool processing: (optional) When `true`, the collection is currently - processing training. - :attr bool minimum_queries_added: (optional) When `true`, the collection has a - sufficent amount of queries added for training to occur. - :attr bool minimum_examples_added: (optional) When `true`, the collection has a - sufficent amount of examples added for training to occur. - :attr bool sufficient_label_diversity: (optional) When `true`, the collection - has a sufficent amount of diversity in labeled results for training to occur. - :attr int notices: (optional) The number of notices associated with this data - set. - :attr datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. - :attr datetime data_updated: (optional) The timestamp of when the data was - uploaded. - """ - - def __init__(self, - *, - total_examples: int = None, - available: bool = None, - processing: bool = None, - minimum_queries_added: bool = None, - minimum_examples_added: bool = None, - sufficient_label_diversity: bool = None, - notices: int = None, - successfully_trained: datetime = None, - data_updated: datetime = None) -> None: - """ - Initialize a TrainingStatus object. - - :param int total_examples: (optional) The total number of training examples - uploaded to this collection. - :param bool available: (optional) When `true`, the collection has been - successfully trained. - :param bool processing: (optional) When `true`, the collection is currently - processing training. - :param bool minimum_queries_added: (optional) When `true`, the collection - has a sufficent amount of queries added for training to occur. - :param bool minimum_examples_added: (optional) When `true`, the collection - has a sufficent amount of examples added for training to occur. - :param bool sufficient_label_diversity: (optional) When `true`, the - collection has a sufficent amount of diversity in labeled results for - training to occur. - :param int notices: (optional) The number of notices associated with this - data set. - :param datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. - :param datetime data_updated: (optional) The timestamp of when the data was - uploaded. - """ - self.total_examples = total_examples - self.available = available - self.processing = processing - self.minimum_queries_added = minimum_queries_added - self.minimum_examples_added = minimum_examples_added - self.sufficient_label_diversity = sufficient_label_diversity - self.notices = notices - self.successfully_trained = successfully_trained - self.data_updated = data_updated - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingStatus': - """Initialize a TrainingStatus object from a json dictionary.""" - args = {} - if 'total_examples' in _dict: - args['total_examples'] = _dict.get('total_examples') - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'minimum_queries_added' in _dict: - args['minimum_queries_added'] = _dict.get('minimum_queries_added') - if 'minimum_examples_added' in _dict: - args['minimum_examples_added'] = _dict.get('minimum_examples_added') - if 'sufficient_label_diversity' in _dict: - args['sufficient_label_diversity'] = _dict.get( - 'sufficient_label_diversity') - if 'notices' in _dict: - args['notices'] = _dict.get('notices') - if 'successfully_trained' in _dict: - args['successfully_trained'] = string_to_datetime( - _dict.get('successfully_trained')) - if 'data_updated' in _dict: - args['data_updated'] = string_to_datetime(_dict.get('data_updated')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'total_examples') and self.total_examples is not None: - _dict['total_examples'] = self.total_examples - if hasattr(self, 'available') and self.available is not None: - _dict['available'] = self.available - if hasattr(self, 'processing') and self.processing is not None: - _dict['processing'] = self.processing - if hasattr(self, 'minimum_queries_added' - ) and self.minimum_queries_added is not None: - _dict['minimum_queries_added'] = self.minimum_queries_added - if hasattr(self, 'minimum_examples_added' - ) and self.minimum_examples_added is not None: - _dict['minimum_examples_added'] = self.minimum_examples_added - if hasattr(self, 'sufficient_label_diversity' - ) and self.sufficient_label_diversity is not None: - _dict[ - 'sufficient_label_diversity'] = self.sufficient_label_diversity - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = self.notices - if hasattr(self, 'successfully_trained' - ) and self.successfully_trained is not None: - _dict['successfully_trained'] = datetime_to_string( - self.successfully_trained) - if hasattr(self, 'data_updated') and self.data_updated is not None: - _dict['data_updated'] = datetime_to_string(self.data_updated) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TrainingStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordHeadingDetection(): - """ - Object containing heading detection conversion settings for Microsoft Word documents. - - :attr List[FontSetting] fonts: (optional) Array of font matching configurations. - :attr List[WordStyle] styles: (optional) Array of Microsoft Word styles to - convert. - """ - - def __init__(self, - *, - fonts: List['FontSetting'] = None, - styles: List['WordStyle'] = None) -> None: - """ - Initialize a WordHeadingDetection object. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to - convert. - """ - self.fonts = fonts - self.styles = styles - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': - """Initialize a WordHeadingDetection object from a json dictionary.""" - args = {} - if 'fonts' in _dict: - args['fonts'] = [ - FontSetting.from_dict(x) for x in _dict.get('fonts') - ] - if 'styles' in _dict: - args['styles'] = [ - WordStyle.from_dict(x) for x in _dict.get('styles') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WordHeadingDetection object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x.to_dict() for x in self.fonts] - if hasattr(self, 'styles') and self.styles is not None: - _dict['styles'] = [x.to_dict() for x in self.styles] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this WordHeadingDetection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WordHeadingDetection') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'WordHeadingDetection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordSettings(): - """ - A list of Word conversion settings. - - :attr WordHeadingDetection heading: (optional) Object containing heading - detection conversion settings for Microsoft Word documents. - """ - - def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: - """ - Initialize a WordSettings object. - - :param WordHeadingDetection heading: (optional) Object containing heading - detection conversion settings for Microsoft Word documents. - """ - self.heading = heading - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordSettings': - """Initialize a WordSettings object from a json dictionary.""" - args = {} - if 'heading' in _dict: - args['heading'] = WordHeadingDetection.from_dict( - _dict.get('heading')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WordSettings object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this WordSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WordSettings') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'WordSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordStyle(): - """ - Microsoft Word styles to convert into a specified HTML head level. - - :attr int level: (optional) HTML head level that content matching this style is - tagged with. - :attr List[str] names: (optional) Array of word style names to convert. - """ - - def __init__(self, *, level: int = None, names: List[str] = None) -> None: - """ - Initialize a WordStyle object. - - :param int level: (optional) HTML head level that content matching this - style is tagged with. - :param List[str] names: (optional) Array of word style names to convert. - """ - self.level = level - self.names = names - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordStyle': - """Initialize a WordStyle object from a json dictionary.""" - args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'names' in _dict: - args['names'] = _dict.get('names') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WordStyle object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'names') and self.names is not None: - _dict['names'] = self.names - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this WordStyle object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WordStyle') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'WordStyle') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class XPathPatterns(): - """ - Object containing an array of XPaths. - - :attr List[str] xpaths: (optional) An array to XPaths. - """ - - def __init__(self, *, xpaths: List[str] = None) -> None: - """ - Initialize a XPathPatterns object. - - :param List[str] xpaths: (optional) An array to XPaths. - """ - self.xpaths = xpaths - - @classmethod - def from_dict(cls, _dict: Dict) -> 'XPathPatterns': - """Initialize a XPathPatterns object from a json dictionary.""" - args = {} - if 'xpaths' in _dict: - args['xpaths'] = _dict.get('xpaths') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a XPathPatterns object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'xpaths') and self.xpaths is not None: - _dict['xpaths'] = self.xpaths - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this XPathPatterns object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'XPathPatterns') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'XPathPatterns') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryCalculationAggregation(QueryAggregation): - """ - Returns a scalar calculation across all documents for the field specified. Possible - calculations include min, max, sum, average, and unique_count. - - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. - """ - - def __init__(self, type: str, field: str, *, value: float = None) -> None: - """ - Initialize a QueryCalculationAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The field to perform the calculation on. - :param float value: (optional) The value of the calculation. - """ - self.type = type - self.field = field - self.value = value - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': - """Initialize a QueryCalculationAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryCalculationAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' - ) - if 'value' in _dict: - args['value'] = _dict.get('value') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryCalculationAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryCalculationAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryCalculationAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryFilterAggregation(QueryAggregation): - """ - A modifier that narrows the document set of the sub-aggregations it precedes. - - :attr str match: The filter that is written in Discovery Query Language syntax - and is applied to the documents before sub-aggregations are run. - :attr int matching_results: Number of documents that match the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__(self, - type: str, - match: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: - """ - Initialize a QueryFilterAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str match: The filter that is written in Discovery Query Language - syntax and is applied to the documents before sub-aggregations are run. - :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.type = type - self.match = match - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': - """Initialize a QueryFilterAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryFilterAggregation JSON' - ) - if 'match' in _dict: - args['match'] = _dict.get('match') - else: - raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryFilterAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryFilterAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryFilterAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryHistogramAggregation(QueryAggregation): - """ - Numeric interval segments to categorize documents by using field values from a single - numeric field to describe the category. - - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. - """ - - def __init__( - self, - type: str, - field: str, - interval: int, - *, - name: str = None, - results: List['QueryHistogramAggregationResult'] = None) -> None: - """ - Initialize a QueryHistogramAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections that the results are split - into. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - self.type = type - self.field = field - self.interval = interval - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': - """Initialize a QueryHistogramAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryHistogramAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' - ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: - args['results'] = [ - QueryHistogramAggregationResult.from_dict(x) - for x in _dict.get('results') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryHistogramAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryHistogramAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryHistogramAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNestedAggregation(QueryAggregation): - """ - A restriction that alters the document set that is used for sub-aggregations it - precedes to nested documents found in the field specified. - - :attr str path: The path to the document field to scope sub-aggregations to. - :attr int matching_results: Number of nested documents found in the specified - field. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__(self, - type: str, - path: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: - """ - Initialize a QueryNestedAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str path: The path to the document field to scope sub-aggregations - to. - :param int matching_results: Number of nested documents found in the - specified field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.type = type - self.path = path - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': - """Initialize a QueryNestedAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryNestedAggregation JSON' - ) - if 'path' in _dict: - args['path'] = _dict.get('path') - else: - raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryNestedAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryNestedAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryNestedAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregation(QueryAggregation): - """ - Returns the top values for the field specified. - - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryTermAggregationResult] results: (optional) Array of top values - for the field. - """ - - def __init__(self, - type: str, - field: str, - *, - count: int = None, - name: str = None, - results: List['QueryTermAggregationResult'] = None) -> None: - """ - Initialize a QueryTermAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top - values for the field. - """ - self.type = type - self.field = field - self.count = count - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': - """Initialize a QueryTermAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTermAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: - args['results'] = [ - QueryTermAggregationResult.from_dict(x) - for x in _dict.get('results') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTermAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTermAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryTermAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregation(QueryAggregation): - """ - A specialized histogram aggregation that uses dates to create interval segments. - - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, - hours, days, weeks, and years. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. - """ - - def __init__( - self, - type: str, - field: str, - interval: str, - *, - name: str = None, - results: List['QueryTimesliceAggregationResult'] = None) -> None: - """ - Initialize a QueryTimesliceAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The date field name used to create the timeslice. - :param str interval: The date interval value. Valid values are seconds, - minutes, hours, days, weeks, and years. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. - """ - self.type = type - self.field = field - self.interval = interval - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTimesliceAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' - ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: - args['results'] = [ - QueryTimesliceAggregationResult.from_dict(x) - for x in _dict.get('results') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTimesliceAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryTimesliceAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregation(QueryAggregation): - """ - Returns the top documents ranked by the score of the query. - - :attr int size: The number of documents to return. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) - """ - - def __init__(self, - type: str, - size: int, - *, - name: str = None, - hits: 'QueryTopHitsAggregationResult' = None) -> None: - """ - Initialize a QueryTopHitsAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param int size: The number of documents to return. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param QueryTopHitsAggregationResult hits: (optional) - """ - self.type = type - self.size = size - self.name = name - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTopHitsAggregation JSON' - ) - if 'size' in _dict: - args['size'] = _dict.get('size') - else: - raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult.from_dict( - _dict.get('hits')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTopHitsAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTopHitsAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryTopHitsAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 708007d08..642007426 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2019, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ -IBM Watson™ Discovery is a cognitive search and content analytics engine that you -can add to applications to identify patterns, trends and actionable insights to drive -better decision-making. Securely unify structured and unstructured data with pre-enriched +IBM Watson® Discovery is a cognitive search and content analytics engine that you can +add to applications to identify patterns, trends and actionable insights to drive better +decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of results. @@ -29,7 +29,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -61,10 +61,10 @@ def __init__( Construct a new client for the Discovery service. :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-08-30`. + Specify dates in YYYY-MM-DD format. The current version is `2023-03-31`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -79,92 +79,101 @@ def __init__( self.configure_service(service_name) ######################### - # Collections + # Projects ######################### - def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: + def list_projects( + self, + **kwargs, + ) -> DetailedResponse: """ - List collections. + List projects. - Lists existing collections for the specified project. + Lists existing projects for this instance. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object + :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object """ - if project_id is None: - raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_collections') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_projects', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects' + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_collection(self, - project_id: str, - name: str, - *, - description: str = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def create_project( + self, + name: str, + type: str, + *, + default_query_parameters: Optional['DefaultQueryParams'] = None, + **kwargs, + ) -> DetailedResponse: """ - Create a collection. + Create a project. - Create a new collection in the specified project. + Create a new project for this instance. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str language: (optional) The language of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + :param str name: The human readable name of this project. + :param str type: The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* + project and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with + Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from + IBM Cloud-managed instances only. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: - raise ValueError('project_id must be provided') if name is None: raise ValueError('name must be provided') - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] + if type is None: + raise ValueError('type must be provided') + if default_query_parameters is not None: + default_query_parameters = convert_model(default_query_parameters) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_project', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, - 'description': description, - 'language': language, - 'enrichments': enrichments + 'type': type, + 'default_query_parameters': default_query_parameters, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -172,108 +181,109 @@ def create_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + url = '/v2/projects' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_project( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - Get collection. + Get project. - Get details about the specified collection. + Get details on the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_project', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_collection(self, - project_id: str, - collection_id: str, - *, - name: str = None, - description: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def update_project( + self, + project_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ - Update a collection. + Update a project. - Updates the specified collection's name, description, and enrichments. + Update the specified project's name. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param str name: (optional) The name of the collection. - :param str description: (optional) A description of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str name: (optional) The new name to give this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_project', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, - 'description': description, - 'enrichments': enrichments } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -281,501 +291,482 @@ def update_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + url = '/v2/projects/{project_id}'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_project( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - Delete a collection. + Delete a project. - Deletes the specified collection from the project. All documents stored in the - specified collection and not shared is also deleted. + Deletes the specified project. + **Important:** Deleting a project deletes everything that is part of the specified + project, including all collections. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_project', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}'.format(**path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - ######################### - # Queries - ######################### - - def query(self, - project_id: str, - *, - collection_ids: List[str] = None, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - spelling_suggestions: bool = None, - table_results: 'QueryLargeTableResults' = None, - suggested_refinements: 'QueryLargeSuggestedRefinements' = None, - passages: 'QueryLargePassages' = None, - **kwargs) -> DetailedResponse: + def list_fields( + self, + project_id: str, + *, + collection_ids: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ - Query a project. + List fields. - By using this method, you can construct queries. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). - The default query parameters are defined by the settings for this project, see the - [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-project-defaults) - for an overview of the standard default settings, and see [the Projects API - documentation](#create-project) for details about how to set custom default query - settings. + Gets a list of the unique fields (and their types) stored in the specified + collections. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param List[str] collection_ids: (optional) A comma-separated list of - collection IDs to be queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param List[str] return_: (optional) A list of the fields in the document - hierarchy to return. If this parameter is an empty list, then all fields - are returned. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When `true`, a highlight field is - returned for each result which contains the fields which match the query - with `` tags around the matching query terms. - :param bool spelling_suggestions: (optional) When `true` and the - **natural_language_query** parameter is used, the - **natural_language_query** parameter is spell checked. The most likely - correction is returned in the **suggested_query** field of the response (if - one exists). - :param QueryLargeTableResults table_results: (optional) Configuration for - table retrieval. - :param QueryLargeSuggestedRefinements suggested_refinements: (optional) - Configuration for suggested refinements. Available with Premium plans only. - :param QueryLargePassages passages: (optional) Configuration for passage - retrieval. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param List[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object + :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if table_results is not None: - table_results = convert_model(table_results) - if suggested_refinements is not None: - suggested_refinements = convert_model(suggested_refinements) - if passages is not None: - passages = convert_model(passages) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_fields', + ) headers.update(sdk_headers) - params = {'version': self.version} - - data = { - 'collection_ids': collection_ids, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'spelling_suggestions': spelling_suggestions, - 'table_results': table_results, - 'suggested_refinements': suggested_refinements, - 'passages': passages + params = { + 'version': self.version, + 'collection_ids': convert_list(collection_ids), } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/query'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - project_id: str, - prefix: str, - *, - collection_ids: List[str] = None, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + ######################### + # Collections + ######################### + + def list_collections( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - Get Autocomplete Suggestions. + List collections. - Returns completion query suggestions for the specified prefix. + Lists existing collections for the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. - :param List[str] collection_ids: (optional) Comma separated list of the - collection IDs. If this parameter is not specified, all collections in the - project are used. - :param str field: (optional) The field in the result documents that - autocompletion suggestions are identified from. - :param int count: (optional) The number of autocompletion suggestions to - return. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Completions` object + :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if prefix is None: - raise ValueError('prefix must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_autocompletion') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_collections', + ) headers.update(sdk_headers) params = { 'version': self.version, - 'prefix': prefix, - 'collection_ids': convert_list(collection_ids), - 'field': field, - 'count': count } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/autocompletion'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def query_collection_notices(self, - project_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def create_collection( + self, + project_id: str, + name: str, + *, + description: Optional[str] = None, + language: Optional[str] = None, + ocr_enabled: Optional[bool] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + **kwargs, + ) -> DetailedResponse: """ - Query collection notices. + Create a collection. - Finds collection-level notices (errors and warnings) that are generated when - documents are ingested. + Create a new collection in the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. For a list + of supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of + enrichments that are available for a project, use the [List + enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about + project default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') + if name is None: + raise ValueError('name must be provided') + if enrichments is not None: + enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query_collection_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_collection', + ) headers.update(sdk_headers) params = { 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'count': count, - 'offset': offset } + data = { + 'name': name, + 'description': description, + 'language': language, + 'ocr_enabled': ocr_enabled, + 'enrichments': enrichments, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def query_notices(self, - project_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def get_collection( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - Query project notices. + Get collection details. - Finds project-level notices (errors and warnings). Currently, project-level - notices are generated by relevancy training. + Get details about the specified collection. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_collection', + ) headers.update(sdk_headers) params = { 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'count': count, - 'offset': offset } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_fields(self, - project_id: str, - *, - collection_ids: List[str] = None, - **kwargs) -> DetailedResponse: + def update_collection( + self, + project_id: str, + collection_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ocr_enabled: Optional[bool] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + **kwargs, + ) -> DetailedResponse: """ - List fields. - - Gets a list of the unique fields (and their types) stored in the the specified - collections. + Update a collection. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param List[str] collection_ids: (optional) Comma separated list of the - collection IDs. If this parameter is not specified, all collections in the - project are used. + Updates the specified collection's name, description, enrichments, and + configuration. + If you apply normalization rules to data in an existing collection, you must + initiate reprocessing of the collection. To do so, from the *Manage fields* page + in the product user interface, temporarily change the data type of a field to + enable the reprocess button. Change the data type of the field back to its + original value, and then click **Apply changes and reprocess**. + To remove a configuration that applies JSON normalization operations as part of + the conversion phase of ingestion, specify an empty `json_normalizations` object + (`[]`) in the request. + To remove a configuration that applies JSON normalization operations after + enrichments are applied, specify an empty `normalizations` object (`[]`) in the + request. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str name: (optional) The new name of the collection. + :param str description: (optional) The new description of the collection. + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if enrichments is not None: + enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_collection', + ) headers.update(sdk_headers) params = { 'version': self.version, - 'collection_ids': convert_list(collection_ids) } + data = { + 'name': name, + 'description': description, + 'ocr_enabled': ocr_enabled, + 'enrichments': enrichments, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - ######################### - # Component settings - ######################### - - def get_component_settings(self, project_id: str, - **kwargs) -> DetailedResponse: + def delete_collection( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - List component settings. + Delete a collection. - Returns default configuration settings for components. + Deletes the specified collection from the project. All documents stored in the + specified collection and not shared is also deleted. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object + :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_component_settings') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_collection', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/component_settings'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -784,57 +775,175 @@ def get_component_settings(self, project_id: str, # Documents ######################### - def add_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def list_documents( + self, + project_id: str, + collection_id: str, + *, + count: Optional[int] = None, + status: Optional[str] = None, + has_notices: Optional[bool] = None, + is_parent: Optional[bool] = None, + parent_document_id: Optional[str] = None, + sha256: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + List documents. + + Lists the documents in the specified collection. The list includes only the + document ID of each document and returns information for up to 10,000 documents. + **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and + later installed instances, and from IBM Cloud-managed instances. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param int count: (optional) The maximum number of documents to return. Up + to 1,000 documents are returned by default. The maximum number allowed is + 10,000. + :param str status: (optional) Filters the documents to include only + documents with the specified ingestion status. The options include: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because + of an error. + * `pending`: The document is uploaded, but the ingestion process is not + started. + * `processing`: Ingestion is in progress. + You can specify one status value or add a comma-separated list of more than + one status value. For example, `available,failed`. + :param bool has_notices: (optional) If set to `true`, only documents that + have notices, meaning documents for which warnings or errors were generated + during the ingestion, are returned. If set to `false`, only documents that + don't have notices are returned. If unspecified, no filter based on notices + is applied. + Notice details are not available in the result, but you can use the [Query + collection notices](#querycollectionnotices) method to find details by + adding the parameter `query=notices.document_id:{document-id}`. + :param bool is_parent: (optional) If set to `true`, only parent documents, + meaning documents that were split during the ingestion process and resulted + in two or more child documents, are returned. If set to `false`, only child + documents are returned. If unspecified, no filter based on the parent or + child relationship is applied. + CSV files, for example, are split into separate documents per line and JSON + files are split into separate documents per object. + :param str parent_document_id: (optional) Filters the documents to include + only child documents that were generated when the specified parent document + was processed. + :param str sha256: (optional) Filters the documents to include only + documents with the specified SHA-256 hash. Format the hash as a hexadecimal + string. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListDocumentsResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_documents', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'count': count, + 'status': status, + 'has_notices': has_notices, + 'is_parent': is_parent, + 'parent_document_id': parent_document_id, + 'sha256': sha256, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def add_document( + self, + project_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a document. Add a document to a collection with optional metadata. Returns immediately after the system has accepted the document for processing. - * The user must provide document content, metadata, or both. If the request is - missing both document content and metadata, it is rejected. + Use this method to upload a file to the collection. You cannot use this method to + crawl an external data source. + * For a list of supported file types, see the [product + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + * You must provide document content, metadata, or both. If the request is missing + both document content and metadata, it is rejected. * You can set the **Content-Type** parameter on the **file** part to indicate the media type of the document. If the **Content-Type** parameter is missing or is one of the generic media types (for example, `application/octet-stream`), then the service attempts to automatically detect the document's media type. - * The following field names are reserved and are filtered out if present after - normalization: `id`, `score`, `highlight`, and any field with the prefix of: `_`, - `+`, or `-` - * Fields with empty name values after normalization are filtered out before - indexing. - * Fields that contain the following characters after normalization are filtered - out before indexing: `#` and `,` - If the document is uploaded to a collection that shares its data with another + * If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** You can assign an ID to a document that you add by appending the ID to - the endpoint + * In curl requests only, you can assign an ID to a document that you add by + appending the ID to the endpoint (`/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}`). If a document already exists with the specified ID, it is replaced. - **Note:** This operation works with a file upload collection. It cannot be used to - modify a collection that crawls an external data source. - - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + For more information about how certain file types and field names are handled when + a file is added to a collection, see the [product + documentation](/docs/discovery-data?topic=discovery-data-index-overview#field-name-limits). + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is shared with other collections. @@ -843,17 +952,23 @@ def add_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='add_document') + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='add_document', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -868,6 +983,7 @@ def add_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id'] @@ -875,56 +991,137 @@ def add_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + + def get_document( + self, + project_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get document details. + + Get details about a specific document, whether the document is added by uploading + a file or by crawling an external data source. + **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and + later installed instances, and from IBM Cloud-managed instances. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str document_id: The ID of the document. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentDetails` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not document_id: + raise ValueError('document_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document(self, - project_id: str, - collection_id: str, - document_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def update_document( + self, + project_id: str, + collection_id: str, + document_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document. - Replace an existing document or add a document with a specified **document_id**. + Replace an existing document or add a document with a specified document ID. Starts ingesting a document with optional metadata. + Use this method to upload a file to a collection. You cannot use this method to + crawl an external data source. If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** When uploading a new document with this method it automatically replaces - any document stored with the same **document_id** if it exists. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. - **Note:** If an uploaded document is segmented, all segments are overwritten, even - if the updated version of the document has fewer segments. - - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + **Notes:** + * Uploading a new document with this method automatically replaces any existing + document stored with the same document ID. + * If an uploaded document is split into child documents during ingestion, all + existing child documents are overwritten, even if the updated version of the + document has fewer child documents. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str document_id: The ID of the document. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is shared with other collections. @@ -933,19 +1130,25 @@ def update_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_document') + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -960,6 +1163,7 @@ def update_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id', 'document_id'] @@ -968,37 +1172,63 @@ def update_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document(self, - project_id: str, - collection_id: str, - document_id: str, - *, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def delete_document( + self, + project_id: str, + collection_id: str, + document_id: str, + *, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Delete a document. - If the given document ID is invalid, or if the document is not found, then the a - success response is returned (HTTP status code `200`) with the status set to - 'deleted'. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. - **Note:** Segments of an uploaded document cannot be deleted individually. Delete - all segments by deleting using the `parent_document_id` of a segment result. - - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + Deletes the document with the document ID that you specify from the collection. + Removes uploaded documents from the collection permanently. If you delete a + document that was added by crawling an external data source, the document will be + added again with the next scheduled crawl of the data source. The delete function + removes the document from the collection, not from the external data source. + **Note:** Files such as CSV or JSON files generate subdocuments when they are + added to a collection. If you delete a subdocument, and then repeat the action + that created it, the deleted document is added back in to your collection. To + remove subdocuments that are generated by an uploaded file, delete the original + document instead. You can get the document ID of the original document from the + `parent_document_id` of the subdocument result. + If the document with the given document ID exists, Watson Discovery first marks or + tags the document as deleted when it sends the 200 response code. At a later time + (within a couple of minutes unless the document has many child documents), it + removes the document from the collection. + There is no bulk document delete API. Documents must be deleted one at a time + using this API. However, you can delete a collection, and all the documents from + the collection are removed along with the collection. + The document will be deleted from the given collection only, not from the + corresponding data source. Wherever relevant, an incremental crawl will not bring + back the document into Watson Discovery from the data source. Only a full crawl + will retrieve the deleted document back from the data source provided it is still + present in the same data source. + Finally, if multiple collections share the same dataset, deleting a document from + a collection will remove it from that collection only (in other remaining + collections the document will still exist). The document will be removed from the + dataset, if this document is deleted from all the collections that share the same + dataset. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str document_id: The ID of the document. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is @@ -1008,22 +1238,29 @@ def delete_document(self, :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_document') + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id', 'document_id'] @@ -1032,732 +1269,1069 @@ def delete_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response ######################### - # Training data + # Queries ######################### - def list_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def query( + self, + project_id: str, + *, + collection_ids: Optional[List[str]] = None, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + spelling_suggestions: Optional[bool] = None, + table_results: Optional['QueryLargeTableResults'] = None, + suggested_refinements: Optional[ + 'QueryLargeSuggestedRefinements'] = None, + passages: Optional['QueryLargePassages'] = None, + similar: Optional['QueryLargeSimilar'] = None, + **kwargs, + ) -> DetailedResponse: """ - List training queries. - - List the training queries for the specified project. + Query a project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + Search your data by submitting queries that are written in natural language or + formatted in the Discovery Query Language. For more information, see the + [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-concepts). The + default query parameters differ by project type. For more information about the + project default settings, see the [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-defaults). See [the + Projects API documentation](#create-project) for details about how to set custom + default query settings. + The length of the UTF-8 encoding of the POST body cannot exceed 10,000 bytes, + which is roughly equivalent to 10,000 characters in English. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param List[str] collection_ids: (optional) A comma-separated list of + collection IDs to be queried against. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the **aggregation**, **query**, or + **natural_language_query** parameters, the **filter** parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. Use a query search when you want to find the most + relevant search results. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. You can use this parameter or the **query** parameter to + specify the query input, but not both. To filter the results based on + criteria you specify, include the **filter** parameter in the request. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For more information + about the supported types of aggregations, see the [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-aggregations). + :param int count: (optional) Number of results to return. + :param List[str] return_: (optional) A list of the fields in the document + hierarchy to return. You can specify both root-level (`text`) and nested + (`extracted_metadata.filename`) fields. If this parameter is an empty list, + then all fields are returned. + :param int offset: (optional) The number of query results to skip at the + beginning. Consider that the `count` is set to 10 (the default value) and + the total number of results that are returned is 100. In this case, the + following examples show the returned results for different `offset` values: + * If `offset` is set to 95, it returns the last 5 results. + * If `offset` is set to 10, it returns the second batch of 10 results. + * If `offset` is set to 100 or more, it returns empty results. + :param str sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. + :param bool highlight: (optional) When `true`, a highlight field is + returned for each result that contains fields that match the query. The + matching query terms are emphasized with surrounding `` tags. This + parameter is ignored if **passages.enabled** and **passages.per_document** + are `true`, in which case passages are returned for each document instead + of highlights. + :param bool spelling_suggestions: (optional) When `true` and the + **natural_language_query** parameter is used, the + **natural_language_query** parameter is spell checked. The most likely + correction is returned in the **suggested_query** field of the response (if + one exists). + :param QueryLargeTableResults table_results: (optional) Configuration for + table retrieval. + :param QueryLargeSuggestedRefinements suggested_refinements: (optional) + Configuration for suggested refinements. + **Note**: The **suggested_refinements** parameter that identified dynamic + facets from the data is deprecated. + :param QueryLargePassages passages: (optional) Configuration for passage + retrieval. + :param QueryLargeSimilar similar: (optional) Finds results from documents + that are similar to documents of interest. Use this parameter to add a + *More like these* function to your search. You can include this parameter + with or without a **query**, **filter** or **natural_language_query** + parameter. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object + :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if table_results is not None: + table_results = convert_model(table_results) + if suggested_refinements is not None: + suggested_refinements = convert_model(suggested_refinements) + if passages is not None: + passages = convert_model(passages) + if similar is not None: + similar = convert_model(similar) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_training_queries') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } + + data = { + 'collection_ids': collection_ids, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'aggregation': aggregation, + 'count': count, + 'return': return_, + 'offset': offset, + 'sort': sort, + 'highlight': highlight, + 'spelling_suggestions': spelling_suggestions, + 'table_results': table_results, + 'suggested_refinements': suggested_refinements, + 'passages': passages, + 'similar': similar, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/query'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def get_autocompletion( + self, + project_id: str, + prefix: str, + *, + collection_ids: Optional[List[str]] = None, + field: Optional[str] = None, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ - Delete training queries. + Get Autocomplete Suggestions. - Removes all training queries for the specified project. + Returns completion query suggestions for the specified prefix. + Suggested words are based on terms from the project documents. Suggestions are not + based on terms from the project's search history, and the project does not learn + from previous user choices. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str prefix: The prefix to use for autocompletion. For example, the + prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. + :param List[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. + :param str field: (optional) The field in the result documents that + autocompletion suggestions are identified from. + :param int count: (optional) The number of autocompletion suggestions to + return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Completions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not prefix: + raise ValueError('prefix must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_training_queries') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_autocompletion', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'prefix': prefix, + 'collection_ids': convert_list(collection_ids), + 'field': field, + 'count': count, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( + url = '/v2/projects/{project_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_training_query(self, - project_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + def query_collection_notices( + self, + project_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ - Create training query. + Query collection notices. - Add a query to the training data for this project. The query can contain a filter - and natural language query. + Finds collection-level notices (errors and warnings) that are generated when + documents are ingested. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str natural_language_query: The natural text query for the training - query. - :param List[TrainingExample] examples: Array of training examples. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the `aggregation`, `query`, or + `natural_language_query` parameters, the `filter` parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using natural language understanding. You can + use this parameter or the **query** parameter to specify the query input, + but not both. To filter the results based on criteria you specify, include + the **filter** parameter in the request. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is + **10,000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if natural_language_query is None: - raise ValueError('natural_language_query must be provided') - if examples is None: - raise ValueError('examples must be provided') - examples = [convert_model(x) for x in examples] + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_collection_notices', + ) headers.update(sdk_headers) - params = {'version': self.version} - - data = { + params = { + 'version': self.version, + 'filter': filter, + 'query': query, 'natural_language_query': natural_language_query, - 'examples': examples, - 'filter': filter + 'count': count, + 'offset': offset, } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def query_notices( + self, + project_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ - Get a training data query. + Query project notices. - Get details for a specific training data query, including the query string and all - examples. + Finds project-level notices (errors and warnings). Currently, project-level + notices are generated by relevancy training. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the `aggregation`, `query`, or + `natural_language_query` parameters, the `filter` parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using natural language understanding. You can + use this parameter or the **query** parameter to specify the query input, + but not both. To filter the results based on criteria you specify, include + the **filter** parameter in the request. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is + **10,000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_notices', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'count': count, + 'offset': offset, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_training_query(self, - project_id: str, - query_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + ######################### + # Query modifications + ######################### + + def get_stopword_list( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - Update a training query. + Get a custom stop words list. - Updates an existing training query and it's examples. + Returns the custom stop words list that is used by the collection. For information + about the default stop words lists that are applied to queries, see [the product + documentation](/docs/discovery-data?topic=discovery-data-stopwords). - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. - :param str natural_language_query: The natural text query for the training - query. - :param List[TrainingExample] examples: Array of training examples. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - if natural_language_query is None: - raise ValueError('natural_language_query must be provided') - if examples is None: - raise ValueError('examples must be provided') - examples = [convert_model(x) for x in examples] + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_stopword_list', + ) headers.update(sdk_headers) - params = {'version': self.version} - - data = { - 'natural_language_query': natural_language_query, - 'examples': examples, - 'filter': filter + params = { + 'version': self.version, } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a training data query. - - Removes details from a training data query, including the query string and all - examples. - - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. + def create_stopword_list( + self, + project_id: str, + collection_id: str, + *, + stopwords: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create a custom stop words list. + + Adds a list of custom stop words. Stop words are words that you want the service + to ignore when they occur in a query because they're not useful in distinguishing + the semantic meaning of the query. The stop words list cannot contain more than 1 + million characters. + A default stop words list is used by all collections. The default list is applied + both at indexing time and at query time. A custom stop words list that you add is + used at query time only. + The custom stop words list augments the default stop words list; you cannot remove + stop words. For information about the default stop words lists per language, see + [the product documentation](/docs/discovery-data?topic=discovery-data-stopwords). + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param List[str] stopwords: (optional) List of stop words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_stopword_list', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } + + data = { + 'stopwords': stopwords, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - ######################### - # analyze - ######################### - - def analyze_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def delete_stopword_list( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - Analyze a Document. + Delete a custom stop words list. - Process a document and return it for realtime use. Supports JSON files only. - The document is processed according to the collection's configuration settings but - is not stored in the collection. - **Note:** This method is supported on installed instances of Discovery only. - - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + Deletes a custom stop words list to stop using it in queries against the + collection. After a custom stop words list is deleted, the default stop words list + is used. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object + :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='analyze_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_stopword_list', + ) headers.update(sdk_headers) - params = {'version': self.version} - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] path_param_keys = ['project_id', 'collection_id'] path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - ######################### - # enrichments - ######################### - - def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: + def list_expansions( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - List Enrichments. + Get the expansion list. - Lists the enrichments available to this project. The *Part of Speech* and - *Sentiment of Phrases* enrichments might be listed, but are reserved for internal - use only. + Returns the current expansion list for the specified collection. If an expansion + list is not specified, an empty expansions array is returned. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichments` object + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_enrichments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_expansions', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_enrichment(self, - project_id: str, - enrichment: 'CreateEnrichment', - *, - file: BinaryIO = None, - **kwargs) -> DetailedResponse: - """ - Create an enrichment. - - Create an enrichment for use with the specified project. - - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param CreateEnrichment enrichment: Information about a specific - enrichment. - :param BinaryIO file: (optional) The enrichment file to upload. + def create_expansions( + self, + project_id: str, + collection_id: str, + expansions: List['Expansion'], + **kwargs, + ) -> DetailedResponse: + """ + Create or update an expansion list. + + Creates or replaces the expansion list for this collection. An expansion list + introduces alternative wording for key terms that are mentioned in your + collection. By identifying synonyms or common misspellings, you expand the scope + of a query beyond exact matches. The maximum number of expanded terms allowed per + collection is 5,000. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to + include all expanded terms. For example, a query for `ibm` expands to `ibm + OR international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced + by the terms in `expanded_terms`. For example, a query for the often + misused term `on premise` is converted to `on premises OR on-premises` and + does not contain the original term. If you want an input term to be + included in the query, then repeat the input term in the expanded terms + list. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment is None: - raise ValueError('enrichment must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if expansions is None: + raise ValueError('expansions must be provided') + expansions = [convert_model(x) for x in expansions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_expansions', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - form_data = [] - form_data.append( - ('enrichment', (None, json.dumps(enrichment), 'application/json'))) - if file: - form_data.append(('file', (None, file, 'application/octet-stream'))) + data = { + 'expansions': expansions, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ - Get enrichment. + Delete the expansion list. - Get details about a specific enrichment. + Removes the expansion information for this collection. To disable query expansion + for a collection, delete the expansion list. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_expansions', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_enrichment(self, - project_id: str, - enrichment_id: str, - name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + ######################### + # Component settings + ######################### + + def get_component_settings( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - Update an enrichment. + List component settings. - Updates an existing enrichment's name and description. + Returns default configuration settings for components. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. - :param str name: A new name for the enrichment. - :param str description: (optional) A new description for the enrichment. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') - if name is None: - raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_component_settings', + ) headers.update(sdk_headers) - params = {'version': self.version} - - data = {'name': name, 'description': description} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/component_settings'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + ######################### + # Training data + ######################### + + def list_training_queries( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - Delete an enrichment. + List training queries. - Deletes an existing enrichment from the specified project. - **Note:** Only enrichments that have been manually created can be deleted. + List the training queries for the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_training_queries', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - ######################### - # projects - ######################### - - def list_projects(self, **kwargs) -> DetailedResponse: + def delete_training_queries( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - List projects. + Delete training queries. - Lists existing projects for this instance. + Removes all training queries for the specified project. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object + :rtype: DetailedResponse """ + if not project_id: + raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_projects') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_queries', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - url = '/v2/projects' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_project(self, - name: str, - type: str, - *, - default_query_parameters: 'DefaultQueryParams' = None, - **kwargs) -> DetailedResponse: + def create_training_query( + self, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ - Create a Project. + Create a training query. - Create a new project for this instance. + Add a query to the training data for this project. The query can contain a filter + and natural language query. + **Note**: You cannot apply relevancy training to a `content_mining` project type. - :param str name: The human readable name of this project. - :param str type: The type of project. - The `content_intelligence` type is a *Document Retrieval for Contracts* - project and the `other` type is a *Custom* project. - The `content_mining` and `content_intelligence` types are available with - Premium plan managed deployments and installed deployments only. - :param DefaultQueryParams default_query_parameters: (optional) Default - query parameters for this project. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str natural_language_query: The natural text query that is used as + the training query. + :param List[TrainingExample] examples: Array of training examples. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if name is None: - raise ValueError('name must be provided') - if type is None: - raise ValueError('type must be provided') - if default_query_parameters is not None: - default_query_parameters = convert_model(default_query_parameters) + if not project_id: + raise ValueError('project_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_training_query', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { - 'name': name, - 'type': type, - 'default_query_parameters': default_query_parameters + 'natural_language_query': natural_language_query, + 'examples': examples, + 'filter': filter, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1765,296 +2339,2804 @@ def create_project(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - url = '/v2/projects' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_project(self, project_id: str, **kwargs) -> DetailedResponse: + def get_training_query( + self, + project_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ - Get project. + Get a training data query. - Get details on the specified project. + Get details for a specific training data query, including the query string and all + examples. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not query_id: + raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_training_query', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_project(self, - project_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def update_training_query( + self, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ - Update a project. + Update a training query. - Update the specified project's name. + Updates an existing training query and its examples. You must resubmit all of the + examples with the update request. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str name: (optional) The new name to give this project. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str query_id: The ID of the query used for training. + :param str natural_language_query: The natural text query that is used as + the training query. + :param List[TrainingExample] examples: Array of training examples. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not query_id: + raise ValueError('query_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_training_query', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name} + data = { + 'natural_language_query': natural_language_query, + 'examples': examples, + 'filter': filter, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: + def delete_training_query( + self, + project_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ - Delete a project. + Delete a training data query. - Deletes the specified project. - **Important:** Deleting a project deletes everything that is part of the specified - project, including all collections. + Removes details from a training data query, including the query string and all + examples. + To delete an example, use the *Update a training query* method and omit the + example that you want to delete from the example set. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not query_id: + raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_query', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response ######################### - # userData + # Enrichments ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def list_enrichments( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ - Delete labeled data. + List enrichments. - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - You associate a customer ID with data by passing the **X-Watson-Metadata** header - with a request that passes data. For more information about personal data and - customer IDs, see [Information - security](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-information-security#information-security). - **Note:** This method is only supported on IBM Cloud instances of Discovery. + Lists the enrichments available to this project. The *Part of Speech* and + *Sentiment of Phrases* enrichments might be listed, but are reserved for internal + use only. - :param str customer_id: The customer ID for which all data is to be - deleted. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichments` object """ - if customer_id is None: - raise ValueError('customer_id must be provided') + if not project_id: + raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_enrichments', + ) headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - url = '/v2/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - -class AddDocumentEnums: - """ - Enums for add_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. + def create_enrichment( + self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - + Create an enrichment. -class UpdateDocumentEnums: - """ - Enums for update_document parameters. - """ + Create an enrichment for use with the specified project. To apply the enrichment + to a collection in the project, use the [Collections + API](/apidocs/discovery-data#createcollection). - class FileContentType(str, Enum): - """ - The content type of file. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param CreateEnrichment enrichment: Information about a specific + enrichment. + :param BinaryIO file: (optional) The enrichment file to upload. Expected + file types per enrichment are as follows: + * CSV for `dictionary` and `sentence_classifier` (the training data CSV + file to upload). + * PEAR for `uima_annotator` and `rule_based` (Explorer) + * ZIP for `watson_knowledge_studio_model` and `rule_based` (Studio Advanced + Rule Editor). + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if not project_id: + raise ValueError('project_id must be provided') + if enrichment is None: + raise ValueError('enrichment must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment', + ) + headers.update(sdk_headers) -class AnalyzeDocumentEnums: - """ - Enums for analyze_document parameters. - """ + params = { + 'version': self.version, + } - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + form_data = [] + form_data.append( + ('enrichment', (None, json.dumps(enrichment), 'application/json'))) + if file: + form_data.append(('file', (None, file, 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -############################################################################## -# Models -############################################################################## + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + response = self.send(request, **kwargs) + return response -class AnalyzedDocument(): - """ - An object that contains the converted document and any identified enrichments. + def get_enrichment( + self, + project_id: str, + enrichment_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get enrichment. - :attr List[Notice] notices: (optional) Array of document results that match the - query. - :attr AnalyzedResult result: (optional) Result of the document analysis. - """ + Get details about a specific enrichment. - def __init__(self, - *, - notices: List['Notice'] = None, - result: 'AnalyzedResult' = None) -> None: + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not enrichment_id: + raise ValueError('enrichment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_enrichment', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_enrichment( + self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Update an enrichment. + + Updates an existing enrichment's name and description. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. + :param str name: A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not enrichment_id: + raise ValueError('enrichment_id must be provided') + if name is None: + raise ValueError('name must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_enrichment', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def delete_enrichment( + self, + project_id: str, + enrichment_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Delete an enrichment. + + Deletes an existing enrichment from the specified project. + **Note:** Only enrichments that have been manually created can be deleted. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not enrichment_id: + raise ValueError('enrichment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_enrichment', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Batches + ######################### + + def list_batches( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: + """ + List batches. + + A batch is a set of documents that are ready for enrichment by an external + application. After you apply a webhook enrichment to a collection, and then + process or upload documents to the collection, Discovery creates a batch with a + unique **batch_id**. + To start, you must register your external application as a **webhook** type by + using the [Create enrichment API](/apidocs/discovery-data#createenrichment) + method. + Use the List batches API to get the following: + * Notified batches that are not yet pulled by the external enrichment + application. + * Batches that are pulled, but not yet pushed to Discovery by the external + enrichment application. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListBatchesResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def pull_batches( + self, + project_id: str, + collection_id: str, + batch_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Pull batches. + + Pull a batch of documents from Discovery for enrichment by an external + application. Ensure to include the `Accept-Encoding: gzip` header in this method + to get the file. You can also implement retry logic when calling this method to + avoid any network errors. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str batch_id: The Universally Unique Identifier (UUID) of the + document batch that is being requested from Discovery. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `PullBatchesResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not batch_id: + raise ValueError('batch_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='pull_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'batch_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches/{batch_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def push_batches( + self, + project_id: str, + collection_id: str, + batch_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Push batches. + + Push a batch of documents to Discovery after annotation by an external + application. You can implement retry logic when calling this method to avoid any + network errors. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str batch_id: The Universally Unique Identifier (UUID) of the + document batch that is being requested from Discovery. + :param BinaryIO file: (optional) A compressed newline-delimited JSON + (NDJSON), which is a JSON file with one row of data per line. For example, + `{batch_id}.ndjson.gz`. For more information, see [Binary attachment in the + push batches + method](/docs/discovery-data?topic=discovery-data-external-enrichment#binary-attachment-push-batches). + There is no limitation on the name of the file because Discovery does not + use the name for processing. The list of features in the document is + specified in the `features` object. + :param str filename: (optional) The filename for file. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `bool` result + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not batch_id: + raise ValueError('batch_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='push_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append( + ('file', (filename, file, 'application/octet-stream'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'batch_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches/{batch_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Document classifiers + ######################### + + def list_document_classifiers( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: + """ + List document classifiers. + + Get a list of the document classifiers in a project. Returns only the name and + classifier ID of each document classifier. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifiers` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifiers', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def create_document_classifier( + self, + project_id: str, + training_data: BinaryIO, + classifier: 'CreateDocumentClassifier', + *, + test_data: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create a document classifier. + + Create a document classifier. You can use the API to create a document classifier + in any project type. After you create a document classifier, you can use the + Enrichments API to create a classifier enrichment, and then the Collections API to + apply the enrichment to a collection in the project. + **Note:** This method is supported on installed instances (IBM Cloud Pak for Data) + or IBM Cloud-managed Premium or Enterprise plan instances. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param BinaryIO training_data: The training data CSV file to upload. The + CSV file must have headers. The file must include a field that contains the + text you want to classify and a field that contains the classification + labels that you want to use to classify your data. If you want to specify + multiple values in a single field, use a semicolon as the value separator. + For a sample file, see [the product + documentation](/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + :param CreateDocumentClassifier classifier: An object that manages the + settings and data that is required to train a document classification + model. + :param BinaryIO test_data: (optional) The CSV with test data to upload. The + column values in the test file must be the same as the column values in the + training data file. If no test data is provided, the training data is split + into two separate groups of training and test data. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + if classifier is None: + raise ValueError('classifier must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + form_data.append(('training_data', (None, training_data, 'text/csv'))) + form_data.append( + ('classifier', (None, json.dumps(classifier), 'application/json'))) + if test_data: + form_data.append(('test_data', (None, test_data, 'text/csv'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + + def get_document_classifier( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get a document classifier. + + Get details about a specific document classifier. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_document_classifier( + self, + project_id: str, + classifier_id: str, + classifier: 'UpdateDocumentClassifier', + *, + training_data: Optional[BinaryIO] = None, + test_data: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: + """ + Update a document classifier. + + Update the document classifier name or description, update the training data, or + add or update the test data. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param UpdateDocumentClassifier classifier: An object that contains a new + name or description for a document classifier, updated training data, or + new or updated test data. + :param BinaryIO training_data: (optional) The training data CSV file to + upload. The CSV file must have headers. The file must include a field that + contains the text you want to classify and a field that contains the + classification labels that you want to use to classify your data. If you + want to specify multiple values in a single column, use a semicolon as the + value separator. For a sample file, see [the product + documentation](/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + :param BinaryIO test_data: (optional) The CSV with test data to upload. The + column values in the test file must be the same as the column values in the + training data file. If no test data is provided, the training data is split + into two separate groups of training and test data. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if classifier is None: + raise ValueError('classifier must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + form_data.append( + ('classifier', (None, json.dumps(classifier), 'application/json'))) + if training_data: + form_data.append( + ('training_data', (None, training_data, 'text/csv'))) + if test_data: + form_data.append(('test_data', (None, test_data, 'text/csv'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + + def delete_document_classifier( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Delete a document classifier. + + Deletes an existing document classifier from the specified project. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Document classifier models + ######################### + + def list_document_classifier_models( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: + """ + List document classifier models. + + Get a list of the document classifier models in a project. Returns only the name + and model ID of each document classifier model. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModels` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifier_models', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def create_document_classifier_model( + self, + project_id: str, + classifier_id: str, + name: str, + *, + description: Optional[str] = None, + learning_rate: Optional[float] = None, + l1_regularization_strengths: Optional[List[float]] = None, + l2_regularization_strengths: Optional[List[float]] = None, + training_max_steps: Optional[int] = None, + improvement_ratio: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: + """ + Create a document classifier model. + + Create a document classifier model by training a model that uses the data and + classifier settings defined in the specified document classifier. + **Note:** This method is supported on installed intances (IBM Cloud Pak for Data) + or IBM Cloud-managed Premium or Enterprise plan instances. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str name: The name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param float learning_rate: (optional) A tuning parameter in an + optimization algorithm that determines the step size at each iteration of + the training process. It influences how much of any newly acquired + information overrides the existing information, and therefore is said to + represent the speed at which a machine learning model learns. The default + value is `0.1`. + :param List[float] l1_regularization_strengths: (optional) Avoids + overfitting by shrinking the coefficient of less important features to + zero, which removes some features altogether. You can specify many values + for hyper-parameter optimization. The default value is `[0.000001]`. + :param List[float] l2_regularization_strengths: (optional) A method you can + apply to avoid overfitting your model on the training data. You can specify + many values for hyper-parameter optimization. The default value is + `[0.000001]`. + :param int training_max_steps: (optional) Maximum number of training steps + to complete. This setting is useful if you need the training process to + finish in a specific time frame to fit into an automated process. The + default value is ten million. + :param float improvement_ratio: (optional) Stops the training run early if + the improvement ratio is not met by the time the process reaches a certain + point. The default value is `0.00001`. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if name is None: + raise ValueError('name must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier_model', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + 'learning_rate': learning_rate, + 'l1_regularization_strengths': l1_regularization_strengths, + 'l2_regularization_strengths': l2_regularization_strengths, + 'training_max_steps': training_max_steps, + 'improvement_ratio': improvement_ratio, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def get_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get a document classifier model. + + Get details about a specific document classifier model. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str model_id: The Universally Unique Identifier (UUID) of the + classifier model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if not model_id: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier_model', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Update a document classifier model. + + Update the document classifier model name or description. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str model_id: The Universally Unique Identifier (UUID) of the + classifier model. + :param str name: (optional) A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if not model_id: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier_model', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def delete_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Delete a document classifier model. + + Deletes an existing document classifier model from the specified project. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str model_id: The Universally Unique Identifier (UUID) of the + classifier model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if not model_id: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier_model', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Analyze + ######################### + + def analyze_document( + self, + project_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Analyze a document. + + Process a document and return it for realtime use. Supports JSON files only. + The file is not stored in the collection, but is processed according to the + collection's configuration settings. To get results, enrichments must be applied + to a field in the collection that also exists in the file that you want to + analyze. For example, to analyze text in a `Quote` field, you must apply + enrichments to the `Quote` field in the collection configuration. Then, when you + analyze the file, the text in the `Quote` field is analyzed and results are + written to a field named `enriched_Quote`. + Submit a request against only one collection at a time. Remember, the documents in + the collection are not significant. It is the enrichments that are defined for the + collection that matter. If you submit requests to several collections, then + several models are initiated at the same time, which can cause request failures. + **Note:** This method is supported with Enterprise plan deployments and installed + deployments only. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='analyze_document', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) + if metadata: + form_data.append(('metadata', (None, metadata, 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # User data + ######################### + + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + You associate a customer ID with data by passing the **X-Watson-Metadata** header + with a request that passes data. For more information about personal data and + customer IDs, see [Information + security](/docs/discovery-data?topic=discovery-data-information-security#information-security). + **Note:** This method is only supported on IBM Cloud instances of Discovery. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not customer_id: + raise ValueError('customer_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'customer_id': customer_id, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + url = '/v2/user_data' + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + +class AddDocumentEnums: + """ + Enums for add_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums: + """ + Enums for update_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class AnalyzeDocumentEnums: + """ + Enums for analyze_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +############################################################################## +# Models +############################################################################## + + +class AnalyzedDocument: + """ + An object that contains the converted document and any identified enrichments. + Root-level fields from the original file are returned also. + + :param List[Notice] notices: (optional) Array of notices that are triggered when + the files are processed. + :param AnalyzedResult result: (optional) Result of the document analysis. + """ + + def __init__( + self, + *, + notices: Optional[List['Notice']] = None, + result: Optional['AnalyzedResult'] = None, + ) -> None: + """ + Initialize a AnalyzedDocument object. + + :param List[Notice] notices: (optional) Array of notices that are triggered + when the files are processed. + :param AnalyzedResult result: (optional) Result of the document analysis. + """ + self.notices = notices + self.result = result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': + """Initialize a AnalyzedDocument object from a json dictionary.""" + args = {} + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (result := _dict.get('result')) is not None: + args['result'] = AnalyzedResult.from_dict(result) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedDocument object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'notices') and self.notices is not None: + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list + if hasattr(self, 'result') and self.result is not None: + if isinstance(self.result, dict): + _dict['result'] = self.result + else: + _dict['result'] = self.result.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AnalyzedDocument object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedDocument') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AnalyzedDocument') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AnalyzedResult: + """ + Result of the document analysis. + + :param dict metadata: (optional) Metadata that was specified with the request. + + This type supports additional properties of type object. The remaining key-value + pairs. + """ + + # The set of defined properties for the class + _properties = frozenset(['metadata']) + + def __init__( + self, + *, + metadata: Optional[dict] = None, + **kwargs: Optional[object], + ) -> None: + """ + Initialize a AnalyzedResult object. + + :param dict metadata: (optional) Metadata that was specified with the + request. + :param object **kwargs: (optional) The remaining key-value pairs. + """ + self.metadata = metadata + for k, v in kwargs.items(): + if k not in AnalyzedResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': + """Initialize a AnalyzedResult object from a json dictionary.""" + args = {} + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return the additional properties from this instance of AnalyzedResult in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of AnalyzedResult""" + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in AnalyzedResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + def __str__(self) -> str: + """Return a `str` version of this AnalyzedResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AnalyzedResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BatchDetails: + """ + A batch is a set of documents that are ready for enrichment by an external + application. After you apply a webhook enrichment to a collection, and then process or + upload documents to the collection, Discovery creates a batch with a unique + **batch_id**. + + :param str batch_id: (optional) The Universally Unique Identifier (UUID) for a + batch of documents. + :param datetime created: (optional) The date and time (RFC3339) that the batch + was created. + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) + for the external enrichment. + """ + + def __init__( + self, + *, + batch_id: Optional[str] = None, + created: Optional[datetime] = None, + enrichment_id: Optional[str] = None, + ) -> None: + """ + Initialize a BatchDetails object. + + :param str enrichment_id: (optional) The Universally Unique Identifier + (UUID) for the external enrichment. + """ + self.batch_id = batch_id + self.created = created + self.enrichment_id = enrichment_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BatchDetails': + """Initialize a BatchDetails object from a json dictionary.""" + args = {} + if (batch_id := _dict.get('batch_id')) is not None: + args['batch_id'] = batch_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BatchDetails object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'batch_id') and getattr(self, 'batch_id') is not None: + _dict['batch_id'] = getattr(self, 'batch_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BatchDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BatchDetails') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BatchDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClassifierFederatedModel: + """ + An object with details for creating federated document classifier models. + + :param str field: Name of the field that contains the values from which multiple + classifier models are defined. For example, you can specify a field that lists + product lines to create a separate model per product line. + """ + + def __init__( + self, + field: str, + ) -> None: + """ + Initialize a ClassifierFederatedModel object. + + :param str field: Name of the field that contains the values from which + multiple classifier models are defined. For example, you can specify a + field that lists product lines to create a separate model per product line. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassifierFederatedModel': + """Initialize a ClassifierFederatedModel object from a json dictionary.""" + args = {} + if (field := _dict.get('field')) is not None: + args['field'] = field + else: + raise ValueError( + 'Required property \'field\' not present in ClassifierFederatedModel JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierFederatedModel object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClassifierFederatedModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassifierFederatedModel') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClassifierFederatedModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClassifierModelEvaluation: + """ + An object that contains information about a trained document classifier model. + + :param ModelEvaluationMicroAverage micro_average: A micro-average aggregates the + contributions of all classes to compute the average metric. Classes refers to + the classification labels that are specified in the **answer_field**. + :param ModelEvaluationMacroAverage macro_average: A macro-average computes + metric independently for each class and then takes the average. Class refers to + the classification label that is specified in the **answer_field**. + :param List[PerClassModelEvaluation] per_class: An array of evaluation metrics, + one set of metrics for each class, where class refers to the classification + label that is specified in the **answer_field**. + """ + + def __init__( + self, + micro_average: 'ModelEvaluationMicroAverage', + macro_average: 'ModelEvaluationMacroAverage', + per_class: List['PerClassModelEvaluation'], + ) -> None: + """ + Initialize a ClassifierModelEvaluation object. + + :param ModelEvaluationMicroAverage micro_average: A micro-average + aggregates the contributions of all classes to compute the average metric. + Classes refers to the classification labels that are specified in the + **answer_field**. + :param ModelEvaluationMacroAverage macro_average: A macro-average computes + metric independently for each class and then takes the average. Class + refers to the classification label that is specified in the + **answer_field**. + :param List[PerClassModelEvaluation] per_class: An array of evaluation + metrics, one set of metrics for each class, where class refers to the + classification label that is specified in the **answer_field**. + """ + self.micro_average = micro_average + self.macro_average = macro_average + self.per_class = per_class + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassifierModelEvaluation': + """Initialize a ClassifierModelEvaluation object from a json dictionary.""" + args = {} + if (micro_average := _dict.get('micro_average')) is not None: + args['micro_average'] = ModelEvaluationMicroAverage.from_dict( + micro_average) + else: + raise ValueError( + 'Required property \'micro_average\' not present in ClassifierModelEvaluation JSON' + ) + if (macro_average := _dict.get('macro_average')) is not None: + args['macro_average'] = ModelEvaluationMacroAverage.from_dict( + macro_average) + else: + raise ValueError( + 'Required property \'macro_average\' not present in ClassifierModelEvaluation JSON' + ) + if (per_class := _dict.get('per_class')) is not None: + args['per_class'] = [ + PerClassModelEvaluation.from_dict(v) for v in per_class + ] + else: + raise ValueError( + 'Required property \'per_class\' not present in ClassifierModelEvaluation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierModelEvaluation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'micro_average') and self.micro_average is not None: + if isinstance(self.micro_average, dict): + _dict['micro_average'] = self.micro_average + else: + _dict['micro_average'] = self.micro_average.to_dict() + if hasattr(self, 'macro_average') and self.macro_average is not None: + if isinstance(self.macro_average, dict): + _dict['macro_average'] = self.macro_average + else: + _dict['macro_average'] = self.macro_average.to_dict() + if hasattr(self, 'per_class') and self.per_class is not None: + per_class_list = [] + for v in self.per_class: + if isinstance(v, dict): + per_class_list.append(v) + else: + per_class_list.append(v.to_dict()) + _dict['per_class'] = per_class_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClassifierModelEvaluation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassifierModelEvaluation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClassifierModelEvaluation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Collection: + """ + A collection for storing documents. + + :param str collection_id: (optional) The Universally Unique Identifier (UUID) of + the collection. + :param str name: (optional) The name of the collection. + """ + + def __init__( + self, + *, + collection_id: Optional[str] = None, + name: Optional[str] = None, + ) -> None: + """ + Initialize a Collection object. + + :param str name: (optional) The name of the collection. + """ + self.collection_id = collection_id + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Collection': + """Initialize a Collection object from a json dictionary.""" + args = {} + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Collection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Collection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Collection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetails: + """ + A collection for storing documents. + + :param str collection_id: (optional) The Universally Unique Identifier (UUID) of + the collection. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param datetime created: (optional) The date that the collection was created. + :param str language: (optional) The language of the collection. For a list of + supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of enrichments + that are available for a project, use the [List enrichments](#listenrichments) + method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about project + default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + :param CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: + (optional) An object that describes the Smart Document Understanding model for a + collection. + """ + + def __init__( + self, + name: str, + *, + collection_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + language: Optional[str] = None, + ocr_enabled: Optional[bool] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + smart_document_understanding: Optional[ + 'CollectionDetailsSmartDocumentUnderstanding'] = None, + ) -> None: + """ + Initialize a CollectionDetails object. + + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. For a list + of supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of + enrichments that are available for a project, use the [List + enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about + project default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.language = language + self.ocr_enabled = ocr_enabled + self.enrichments = enrichments + self.smart_document_understanding = smart_document_understanding + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionDetails': + """Initialize a CollectionDetails object from a json dictionary.""" + args = {} + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in CollectionDetails JSON' + ) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (ocr_enabled := _dict.get('ocr_enabled')) is not None: + args['ocr_enabled'] = ocr_enabled + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [ + CollectionEnrichment.from_dict(v) for v in enrichments + ] + if (smart_document_understanding := + _dict.get('smart_document_understanding')) is not None: + args[ + 'smart_document_understanding'] = CollectionDetailsSmartDocumentUnderstanding.from_dict( + smart_document_understanding) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetails object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'ocr_enabled') and self.ocr_enabled is not None: + _dict['ocr_enabled'] = self.ocr_enabled + if hasattr(self, 'enrichments') and self.enrichments is not None: + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, 'smart_document_understanding') and getattr( + self, 'smart_document_understanding') is not None: + if isinstance(getattr(self, 'smart_document_understanding'), dict): + _dict['smart_document_understanding'] = getattr( + self, 'smart_document_understanding') + else: + _dict['smart_document_understanding'] = getattr( + self, 'smart_document_understanding').to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionDetails') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CollectionDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetailsSmartDocumentUnderstanding: + """ + An object that describes the Smart Document Understanding model for a collection. + + :param bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for the collection. + :param str model: (optional) Specifies the type of Smart Document Understanding + (SDU) model that is enabled for the collection. The following types of models + are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is applied + automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the types + of documents in the collection (as long as the service plan supports SDU + models). + You can apply user-trained or pretrained models to collections from the + *Identify fields* page of the product user interface. For more information, see + [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + + def __init__( + self, + *, + enabled: Optional[bool] = None, + model: Optional[str] = None, + ) -> None: + """ + Initialize a CollectionDetailsSmartDocumentUnderstanding object. + + :param bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for the collection. + :param str model: (optional) Specifies the type of Smart Document + Understanding (SDU) model that is enabled for the collection. The following + types of models are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is + applied automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the + types of documents in the collection (as long as the service plan supports + SDU models). + You can apply user-trained or pretrained models to collections from the + *Identify fields* page of the product user interface. For more information, + see [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + self.enabled = enabled + self.model = model + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'CollectionDetailsSmartDocumentUnderstanding': + """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" + args = {} + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (model := _dict.get('model')) is not None: + args['model'] = model + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionDetailsSmartDocumentUnderstanding object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'CollectionDetailsSmartDocumentUnderstanding') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'CollectionDetailsSmartDocumentUnderstanding') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelEnum(str, Enum): + """ + Specifies the type of Smart Document Understanding (SDU) model that is enabled for + the collection. The following types of models are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is applied + automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the types + of documents in the collection (as long as the service plan supports SDU models). + You can apply user-trained or pretrained models to collections from the *Identify + fields* page of the product user interface. For more information, see [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + + CUSTOM = 'custom' + PRE_TRAINED = 'pre_trained' + TEXT_EXTRACTION = 'text_extraction' + + +class CollectionEnrichment: + """ + An object describing an enrichment for a collection. + + :param str enrichment_id: (optional) The unique identifier of this enrichment. + For more information about how to determine the ID of an enrichment, see [the + product + documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). + :param List[str] fields: (optional) An array of field names that the enrichment + is applied to. + If you apply an enrichment to a field from a JSON file, the data is converted to + an array automatically, even if the field contains a single value. + """ + + def __init__( + self, + *, + enrichment_id: Optional[str] = None, + fields: Optional[List[str]] = None, + ) -> None: + """ + Initialize a CollectionEnrichment object. + + :param str enrichment_id: (optional) The unique identifier of this + enrichment. For more information about how to determine the ID of an + enrichment, see [the product + documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). + :param List[str] fields: (optional) An array of field names that the + enrichment is applied to. + If you apply an enrichment to a field from a JSON file, the data is + converted to an array automatically, even if the field contains a single + value. + """ + self.enrichment_id = enrichment_id + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': + """Initialize a CollectionEnrichment object from a json dictionary.""" + args = {} + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionEnrichment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionEnrichment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Completions: + """ + An object that contains an array of autocompletion suggestions. + + :param List[str] completions: (optional) Array of autocomplete suggestion based + on the provided prefix. + """ + + def __init__( + self, + *, + completions: Optional[List[str]] = None, + ) -> None: + """ + Initialize a Completions object. + + :param List[str] completions: (optional) Array of autocomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Completions': + """Initialize a Completions object from a json dictionary.""" + args = {} + if (completions := _dict.get('completions')) is not None: + args['completions'] = completions + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Completions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Completions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Completions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsAggregation: + """ + Display settings for aggregations. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is allowed to + select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + + def __init__( + self, + *, + name: Optional[str] = None, + label: Optional[str] = None, + multiple_selections_allowed: Optional[bool] = None, + visualization_type: Optional[str] = None, + ) -> None: + """ + Initialize a ComponentSettingsAggregation object. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is + allowed to select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + self.name = name + self.label = label + self.multiple_selections_allowed = multiple_selections_allowed + self.visualization_type = visualization_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (label := _dict.get('label')) is not None: + args['label'] = label + if (multiple_selections_allowed := + _dict.get('multiple_selections_allowed')) is not None: + args['multiple_selections_allowed'] = multiple_selections_allowed + if (visualization_type := _dict.get('visualization_type')) is not None: + args['visualization_type'] = visualization_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'multiple_selections_allowed' + ) and self.multiple_selections_allowed is not None: + _dict[ + 'multiple_selections_allowed'] = self.multiple_selections_allowed + if hasattr( + self, + 'visualization_type') and self.visualization_type is not None: + _dict['visualization_type'] = self.visualization_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class VisualizationTypeEnum(str, Enum): + """ + Type of visualization to use when rendering the aggregation. """ - Initialize a AnalyzedDocument object. - :param List[Notice] notices: (optional) Array of document results that - match the query. - :param AnalyzedResult result: (optional) Result of the document analysis. + AUTO = 'auto' + FACET_TABLE = 'facet_table' + WORD_CLOUD = 'word_cloud' + MAP = 'map' + + +class ComponentSettingsFieldsShown: + """ + Fields shown in the results section of the UI. + + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + + def __init__( + self, + *, + body: Optional['ComponentSettingsFieldsShownBody'] = None, + title: Optional['ComponentSettingsFieldsShownTitle'] = None, + ) -> None: """ - self.notices = notices - self.result = result + Initialize a ComponentSettingsFieldsShown object. + + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + self.body = body + self.title = title @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': - """Initialize a AnalyzedDocument object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'result' in _dict: - args['result'] = AnalyzedResult.from_dict(_dict.get('result')) + if (body := _dict.get('body')) is not None: + args['body'] = ComponentSettingsFieldsShownBody.from_dict(body) + if (title := _dict.get('title')) is not None: + args['title'] = ComponentSettingsFieldsShownTitle.from_dict(title) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalyzedDocument object from a json dictionary.""" + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - if hasattr(self, 'result') and self.result is not None: - _dict['result'] = self.result.to_dict() + if hasattr(self, 'body') and self.body is not None: + if isinstance(self.body, dict): + _dict['body'] = self.body + else: + _dict['body'] = self.body.to_dict() + if hasattr(self, 'title') and self.title is not None: + if isinstance(self.title, dict): + _dict['title'] = self.title + else: + _dict['title'] = self.title.to_dict() return _dict def _to_dict(self): @@ -2062,151 +5144,234 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AnalyzedDocument object.""" + """Return a `str` version of this ComponentSettingsFieldsShown object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalyzedDocument') -> bool: + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'AnalyzedDocument') -> bool: + def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class AnalyzedResult(): +class ComponentSettingsFieldsShownBody: """ - Result of the document analysis. + Body label. - :attr dict metadata: (optional) Metadata of the document. + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. """ - # The set of defined properties for the class - _properties = frozenset(['metadata']) - - def __init__(self, *, metadata: dict = None, **kwargs) -> None: + def __init__( + self, + *, + use_passage: Optional[bool] = None, + field: Optional[str] = None, + ) -> None: """ - Initialize a AnalyzedResult object. + Initialize a ComponentSettingsFieldsShownBody object. - :param dict metadata: (optional) Metadata of the document. - :param **kwargs: (optional) Any additional properties. + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. """ - self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.use_passage = use_passage + self.field = field @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': - """Initialize a AnalyzedResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (use_passage := _dict.get('use_passage')) is not None: + args['use_passage'] = use_passage + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalyzedResult object from a json dictionary.""" + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'use_passage') and self.use_passage is not None: + _dict['use_passage'] = self.use_passage + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" - _dict = {} + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + return json.dumps(self.to_dict(), indent=2) - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - delattr(self, _key) + def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownTitle: + """ + Title label. + + :param str field: (optional) Use a specific field as the title. + """ + + def __init__( + self, + *, + field: Optional[str] = None, + ) -> None: + """ + Initialize a ComponentSettingsFieldsShownTitle object. + + :param str field: (optional) Use a specific field as the title. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + args = {} + if (field := _dict.get('field')) is not None: + args['field'] = field + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict - for _key, _value in _dict.items(): - if _key not in AnalyzedResult._properties: - setattr(self, _key, _value) + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AnalyzedResult object.""" + """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalyzedResult') -> bool: + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'AnalyzedResult') -> bool: + def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Collection(): +class ComponentSettingsResponse: """ - A collection for storing documents. + The default component settings for this project. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is enabled. + :param bool structured_search: (optional) Whether or not structured search is + enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list of + component setting aggregations. """ - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def __init__( + self, + *, + fields_shown: Optional['ComponentSettingsFieldsShown'] = None, + autocomplete: Optional[bool] = None, + structured_search: Optional[bool] = None, + results_per_page: Optional[int] = None, + aggregations: Optional[List['ComponentSettingsAggregation']] = None, + ) -> None: """ - Initialize a Collection object. + Initialize a ComponentSettingsResponse object. - :param str name: (optional) The name of the collection. + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown + in the results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is + enabled. + :param bool structured_search: (optional) Whether or not structured search + is enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list + of component setting aggregations. """ - self.collection_id = collection_id - self.name = name + self.fields_shown = fields_shown + self.autocomplete = autocomplete + self.structured_search = structured_search + self.results_per_page = results_per_page + self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': + """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (fields_shown := _dict.get('fields_shown')) is not None: + args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( + fields_shown) + if (autocomplete := _dict.get('autocomplete')) is not None: + args['autocomplete'] = autocomplete + if (structured_search := _dict.get('structured_search')) is not None: + args['structured_search'] = structured_search + if (results_per_page := _dict.get('results_per_page')) is not None: + args['results_per_page'] = results_per_page + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = [ + ComponentSettingsAggregation.from_dict(v) for v in aggregations + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Collection object from a json dictionary.""" + """Initialize a ComponentSettingsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name + if hasattr(self, 'fields_shown') and self.fields_shown is not None: + if isinstance(self.fields_shown, dict): + _dict['fields_shown'] = self.fields_shown + else: + _dict['fields_shown'] = self.fields_shown.to_dict() + if hasattr(self, 'autocomplete') and self.autocomplete is not None: + _dict['autocomplete'] = self.autocomplete + if hasattr(self, + 'structured_search') and self.structured_search is not None: + _dict['structured_search'] = self.structured_search + if hasattr(self, + 'results_per_page') and self.results_per_page is not None: + _dict['results_per_page'] = self.results_per_page + if hasattr(self, 'aggregations') and self.aggregations is not None: + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -2214,103 +5379,145 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Collection object.""" + """Return a `str` version of this ComponentSettingsResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Collection') -> bool: + def __eq__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Collection') -> bool: + def __ne__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CollectionDetails(): +class CreateDocumentClassifier: """ - A collection for storing documents. + An object that manages the settings and data that is required to train a document + classification model. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: The name of the collection. - :attr str description: (optional) A description of the collection. - :attr datetime created: (optional) The date that the collection was created. - :attr str language: (optional) The language of the collection. - :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments - that are applied to this collection. + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document classifier. + :param str language: The language of the training data that is associated with + the document classifier. Language is specified by using the ISO 639-1 language + code, such as `en` for English or `ja` for Japanese. + :param str answer_field: The name of the field from the training and test data + that contains the classification labels. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array of + enrichments to apply to the data that is used to train and test the document + classifier. The output from the enrichments is used as features by the + classifier to classify the document content both during training and at run + time. + :param ClassifierFederatedModel federated_classification: (optional) An object + with details for creating federated document classifier models. """ - def __init__(self, - name: str, - *, - collection_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None) -> None: + def __init__( + self, + name: str, + language: str, + answer_field: str, + *, + description: Optional[str] = None, + enrichments: Optional[List['DocumentClassifierEnrichment']] = None, + federated_classification: Optional['ClassifierFederatedModel'] = None, + ) -> None: """ - Initialize a CollectionDetails object. - - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str language: (optional) The language of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + Initialize a CreateDocumentClassifier object. + + :param str name: A human-readable name of the document classifier. + :param str language: The language of the training data that is associated + with the document classifier. Language is specified by using the ISO 639-1 + language code, such as `en` for English or `ja` for Japanese. + :param str answer_field: The name of the field from the training and test + data that contains the classification labels. + :param str description: (optional) A description of the document + classifier. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array + of enrichments to apply to the data that is used to train and test the + document classifier. The output from the enrichments is used as features by + the classifier to classify the document content both during training and at + run time. + :param ClassifierFederatedModel federated_classification: (optional) An + object with details for creating federated document classifier models. """ - self.collection_id = collection_id self.name = name self.description = description - self.created = created self.language = language + self.answer_field = answer_field self.enrichments = enrichments + self.federated_classification = federated_classification @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionDetails': - """Initialize a CollectionDetails object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateDocumentClassifier': + """Initialize a CreateDocumentClassifier object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( - 'Required property \'name\' not present in CollectionDetails JSON' + 'Required property \'name\' not present in CreateDocumentClassifier JSON' + ) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in CreateDocumentClassifier JSON' + ) + if (answer_field := _dict.get('answer_field')) is not None: + args['answer_field'] = answer_field + else: + raise ValueError( + 'Required property \'answer_field\' not present in CreateDocumentClassifier JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'enrichments' in _dict: + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - CollectionEnrichment.from_dict(x) - for x in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) for v in enrichments ] + if (federated_classification := + _dict.get('federated_classification')) is not None: + args[ + 'federated_classification'] = ClassifierFederatedModel.from_dict( + federated_classification) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CollectionDetails object from a json dictionary.""" + """Initialize a CreateDocumentClassifier object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language + if hasattr(self, 'answer_field') and self.answer_field is not None: + _dict['answer_field'] = self.answer_field if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, 'federated_classification' + ) and self.federated_classification is not None: + if isinstance(self.federated_classification, dict): + _dict[ + 'federated_classification'] = self.federated_classification + else: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -2318,71 +5525,136 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CollectionDetails object.""" + """Return a `str` version of this CreateDocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CollectionDetails') -> bool: + def __eq__(self, other: 'CreateDocumentClassifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CollectionDetails') -> bool: + def __ne__(self, other: 'CreateDocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CollectionEnrichment(): +class CreateEnrichment: """ - An object describing an Enrichment for a collection. + Information about a specific enrichment. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. - :attr List[str] fields: (optional) An array of field names that the enrichment - is applied to. - If you apply an enrichment to a field from a JSON file, the data is converted to - an array automatically, even if the field contains a single value. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. The following types are + supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a CSV + file. + * `regular_expression`: Creates a custom regular expression enrichment from + regex syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is + created and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis model + that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM Cloud + Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge + Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a webhook. + * `sentence_classifier`: Use sentence classifier to classify sentences in your + documents. This feature is available in IBM Cloud-managed instances only. The + sentence classifier feature is beta functionality. Beta features are not + supported by the SDKs. + :param EnrichmentOptions options: (optional) An object that contains options for + the current enrichment. Starting with version `2020-08-30`, the enrichment + options are not included in responses from the List Enrichments method. """ - def __init__(self, - *, - enrichment_id: str = None, - fields: List[str] = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + type: Optional[str] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ - Initialize a CollectionEnrichment object. + Initialize a CreateEnrichment object. - :param str enrichment_id: (optional) The unique identifier of this - enrichment. - :param List[str] fields: (optional) An array of field names that the - enrichment is applied to. - If you apply an enrichment to a field from a JSON file, the data is - converted to an array automatically, even if the field contains a single - value. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. The following + types are supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a + CSV file. + * `regular_expression`: Creates a custom regular expression enrichment from + regex syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is + created and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis + model that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM + Cloud Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson + Knowledge Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a + webhook. + * `sentence_classifier`: Use sentence classifier to classify sentences in + your documents. This feature is available in IBM Cloud-managed instances + only. The sentence classifier feature is beta functionality. Beta features + are not supported by the SDKs. + :param EnrichmentOptions options: (optional) An object that contains + options for the current enrichment. Starting with version `2020-08-30`, the + enrichment options are not included in responses from the List Enrichments + method. """ - self.enrichment_id = enrichment_id - self.fields = fields + self.name = name + self.description = description + self.type = type + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': - """Initialize a CollectionEnrichment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': + """Initialize a CreateEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (type := _dict.get('type')) is not None: + args['type'] = type + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CollectionEnrichment object from a json dictionary.""" + """Initialize a CreateEnrichment object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: - _dict['enrichment_id'] = self.enrichment_id - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = self.fields + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -2390,55 +5662,208 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CollectionEnrichment object.""" + """Return a `str` version of this CreateEnrichment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CollectionEnrichment') -> bool: + def __eq__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CollectionEnrichment') -> bool: + def __ne__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of this enrichment. The following types are supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a CSV + file. + * `regular_expression`: Creates a custom regular expression enrichment from regex + syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is created + and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis model + that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM Cloud + Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge + Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a webhook. + * `sentence_classifier`: Use sentence classifier to classify sentences in your + documents. This feature is available in IBM Cloud-managed instances only. The + sentence classifier feature is beta functionality. Beta features are not supported + by the SDKs. + """ + + CLASSIFIER = 'classifier' + DICTIONARY = 'dictionary' + REGULAR_EXPRESSION = 'regular_expression' + UIMA_ANNOTATOR = 'uima_annotator' + RULE_BASED = 'rule_based' + WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + WEBHOOK = 'webhook' + SENTENCE_CLASSIFIER = 'sentence_classifier' + -class Completions(): +class DefaultQueryParams: """ - An object that contains an array of autocompletion suggestions. + Default query parameters for this project. - :attr List[str] completions: (optional) Array of autocomplete suggestion based - on the provided prefix. + :param List[str] collection_ids: (optional) An array of collection identifiers + to query. If empty or omitted all collections in the project are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :param DefaultQueryParamsTableResults table_results: (optional) Default project + query settings for table results. + :param str aggregation: (optional) A string representing the default aggregation + query for the project. + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic facets + from the data is deprecated. + :param bool spelling_suggestions: (optional) When `true`, a spelling suggestions + for the query are returned by default. + :param bool highlight: (optional) When `true`, highlights for the query are + returned by default. + :param int count: (optional) The number of document results returned by default. + :param str sort: (optional) A comma separated list of document fields to sort + results by default. + :param List[str] return_: (optional) An array of field names to return in + document results if present by default. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__( + self, + *, + collection_ids: Optional[List[str]] = None, + passages: Optional['DefaultQueryParamsPassages'] = None, + table_results: Optional['DefaultQueryParamsTableResults'] = None, + aggregation: Optional[str] = None, + suggested_refinements: Optional[ + 'DefaultQueryParamsSuggestedRefinements'] = None, + spelling_suggestions: Optional[bool] = None, + highlight: Optional[bool] = None, + count: Optional[int] = None, + sort: Optional[str] = None, + return_: Optional[List[str]] = None, + ) -> None: """ - Initialize a Completions object. + Initialize a DefaultQueryParams object. - :param List[str] completions: (optional) Array of autocomplete suggestion - based on the provided prefix. + :param List[str] collection_ids: (optional) An array of collection + identifiers to query. If empty or omitted all collections in the project + are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :param DefaultQueryParamsTableResults table_results: (optional) Default + project query settings for table results. + :param str aggregation: (optional) A string representing the default + aggregation query for the project. + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: + (optional) Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic + facets from the data is deprecated. + :param bool spelling_suggestions: (optional) When `true`, a spelling + suggestions for the query are returned by default. + :param bool highlight: (optional) When `true`, highlights for the query are + returned by default. + :param int count: (optional) The number of document results returned by + default. + :param str sort: (optional) A comma separated list of document fields to + sort results by default. + :param List[str] return_: (optional) An array of field names to return in + document results if present by default. """ - self.completions = completions + self.collection_ids = collection_ids + self.passages = passages + self.table_results = table_results + self.aggregation = aggregation + self.suggested_refinements = suggested_refinements + self.spelling_suggestions = spelling_suggestions + self.highlight = highlight + self.count = count + self.sort = sort + self.return_ = return_ @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': + """Initialize a DefaultQueryParams object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if (collection_ids := _dict.get('collection_ids')) is not None: + args['collection_ids'] = collection_ids + if (passages := _dict.get('passages')) is not None: + args['passages'] = DefaultQueryParamsPassages.from_dict(passages) + if (table_results := _dict.get('table_results')) is not None: + args['table_results'] = DefaultQueryParamsTableResults.from_dict( + table_results) + if (aggregation := _dict.get('aggregation')) is not None: + args['aggregation'] = aggregation + if (suggested_refinements := + _dict.get('suggested_refinements')) is not None: + args[ + 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( + suggested_refinements) + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (count := _dict.get('count')) is not None: + args['count'] = count + if (sort := _dict.get('sort')) is not None: + args['sort'] = sort + if (return_ := _dict.get('return')) is not None: + args['return_'] = return_ return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Completions object from a json dictionary.""" + """Initialize a DefaultQueryParams object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'completions') and self.completions is not None: - _dict['completions'] = self.completions + if hasattr(self, 'collection_ids') and self.collection_ids is not None: + _dict['collection_ids'] = self.collection_ids + if hasattr(self, 'passages') and self.passages is not None: + if isinstance(self.passages, dict): + _dict['passages'] = self.passages + else: + _dict['passages'] = self.passages.to_dict() + if hasattr(self, 'table_results') and self.table_results is not None: + if isinstance(self.table_results, dict): + _dict['table_results'] = self.table_results + else: + _dict['table_results'] = self.table_results.to_dict() + if hasattr(self, 'aggregation') and self.aggregation is not None: + _dict['aggregation'] = self.aggregation + if hasattr(self, 'suggested_refinements' + ) and self.suggested_refinements is not None: + if isinstance(self.suggested_refinements, dict): + _dict['suggested_refinements'] = self.suggested_refinements + else: + _dict[ + 'suggested_refinements'] = self.suggested_refinements.to_dict( + ) + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'sort') and self.sort is not None: + _dict['sort'] = self.sort + if hasattr(self, 'return_') and self.return_ is not None: + _dict['return'] = self.return_ return _dict def _to_dict(self): @@ -2446,90 +5871,111 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Completions object.""" + """Return a `str` version of this DefaultQueryParams object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Completions') -> bool: + def __eq__(self, other: 'DefaultQueryParams') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Completions') -> bool: + def __ne__(self, other: 'DefaultQueryParams') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsAggregation(): +class DefaultQueryParamsPassages: """ - Display settings for aggregations. + Default settings configuration for passage search options. - :attr str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to - select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :param bool enabled: (optional) When `true`, a passage search is performed by + default. + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perform the + passage search on. + :param int characters: (optional) The approximate number of characters that each + returned passage will contain. + :param bool per_document: (optional) When `true` the number of passages that can + be returned from a single document is restricted to the *max_per_document* + value. + :param int max_per_document: (optional) The default maximum number of passages + that can be taken from a single document as the result of a passage query. """ - def __init__(self, - *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + fields: Optional[List[str]] = None, + characters: Optional[int] = None, + per_document: Optional[bool] = None, + max_per_document: Optional[int] = None, + ) -> None: """ - Initialize a ComponentSettingsAggregation object. + Initialize a DefaultQueryParamsPassages object. - :param str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :param str label: (optional) User-friendly alias for the aggregation. - :param bool multiple_selections_allowed: (optional) Whether users is - allowed to select more than one of the aggregation terms. - :param str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :param bool enabled: (optional) When `true`, a passage search is performed + by default. + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perform the + passage search on. + :param int characters: (optional) The approximate number of characters that + each returned passage will contain. + :param bool per_document: (optional) When `true` the number of passages + that can be returned from a single document is restricted to the + *max_per_document* value. + :param int max_per_document: (optional) The default maximum number of + passages that can be taken from a single document as the result of a + passage query. """ - self.name = name - self.label = label - self.multiple_selections_allowed = multiple_selections_allowed - self.visualization_type = visualization_type + self.enabled = enabled + self.count = count + self.fields = fields + self.characters = characters + self.per_document = per_document + self.max_per_document = max_per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + if (characters := _dict.get('characters')) is not None: + args['characters'] = characters + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document + if (max_per_document := _dict.get('max_per_document')) is not None: + args['max_per_document'] = max_per_document return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'multiple_selections_allowed' - ) and self.multiple_selections_allowed is not None: - _dict[ - 'multiple_selections_allowed'] = self.multiple_selections_allowed - if hasattr( - self, - 'visualization_type') and self.visualization_type is not None: - _dict['visualization_type'] = self.visualization_type + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document return _dict def _to_dict(self): @@ -2537,74 +5983,71 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsAggregation object.""" + """Return a `str` version of this DefaultQueryParamsPassages object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: + def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class VisualizationTypeEnum(str, Enum): - """ - Type of visualization to use when rendering the aggregation. - """ - AUTO = 'auto' - FACET_TABLE = 'facet_table' - WORD_CLOUD = 'word_cloud' - MAP = 'map' - -class ComponentSettingsFieldsShown(): +class DefaultQueryParamsSuggestedRefinements: """ - Fields shown in the results section of the UI. + Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic facets from + the data is deprecated. - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param bool enabled: (optional) When `true`, suggested refinements for the query + are returned by default. + :param int count: (optional) The number of suggested refinements to return by + default. """ - def __init__(self, - *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ - Initialize a ComponentSettingsFieldsShown object. + Initialize a DefaultQueryParamsSuggestedRefinements object. - :param ComponentSettingsFieldsShownBody body: (optional) Body label. - :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param bool enabled: (optional) When `true`, suggested refinements for the + query are returned by default. + :param int count: (optional) The number of suggested refinements to return + by default. """ - self.body = body - self.title = title + self.enabled = enabled + self.count = count @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody.from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle.from_dict( - _dict.get('title')) + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body.to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count return _dict def _to_dict(self): @@ -2612,60 +6055,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShown object.""" + """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownBody(): +class DefaultQueryParamsTableResults: """ - Body label. + Default project query settings for table results. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. + :param bool enabled: (optional) When `true`, a table results for the query are + returned by default. + :param int count: (optional) The number of table results to return by default. + :param int per_document: (optional) The number of table results to include in + each result document. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + per_document: Optional[int] = None, + ) -> None: """ - Initialize a ComponentSettingsFieldsShownBody object. + Initialize a DefaultQueryParamsTableResults object. - :param bool use_passage: (optional) Use the whole passage as the body. - :param str field: (optional) Use a specific field as the title. + :param bool enabled: (optional) When `true`, a table results for the query + are returned by default. + :param int count: (optional) The number of table results to return by + default. + :param int per_document: (optional) The number of table results to include + in each result document. """ - self.use_passage = use_passage - self.field = field + self.enabled = enabled + self.count = count + self.per_document = per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'use_passage') and self.use_passage is not None: - _dict['use_passage'] = self.use_passage - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document return _dict def _to_dict(self): @@ -2673,53 +6134,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + """Return a `str` version of this DefaultQueryParamsTableResults object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownTitle(): +class DeleteDocumentResponse: """ - Title label. + Information returned when a document is deleted. - :attr str field: (optional) Use a specific field as the title. + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document has the + status deleted. """ - def __init__(self, *, field: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ - Initialize a ComponentSettingsFieldsShownTitle object. + Initialize a DeleteDocumentResponse object. - :param str field: (optional) Use a specific field as the title. + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. """ - self.field = field + self.document_id = document_id + self.status = status @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': + """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + """Initialize a DeleteDocumentResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status return _dict def _to_dict(self): @@ -2727,101 +6202,80 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + """Return a `str` version of this DeleteDocumentResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __eq__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + + DELETED = 'deleted' + -class ComponentSettingsResponse(): +class DocumentAccepted: """ - The default component settings for this project. + Information returned after an uploaded document is accepted. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the - results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is - enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of - component setting aggregations. + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. """ def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ - Initialize a ComponentSettingsResponse object. + Initialize a DocumentAccepted object. - :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown - in the results section of the UI. - :param bool autocomplete: (optional) Whether or not autocomplete is - enabled. - :param bool structured_search: (optional) Whether or not structured search - is enabled. - :param int results_per_page: (optional) Number or results shown per page. - :param List[ComponentSettingsAggregation] aggregations: (optional) a list - of component setting aggregations. + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. """ - self.fields_shown = fields_shown - self.autocomplete = autocomplete - self.structured_search = structured_search - self.results_per_page = results_per_page - self.aggregations = aggregations + self.document_id = document_id + self.status = status @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': + """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'fields_shown' in _dict: - args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: - args['aggregations'] = [ - ComponentSettingsAggregation.from_dict(x) - for x in _dict.get('aggregations') - ] + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + """Initialize a DocumentAccepted object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown.to_dict() - if hasattr(self, 'autocomplete') and self.autocomplete is not None: - _dict['autocomplete'] = self.autocomplete - if hasattr(self, - 'structured_search') and self.structured_search is not None: - _dict['structured_search'] = self.structured_search - if hasattr(self, - 'results_per_page') and self.results_per_page is not None: - _dict['results_per_page'] = self.results_per_page - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status return _dict def _to_dict(self): @@ -2829,84 +6283,90 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsResponse object.""" + """Return a `str` version of this DocumentAccepted object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsResponse') -> bool: + def __eq__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsResponse') -> bool: + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + + PROCESSING = 'processing' + PENDING = 'pending' -class CreateEnrichment(): + +class DocumentAttribute: """ - Information about a specific enrichment. + List of document attributes. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) An object that contains options for - the current enrichment. Starting with version `2020-08-30`, the enrichment - options are not included in responses from the List Enrichments method. + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. """ - def __init__(self, - *, - name: str = None, - description: str = None, - type: str = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + ) -> None: """ - Initialize a CreateEnrichment object. + Initialize a DocumentAttribute object. - :param str name: (optional) The human readable name for this enrichment. - :param str description: (optional) The description of this enrichment. - :param str type: (optional) The type of this enrichment. - :param EnrichmentOptions options: (optional) An object that contains - options for the current enrichment. Starting with version `2020-08-30`, the - enrichment options are not included in responses from the List Enrichments - method. + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. """ - self.name = name - self.description = description self.type = type - self.options = options + self.text = text + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': - """Initialize a CreateEnrichment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': + """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CreateEnrichment object from a json dictionary.""" + """Initialize a DocumentAttribute object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2914,167 +6374,192 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CreateEnrichment object.""" + """Return a `str` version of this DocumentAttribute object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CreateEnrichment') -> bool: + def __eq__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CreateEnrichment') -> bool: + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of this enrichment. - """ - DICTIONARY = 'dictionary' - REGULAR_EXPRESSION = 'regular_expression' - UIMA_ANNOTATOR = 'uima_annotator' - RULE_BASED = 'rule_based' - WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' - - -class DefaultQueryParams(): - """ - Default query parameters for this project. - - :attr List[str] collection_ids: (optional) An array of collection identifiers to - query. If empty or omitted all collections in the project are queried. - :attr DefaultQueryParamsPassages passages: (optional) Default settings - configuration for passage search options. - :attr DefaultQueryParamsTableResults table_results: (optional) Default project - query settings for table results. - :attr str aggregation: (optional) A string representing the default aggregation - query for the project. - :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) - Object that contains suggested refinement settings. Available with Premium plans - only. - :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions - for the query are returned by default. - :attr bool highlight: (optional) When `true`, a highlights for the query are - returned by default. - :attr int count: (optional) The number of document results returned by default. - :attr str sort: (optional) A comma separated list of document fields to sort - results by default. - :attr List[str] return_: (optional) An array of field names to return in - document results if present by default. - """ - - def __init__(self, - *, - collection_ids: List[str] = None, - passages: 'DefaultQueryParamsPassages' = None, - table_results: 'DefaultQueryParamsTableResults' = None, - aggregation: str = None, - suggested_refinements: - 'DefaultQueryParamsSuggestedRefinements' = None, - spelling_suggestions: bool = None, - highlight: bool = None, - count: int = None, - sort: str = None, - return_: List[str] = None) -> None: - """ - Initialize a DefaultQueryParams object. - - :param List[str] collection_ids: (optional) An array of collection - identifiers to query. If empty or omitted all collections in the project - are queried. - :param DefaultQueryParamsPassages passages: (optional) Default settings - configuration for passage search options. - :param DefaultQueryParamsTableResults table_results: (optional) Default - project query settings for table results. - :param str aggregation: (optional) A string representing the default - aggregation query for the project. - :param DefaultQueryParamsSuggestedRefinements suggested_refinements: - (optional) Object that contains suggested refinement settings. Available - with Premium plans only. - :param bool spelling_suggestions: (optional) When `true`, a spelling - suggestions for the query are returned by default. - :param bool highlight: (optional) When `true`, a highlights for the query - are returned by default. - :param int count: (optional) The number of document results returned by - default. - :param str sort: (optional) A comma separated list of document fields to - sort results by default. - :param List[str] return_: (optional) An array of field names to return in - document results if present by default. - """ - self.collection_ids = collection_ids - self.passages = passages - self.table_results = table_results - self.aggregation = aggregation - self.suggested_refinements = suggested_refinements - self.spelling_suggestions = spelling_suggestions - self.highlight = highlight - self.count = count - self.sort = sort - self.return_ = return_ - + +class DocumentClassifier: + """ + Information about a document classifier. + + :param str classifier_id: (optional) The Universally Unique Identifier (UUID) of + the document classifier. + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document classifier. + :param datetime created: (optional) The date that the document classifier was + created. + :param str language: (optional) The language of the training data that is + associated with the document classifier. Language is specified by using the ISO + 639-1 language code, such as `en` for English or `ja` for Japanese. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array of + enrichments to apply to the data that is used to train and test the document + classifier. The output from the enrichments is used as features by the + classifier to classify the document content both during training and at run + time. + :param List[str] recognized_fields: (optional) An array of fields that are used + to train the document classifier. The same set of fields must exist in the + training data, the test data, and the documents where the resulting document + classifier enrichment is applied at run time. + :param str answer_field: (optional) The name of the field from the training and + test data that contains the classification labels. + :param str training_data_file: (optional) Name of the CSV file with training + data that is used to train the document classifier. + :param str test_data_file: (optional) Name of the CSV file with data that is + used to test the document classifier. If no test data is provided, a subset of + the training data is used for testing purposes. + :param ClassifierFederatedModel federated_classification: (optional) An object + with details for creating federated document classifier models. + """ + + def __init__( + self, + name: str, + *, + classifier_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + language: Optional[str] = None, + enrichments: Optional[List['DocumentClassifierEnrichment']] = None, + recognized_fields: Optional[List[str]] = None, + answer_field: Optional[str] = None, + training_data_file: Optional[str] = None, + test_data_file: Optional[str] = None, + federated_classification: Optional['ClassifierFederatedModel'] = None, + ) -> None: + """ + Initialize a DocumentClassifier object. + + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document + classifier. + :param str language: (optional) The language of the training data that is + associated with the document classifier. Language is specified by using the + ISO 639-1 language code, such as `en` for English or `ja` for Japanese. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array + of enrichments to apply to the data that is used to train and test the + document classifier. The output from the enrichments is used as features by + the classifier to classify the document content both during training and at + run time. + :param List[str] recognized_fields: (optional) An array of fields that are + used to train the document classifier. The same set of fields must exist in + the training data, the test data, and the documents where the resulting + document classifier enrichment is applied at run time. + :param str answer_field: (optional) The name of the field from the training + and test data that contains the classification labels. + :param str training_data_file: (optional) Name of the CSV file with + training data that is used to train the document classifier. + :param str test_data_file: (optional) Name of the CSV file with data that + is used to test the document classifier. If no test data is provided, a + subset of the training data is used for testing purposes. + :param ClassifierFederatedModel federated_classification: (optional) An + object with details for creating federated document classifier models. + """ + self.classifier_id = classifier_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + self.recognized_fields = recognized_fields + self.answer_field = answer_field + self.training_data_file = training_data_file + self.test_data_file = test_data_file + self.federated_classification = federated_classification + @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': - """Initialize a DefaultQueryParams object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifier': + """Initialize a DocumentClassifier object from a json dictionary.""" args = {} - if 'collection_ids' in _dict: - args['collection_ids'] = _dict.get('collection_ids') - if 'passages' in _dict: - args['passages'] = DefaultQueryParamsPassages.from_dict( - _dict.get('passages')) - if 'table_results' in _dict: - args['table_results'] = DefaultQueryParamsTableResults.from_dict( - _dict.get('table_results')) - if 'aggregation' in _dict: - args['aggregation'] = _dict.get('aggregation') - if 'suggested_refinements' in _dict: + if (classifier_id := _dict.get('classifier_id')) is not None: + args['classifier_id'] = classifier_id + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in DocumentClassifier JSON' + ) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [ + DocumentClassifierEnrichment.from_dict(v) for v in enrichments + ] + if (recognized_fields := _dict.get('recognized_fields')) is not None: + args['recognized_fields'] = recognized_fields + if (answer_field := _dict.get('answer_field')) is not None: + args['answer_field'] = answer_field + if (training_data_file := _dict.get('training_data_file')) is not None: + args['training_data_file'] = training_data_file + if (test_data_file := _dict.get('test_data_file')) is not None: + args['test_data_file'] = test_data_file + if (federated_classification := + _dict.get('federated_classification')) is not None: args[ - 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( - _dict.get('suggested_refinements')) - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'sort' in _dict: - args['sort'] = _dict.get('sort') - if 'return' in _dict: - args['return_'] = _dict.get('return') + 'federated_classification'] = ClassifierFederatedModel.from_dict( + federated_classification) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParams object from a json dictionary.""" + """Initialize a DocumentClassifier object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_ids') and self.collection_ids is not None: - _dict['collection_ids'] = self.collection_ids - if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = self.passages.to_dict() - if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = self.table_results.to_dict() - if hasattr(self, 'aggregation') and self.aggregation is not None: - _dict['aggregation'] = self.aggregation - if hasattr(self, 'suggested_refinements' - ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = self.suggested_refinements.to_dict( - ) - if hasattr(self, 'spelling_suggestions' - ) and self.spelling_suggestions is not None: - _dict['spelling_suggestions'] = self.spelling_suggestions - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'sort') and self.sort is not None: - _dict['sort'] = self.sort - if hasattr(self, 'return_') and self.return_ is not None: - _dict['return'] = self.return_ + if hasattr(self, 'classifier_id') and getattr( + self, 'classifier_id') is not None: + _dict['classifier_id'] = getattr(self, 'classifier_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, + 'recognized_fields') and self.recognized_fields is not None: + _dict['recognized_fields'] = self.recognized_fields + if hasattr(self, 'answer_field') and self.answer_field is not None: + _dict['answer_field'] = self.answer_field + if hasattr( + self, + 'training_data_file') and self.training_data_file is not None: + _dict['training_data_file'] = self.training_data_file + if hasattr(self, 'test_data_file') and self.test_data_file is not None: + _dict['test_data_file'] = self.test_data_file + if hasattr(self, 'federated_classification' + ) and self.federated_classification is not None: + if isinstance(self.federated_classification, dict): + _dict[ + 'federated_classification'] = self.federated_classification + else: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -3082,109 +6567,77 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParams object.""" + """Return a `str` version of this DocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParams') -> bool: + def __eq__(self, other: 'DocumentClassifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParams') -> bool: + def __ne__(self, other: 'DocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DefaultQueryParamsPassages(): +class DocumentClassifierEnrichment: """ - Default settings configuration for passage search options. + An object that describes enrichments that are applied to the training and test data + that is used by the document classifier. - :attr bool enabled: (optional) When `true`, a passage search is performed by - default. - :attr int count: (optional) The number of passages to return. - :attr List[str] fields: (optional) An array of field names to perform the - passage search on. - :attr int characters: (optional) The approximate number of characters that each - returned passage will contain. - :attr bool per_document: (optional) When `true` the number of passages that can - be returned from a single document is restricted to the *max_per_document* - value. - :attr int max_per_document: (optional) The default maximum number of passages - that can be taken from a single document as the result of a passage query. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. + :param List[str] fields: An array of field names where the enrichment is + applied. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - fields: List[str] = None, - characters: int = None, - per_document: bool = None, - max_per_document: int = None) -> None: + def __init__( + self, + enrichment_id: str, + fields: List[str], + ) -> None: """ - Initialize a DefaultQueryParamsPassages object. + Initialize a DocumentClassifierEnrichment object. - :param bool enabled: (optional) When `true`, a passage search is performed - by default. - :param int count: (optional) The number of passages to return. - :param List[str] fields: (optional) An array of field names to perform the - passage search on. - :param int characters: (optional) The approximate number of characters that - each returned passage will contain. - :param bool per_document: (optional) When `true` the number of passages - that can be returned from a single document is restricted to the - *max_per_document* value. - :param int max_per_document: (optional) The default maximum number of - passages that can be taken from a single document as the result of a - passage query. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. + :param List[str] fields: An array of field names where the enrichment is + applied. """ - self.enabled = enabled - self.count = count + self.enrichment_id = enrichment_id self.fields = fields - self.characters = characters - self.per_document = per_document - self.max_per_document = max_per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': - """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierEnrichment': + """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + else: + raise ValueError( + 'Required property \'enrichment_id\' not present in DocumentClassifierEnrichment JSON' + ) + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + else: + raise ValueError( + 'Required property \'fields\' not present in DocumentClassifierEnrichment JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id if hasattr(self, 'fields') and self.fields is not None: _dict['fields'] = self.fields - if hasattr(self, 'characters') and self.characters is not None: - _dict['characters'] = self.characters - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document - if hasattr(self, - 'max_per_document') and self.max_per_document is not None: - _dict['max_per_document'] = self.max_per_document return _dict def _to_dict(self): @@ -3192,64 +6645,162 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsPassages object.""" + """Return a `str` version of this DocumentClassifierEnrichment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: + def __eq__(self, other: 'DocumentClassifierEnrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: + def __ne__(self, other: 'DocumentClassifierEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DefaultQueryParamsSuggestedRefinements(): - """ - Object that contains suggested refinement settings. Available with Premium plans only. - - :attr bool enabled: (optional) When `true`, suggested refinements for the query - are returned by default. - :attr int count: (optional) The number of suggested refinements to return by - default. +class DocumentClassifierModel: + """ + Information about a document classifier model. + + :param str model_id: (optional) The Universally Unique Identifier (UUID) of the + document classifier model. + :param str name: A human-readable name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param datetime created: (optional) The date that the document classifier model + was created. + :param datetime updated: (optional) The date that the document classifier model + was last updated. + :param str training_data_file: (optional) Name of the CSV file that contains the + training data that is used to train the document classifier model. + :param str test_data_file: (optional) Name of the CSV file that contains data + that is used to test the document classifier model. If no test data is provided, + a subset of the training data is used for testing purposes. + :param str status: (optional) The status of the training run. + :param ClassifierModelEvaluation evaluation: (optional) An object that contains + information about a trained document classifier model. + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) of + the enrichment that is generated by this document classifier model. + :param datetime deployed_at: (optional) The date that the document classifier + model was deployed. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: - """ - Initialize a DefaultQueryParamsSuggestedRefinements object. - - :param bool enabled: (optional) When `true`, suggested refinements for the - query are returned by default. - :param int count: (optional) The number of suggested refinements to return - by default. + def __init__( + self, + name: str, + *, + model_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + training_data_file: Optional[str] = None, + test_data_file: Optional[str] = None, + status: Optional[str] = None, + evaluation: Optional['ClassifierModelEvaluation'] = None, + enrichment_id: Optional[str] = None, + deployed_at: Optional[datetime] = None, + ) -> None: """ - self.enabled = enabled - self.count = count + Initialize a DocumentClassifierModel object. + + :param str name: A human-readable name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param str training_data_file: (optional) Name of the CSV file that + contains the training data that is used to train the document classifier + model. + :param str test_data_file: (optional) Name of the CSV file that contains + data that is used to test the document classifier model. If no test data is + provided, a subset of the training data is used for testing purposes. + :param str status: (optional) The status of the training run. + :param ClassifierModelEvaluation evaluation: (optional) An object that + contains information about a trained document classifier model. + :param str enrichment_id: (optional) The Universally Unique Identifier + (UUID) of the enrichment that is generated by this document classifier + model. + """ + self.model_id = model_id + self.name = name + self.description = description + self.created = created + self.updated = updated + self.training_data_file = training_data_file + self.test_data_file = test_data_file + self.status = status + self.evaluation = evaluation + self.enrichment_id = enrichment_id + self.deployed_at = deployed_at @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': - """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModel': + """Initialize a DocumentClassifierModel object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in DocumentClassifierModel JSON' + ) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (training_data_file := _dict.get('training_data_file')) is not None: + args['training_data_file'] = training_data_file + if (test_data_file := _dict.get('test_data_file')) is not None: + args['test_data_file'] = test_data_file + if (status := _dict.get('status')) is not None: + args['status'] = status + if (evaluation := _dict.get('evaluation')) is not None: + args['evaluation'] = ClassifierModelEvaluation.from_dict(evaluation) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (deployed_at := _dict.get('deployed_at')) is not None: + args['deployed_at'] = string_to_datetime(deployed_at) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + """Initialize a DocumentClassifierModel object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count + if hasattr(self, 'model_id') and getattr(self, 'model_id') is not None: + _dict['model_id'] = getattr(self, 'model_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr( + self, + 'training_data_file') and self.training_data_file is not None: + _dict['training_data_file'] = self.training_data_file + if hasattr(self, 'test_data_file') and self.test_data_file is not None: + _dict['test_data_file'] = self.test_data_file + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'evaluation') and self.evaluation is not None: + if isinstance(self.evaluation, dict): + _dict['evaluation'] = self.evaluation + else: + _dict['evaluation'] = self.evaluation.to_dict() + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'deployed_at') and getattr(self, + 'deployed_at') is not None: + _dict['deployed_at'] = datetime_to_string( + getattr(self, 'deployed_at')) return _dict def _to_dict(self): @@ -3257,76 +6808,76 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" + """Return a `str` version of this DocumentClassifierModel object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: + def __eq__(self, other: 'DocumentClassifierModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: + def __ne__(self, other: 'DocumentClassifierModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The status of the training run. + """ + + TRAINING = 'training' + AVAILABLE = 'available' + FAILED = 'failed' + -class DefaultQueryParamsTableResults(): +class DocumentClassifierModels: """ - Default project query settings for table results. + An object that contains a list of document classifier model definitions. - :attr bool enabled: (optional) When `true`, a table results for the query are - returned by default. - :attr int count: (optional) The number of table results to return by default. - :attr int per_document: (optional) The number of table results to include in - each result document. + :param List[DocumentClassifierModel] models: (optional) An array of document + classifier model definitions. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - per_document: int = None) -> None: + def __init__( + self, + *, + models: Optional[List['DocumentClassifierModel']] = None, + ) -> None: """ - Initialize a DefaultQueryParamsTableResults object. + Initialize a DocumentClassifierModels object. - :param bool enabled: (optional) When `true`, a table results for the query - are returned by default. - :param int count: (optional) The number of table results to return by - default. - :param int per_document: (optional) The number of table results to include - in each result document. + :param List[DocumentClassifierModel] models: (optional) An array of + document classifier model definitions. """ - self.enabled = enabled - self.count = count - self.per_document = per_document + self.models = models @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': - """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModels': + """Initialize a DocumentClassifierModels object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') + if (models := _dict.get('models')) is not None: + args['models'] = [ + DocumentClassifierModel.from_dict(v) for v in models + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" + """Initialize a DocumentClassifierModels object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document + if hasattr(self, 'models') and self.models is not None: + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -3334,62 +6885,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsTableResults object.""" + """Return a `str` version of this DocumentClassifierModels object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: + def __eq__(self, other: 'DocumentClassifierModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: + def __ne__(self, other: 'DocumentClassifierModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DeleteDocumentResponse(): +class DocumentClassifiers: """ - Information returned when a document is deleted. + An object that contains a list of document classifier definitions. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the - status deleted. + :param List[DocumentClassifier] classifiers: (optional) An array of document + classifier definitions. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + classifiers: Optional[List['DocumentClassifier']] = None, + ) -> None: """ - Initialize a DeleteDocumentResponse object. + Initialize a DocumentClassifiers object. - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. + :param List[DocumentClassifier] classifiers: (optional) An array of + document classifier definitions. """ - self.document_id = document_id - self.status = status + self.classifiers = classifiers @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifiers': + """Initialize a DocumentClassifiers object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (classifiers := _dict.get('classifiers')) is not None: + args['classifiers'] = [ + DocumentClassifier.from_dict(v) for v in classifiers + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + """Initialize a DocumentClassifiers object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'classifiers') and self.classifiers is not None: + classifiers_list = [] + for v in self.classifiers: + if isinstance(v, dict): + classifiers_list.append(v) + else: + classifiers_list.append(v.to_dict()) + _dict['classifiers'] = classifiers_list return _dict def _to_dict(self): @@ -3397,74 +6953,162 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DeleteDocumentResponse object.""" + """Return a `str` version of this DocumentClassifiers object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DeleteDocumentResponse') -> bool: + def __eq__(self, other: 'DocumentClassifiers') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DeleteDocumentResponse') -> bool: + def __ne__(self, other: 'DocumentClassifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - DELETED = 'deleted' - - -class DocumentAccepted(): - """ - Information returned after an uploaded document is accepted. - :attr str document_id: (optional) The unique identifier of the ingested - document. - :attr str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. +class DocumentDetails: + """ + Information about a document. + + :param str document_id: (optional) The unique identifier of the document. + :param datetime created: (optional) Date and time that the document is added to + the collection. For a child document, the date and time when the process that + generates the child document runs. The date-time format is + `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :param datetime updated: (optional) Date and time that the document is finished + being processed and is indexed. This date changes whenever the document is + reprocessed, including for enrichment changes. The date-time format is + `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :param str status: (optional) The status of the ingestion of the document. The + possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because of an + error. + * `pending`: The document is uploaded, but the ingestion process is not started. + * `processing`: Ingestion is in progress. + :param List[Notice] notices: (optional) Array of JSON objects for notices, + meaning warning or error messages, that are produced by the document ingestion + process. The array does not include notices that are produced for child + documents that are generated when a document is processed. + :param DocumentDetailsChildren children: (optional) Information about the child + documents that are generated from a single document during ingestion or other + processing. + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file, such as + `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. + :param str sha256: (optional) The SHA-256 hash of the original source file. The + hash is formatted as a hexadecimal string. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + notices: Optional[List['Notice']] = None, + children: Optional['DocumentDetailsChildren'] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha256: Optional[str] = None, + ) -> None: """ - Initialize a DocumentAccepted object. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. + Initialize a DocumentDetails object. + + :param str status: (optional) The status of the ingestion of the document. + The possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because + of an error. + * `pending`: The document is uploaded, but the ingestion process is not + started. + * `processing`: Ingestion is in progress. + :param List[Notice] notices: (optional) Array of JSON objects for notices, + meaning warning or error messages, that are produced by the document + ingestion process. The array does not include notices that are produced for + child documents that are generated when a document is processed. + :param DocumentDetailsChildren children: (optional) Information about the + child documents that are generated from a single document during ingestion + or other processing. + :param str filename: (optional) Name of the original source file (if + available). + :param str file_type: (optional) The type of the original source file, such + as `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. + :param str sha256: (optional) The SHA-256 hash of the original source file. + The hash is formatted as a hexadecimal string. """ self.document_id = document_id + self.created = created + self.updated = updated self.status = status + self.notices = notices + self.children = children + self.filename = filename + self.file_type = file_type + self.sha256 = sha256 @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentDetails': + """Initialize a DocumentDetails object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (children := _dict.get('children')) is not None: + args['children'] = DocumentDetailsChildren.from_dict(children) + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha256 := _dict.get('sha256')) is not None: + args['sha256'] = sha256 return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAccepted object from a json dictionary.""" + """Initialize a DocumentDetails object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id + if hasattr(self, 'document_id') and getattr(self, + 'document_id') is not None: + _dict['document_id'] = getattr(self, 'document_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status + if hasattr(self, 'notices') and self.notices is not None: + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list + if hasattr(self, 'children') and self.children is not None: + if isinstance(self.children, dict): + _dict['children'] = self.children + else: + _dict['children'] = self.children.to_dict() + if hasattr(self, 'filename') and self.filename is not None: + _dict['filename'] = self.filename + if hasattr(self, 'file_type') and self.file_type is not None: + _dict['file_type'] = self.file_type + if hasattr(self, 'sha256') and self.sha256 is not None: + _dict['sha256'] = self.sha256 return _dict def _to_dict(self): @@ -3472,85 +7116,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" + """Return a `str` version of this DocumentDetails object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DocumentAccepted') -> bool: + def __eq__(self, other: 'DocumentDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DocumentAccepted') -> bool: + def __ne__(self, other: 'DocumentDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class StatusEnum(str, Enum): """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. + The status of the ingestion of the document. The possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because of an + error. + * `pending`: The document is uploaded, but the ingestion process is not started. + * `processing`: Ingestion is in progress. """ - PROCESSING = 'processing' + + AVAILABLE = 'available' + FAILED = 'failed' PENDING = 'pending' + PROCESSING = 'processing' -class DocumentAttribute(): +class DocumentDetailsChildren: """ - List of document attributes. + Information about the child documents that are generated from a single document during + ingestion or other processing. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. + :param bool have_notices: (optional) Indicates whether the child documents have + any notices. The value is `false` if the document does not have child documents. + :param int count: (optional) Number of child documents. The value is `0` when + processing of the document doesn't generate any child documents. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__( + self, + *, + have_notices: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ - Initialize a DocumentAttribute object. + Initialize a DocumentDetailsChildren object. - :param str type: (optional) The type of attribute. - :param str text: (optional) The text associated with the attribute. - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. + :param bool have_notices: (optional) Indicates whether the child documents + have any notices. The value is `false` if the document does not have child + documents. + :param int count: (optional) Number of child documents. The value is `0` + when processing of the document doesn't generate any child documents. """ - self.type = type - self.text = text - self.location = location + self.have_notices = have_notices + self.count = count @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': - """Initialize a DocumentAttribute object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentDetailsChildren': + """Initialize a DocumentDetailsChildren object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if (have_notices := _dict.get('have_notices')) is not None: + args['have_notices'] = have_notices + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAttribute object from a json dictionary.""" + """Initialize a DocumentDetailsChildren object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if hasattr(self, 'have_notices') and self.have_notices is not None: + _dict['have_notices'] = self.have_notices + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count return _dict def _to_dict(self): @@ -3558,40 +7203,43 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAttribute object.""" + """Return a `str` version of this DocumentDetailsChildren object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DocumentAttribute') -> bool: + def __eq__(self, other: 'DocumentDetailsChildren') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DocumentAttribute') -> bool: + def __ne__(self, other: 'DocumentDetailsChildren') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Enrichment(): +class Enrichment: """ Information about a specific enrichment. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) An object that contains options for + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) of + this enrichment. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. """ - def __init__(self, - *, - enrichment_id: str = None, - name: str = None, - description: str = None, - type: str = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + *, + enrichment_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + type: Optional[str] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a Enrichment object. @@ -3613,16 +7261,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (type := _dict.get('type')) is not None: + args['type'] = type + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -3643,7 +7291,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -3668,6 +7319,7 @@ class TypeEnum(str, Enum): """ The type of this enrichment. """ + PART_OF_SPEECH = 'part_of_speech' SENTIMENT = 'sentiment' NATURAL_LANGUAGE_UNDERSTANDING = 'natural_language_understanding' @@ -3676,68 +7328,186 @@ class TypeEnum(str, Enum): UIMA_ANNOTATOR = 'uima_annotator' RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + CLASSIFIER = 'classifier' + WEBHOOK = 'webhook' + SENTENCE_CLASSIFIER = 'sentence_classifier' -class EnrichmentOptions(): +class EnrichmentOptions: """ An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. - :attr List[str] languages: (optional) An array of supported languages for this - enrichment. Required when `type` is `dictionary`. Optional when `type` is - `rule_based`. Not valid when creating any other type of enrichment. - :attr str entity_type: (optional) The name of the entity type. This value is - used as the field name in the index. Required when `type` is `dictionary` or + :param List[str] languages: (optional) An array of supported languages for this + enrichment. When creating an enrichment, only specify a language that is used by + the model or in the dictionary. Required when **type** is `dictionary`. Optional + when **type** is `rule_based`. Not valid when creating any other type of + enrichment. + :param str entity_type: (optional) The name of the entity type. This value is + used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. - :attr str regular_expression: (optional) The regular expression to apply for - this enrichment. Required when `type` is `regular_expression`. Not valid when + :param str regular_expression: (optional) The regular expression to apply for + this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. - :attr str result_field: (optional) The name of the result document field that - this enrichment creates. Required when `type` is `rule_based`. Not valid when + :param str result_field: (optional) The name of the result document field that + this enrichment creates. Required when **type** is `rule_based` or `classifier`. + Not valid when creating any other type of enrichment. + :param str classifier_id: (optional) The Universally Unique Identifier (UUID) of + the document classifier. Required when **type** is `classifier`. Not valid when creating any other type of enrichment. + :param str model_id: (optional) The Universally Unique Identifier (UUID) of the + document classifier model. Required when **type** is `classifier`. Not valid + when creating any other type of enrichment. + :param float confidence_threshold: (optional) Specifies a threshold. Only + classes with evaluation confidence scores that are higher than the specified + threshold are included in the output. Optional when **type** is `classifier`. + Not valid when creating any other type of enrichment. + :param int top_k: (optional) Evaluates only the classes that fall in the top set + of results when ranked by confidence. For example, if set to `5`, then the top + five classes for each document are evaluated. If set to 0, the + **confidence_threshold** is used to determine the predicted classes. Optional + when **type** is `classifier`. Not valid when creating any other type of + enrichment. + :param str url: (optional) A URL that uses the SSL protocol (begins with https) + for the webhook. Required when type is `webhook`. Not valid when creating any + other type of enrichment. + :param str version: (optional) The Discovery API version that allows to + distinguish the schema. The version is specified in the `yyyy-mm-dd` format. + Optional when `type` is `webhook`. Not valid when creating any other type of + enrichment. + :param str secret: (optional) A private key can be included in the request to + authenticate with the external service. The maximum length is 1,024 characters. + Optional when `type` is `webhook`. Not valid when creating any other type of + enrichment. + :param WebhookHeader headers_: (optional) An array of headers to pass with the + HTTP request. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param str location_encoding: (optional) Discovery calculates offsets of the + text's location with this encoding type in documents. Use the same location + encoding type in both Discovery and external enrichment for a document. + These encoding types are supported: `utf-8`, `utf-16`, and `utf-32`. Optional + when `type` is `webhook`. Not valid when creating any other type of enrichment. """ - def __init__(self, - *, - languages: List[str] = None, - entity_type: str = None, - regular_expression: str = None, - result_field: str = None) -> None: + def __init__( + self, + *, + languages: Optional[List[str]] = None, + entity_type: Optional[str] = None, + regular_expression: Optional[str] = None, + result_field: Optional[str] = None, + classifier_id: Optional[str] = None, + model_id: Optional[str] = None, + confidence_threshold: Optional[float] = None, + top_k: Optional[int] = None, + url: Optional[str] = None, + version: Optional[str] = None, + secret: Optional[str] = None, + headers_: Optional['WebhookHeader'] = None, + location_encoding: Optional[str] = None, + ) -> None: """ Initialize a EnrichmentOptions object. :param List[str] languages: (optional) An array of supported languages for - this enrichment. Required when `type` is `dictionary`. Optional when `type` - is `rule_based`. Not valid when creating any other type of enrichment. + this enrichment. When creating an enrichment, only specify a language that + is used by the model or in the dictionary. Required when **type** is + `dictionary`. Optional when **type** is `rule_based`. Not valid when + creating any other type of enrichment. :param str entity_type: (optional) The name of the entity type. This value - is used as the field name in the index. Required when `type` is + is used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. :param str regular_expression: (optional) The regular expression to apply - for this enrichment. Required when `type` is `regular_expression`. Not + for this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. :param str result_field: (optional) The name of the result document field - that this enrichment creates. Required when `type` is `rule_based`. Not + that this enrichment creates. Required when **type** is `rule_based` or + `classifier`. Not valid when creating any other type of enrichment. + :param str classifier_id: (optional) The Universally Unique Identifier + (UUID) of the document classifier. Required when **type** is `classifier`. + Not valid when creating any other type of enrichment. + :param str model_id: (optional) The Universally Unique Identifier (UUID) of + the document classifier model. Required when **type** is `classifier`. Not valid when creating any other type of enrichment. + :param float confidence_threshold: (optional) Specifies a threshold. Only + classes with evaluation confidence scores that are higher than the + specified threshold are included in the output. Optional when **type** is + `classifier`. Not valid when creating any other type of enrichment. + :param int top_k: (optional) Evaluates only the classes that fall in the + top set of results when ranked by confidence. For example, if set to `5`, + then the top five classes for each document are evaluated. If set to 0, the + **confidence_threshold** is used to determine the predicted classes. + Optional when **type** is `classifier`. Not valid when creating any other + type of enrichment. + :param str url: (optional) A URL that uses the SSL protocol (begins with + https) for the webhook. Required when type is `webhook`. Not valid when + creating any other type of enrichment. + :param str version: (optional) The Discovery API version that allows to + distinguish the schema. The version is specified in the `yyyy-mm-dd` + format. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param str secret: (optional) A private key can be included in the request + to authenticate with the external service. The maximum length is 1,024 + characters. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param WebhookHeader headers_: (optional) An array of headers to pass with + the HTTP request. Optional when `type` is `webhook`. Not valid when + creating any other type of enrichment. + :param str location_encoding: (optional) Discovery calculates offsets of + the text's location with this encoding type in documents. Use the same + location encoding type in both Discovery and external enrichment for a + document. + These encoding types are supported: `utf-8`, `utf-16`, and `utf-32`. + Optional when `type` is `webhook`. Not valid when creating any other type + of enrichment. """ self.languages = languages self.entity_type = entity_type self.regular_expression = regular_expression self.result_field = result_field + self.classifier_id = classifier_id + self.model_id = model_id + self.confidence_threshold = confidence_threshold + self.top_k = top_k + self.url = url + self.version = version + self.secret = secret + self.headers_ = headers_ + self.location_encoding = location_encoding @classmethod def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - if 'languages' in _dict: - args['languages'] = _dict.get('languages') - if 'entity_type' in _dict: - args['entity_type'] = _dict.get('entity_type') - if 'regular_expression' in _dict: - args['regular_expression'] = _dict.get('regular_expression') - if 'result_field' in _dict: - args['result_field'] = _dict.get('result_field') + if (languages := _dict.get('languages')) is not None: + args['languages'] = languages + if (entity_type := _dict.get('entity_type')) is not None: + args['entity_type'] = entity_type + if (regular_expression := _dict.get('regular_expression')) is not None: + args['regular_expression'] = regular_expression + if (result_field := _dict.get('result_field')) is not None: + args['result_field'] = result_field + if (classifier_id := _dict.get('classifier_id')) is not None: + args['classifier_id'] = classifier_id + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (top_k := _dict.get('top_k')) is not None: + args['top_k'] = top_k + if (url := _dict.get('url')) is not None: + args['url'] = url + if (version := _dict.get('version')) is not None: + args['version'] = version + if (secret := _dict.get('secret')) is not None: + args['secret'] = secret + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = WebhookHeader.from_dict(headers_) + if (location_encoding := _dict.get('location_encoding')) is not None: + args['location_encoding'] = location_encoding return cls(**args) @classmethod @@ -3758,6 +7528,29 @@ def to_dict(self) -> Dict: _dict['regular_expression'] = self.regular_expression if hasattr(self, 'result_field') and self.result_field is not None: _dict['result_field'] = self.result_field + if hasattr(self, 'classifier_id') and self.classifier_id is not None: + _dict['classifier_id'] = self.classifier_id + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'top_k') and self.top_k is not None: + _dict['top_k'] = self.top_k + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'version') and self.version is not None: + _dict['version'] = self.version + if hasattr(self, 'secret') and self.secret is not None: + _dict['secret'] = self.secret + if hasattr(self, 'headers_') and self.headers_ is not None: + if isinstance(self.headers_, dict): + _dict['headers'] = self.headers_ + else: + _dict['headers'] = self.headers_.to_dict() + if hasattr(self, + 'location_encoding') and self.location_encoding is not None: + _dict['location_encoding'] = self.location_encoding return _dict def _to_dict(self): @@ -3779,15 +7572,19 @@ def __ne__(self, other: 'EnrichmentOptions') -> bool: return not self == other -class Enrichments(): +class Enrichments: """ An object that contains an array of enrichment definitions. - :attr List[Enrichment] enrichments: (optional) An array of enrichment + :param List[Enrichment] enrichments: (optional) An array of enrichment definitions. """ - def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: + def __init__( + self, + *, + enrichments: Optional[List['Enrichment']] = None, + ) -> None: """ Initialize a Enrichments object. @@ -3800,10 +7597,8 @@ def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Enrichments': """Initialize a Enrichments object from a json dictionary.""" args = {} - if 'enrichments' in _dict: - args['enrichments'] = [ - Enrichment.from_dict(x) for x in _dict.get('enrichments') - ] + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] return cls(**args) @classmethod @@ -3815,7 +7610,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list return _dict def _to_dict(self): @@ -3837,21 +7638,195 @@ def __ne__(self, other: 'Enrichments') -> bool: return not self == other -class Field(): +class Expansion: + """ + An expansion definition. Each object respresents one set of expandable strings. For + example, you could have expansions for the word `hot` in one object, and expansions + for the word `cold` in another. Follow these guidelines when you add terms: + * Specify the terms in lowercase. Lowercase terms expand to uppercase. + * Multiword terms are supported only in bidirectional expansions. + * Do not specify a term that is specified in the stop words list for the collection. + + :param List[str] input_terms: (optional) A list of terms that will be expanded + for this expansion. If specified, only the items in this list are expanded. + :param List[str] expanded_terms: A list of terms that this expansion will be + expanded to. If specified without **input_terms**, the list also functions as + the input term list. + """ + + def __init__( + self, + expanded_terms: List[str], + *, + input_terms: Optional[List[str]] = None, + ) -> None: + """ + Initialize a Expansion object. + + :param List[str] expanded_terms: A list of terms that this expansion will + be expanded to. If specified without **input_terms**, the list also + functions as the input term list. + :param List[str] input_terms: (optional) A list of terms that will be + expanded for this expansion. If specified, only the items in this list are + expanded. + """ + self.input_terms = input_terms + self.expanded_terms = expanded_terms + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Expansion': + """Initialize a Expansion object from a json dictionary.""" + args = {} + if (input_terms := _dict.get('input_terms')) is not None: + args['input_terms'] = input_terms + if (expanded_terms := _dict.get('expanded_terms')) is not None: + args['expanded_terms'] = expanded_terms + else: + raise ValueError( + 'Required property \'expanded_terms\' not present in Expansion JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansion object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input_terms') and self.input_terms is not None: + _dict['input_terms'] = self.input_terms + if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: + _dict['expanded_terms'] = self.expanded_terms + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Expansion object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Expansion') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Expansion') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Expansions: + """ + The query expansion definitions for the specified collection. + + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms that + will be expanded into other terms. Each expansion object can be configured as + `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to include + all expanded terms. For example, a query for `ibm` expands to `ibm OR + international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced by + the terms in `expanded_terms`. For example, a query for the often misused term + `on premise` is converted to `on premises OR on-premises` and does not contain + the original term. If you want an input term to be included in the query, then + repeat the input term in the expanded terms list. + """ + + def __init__( + self, + expansions: List['Expansion'], + ) -> None: + """ + Initialize a Expansions object. + + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to + include all expanded terms. For example, a query for `ibm` expands to `ibm + OR international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced + by the terms in `expanded_terms`. For example, a query for the often + misused term `on premise` is converted to `on premises OR on-premises` and + does not contain the original term. If you want an input term to be + included in the query, then repeat the input term in the expanded terms + list. + """ + self.expansions = expansions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Expansions': + """Initialize a Expansions object from a json dictionary.""" + args = {} + if (expansions := _dict.get('expansions')) is not None: + args['expansions'] = [Expansion.from_dict(v) for v in expansions] + else: + raise ValueError( + 'Required property \'expansions\' not present in Expansions JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'expansions') and self.expansions is not None: + expansions_list = [] + for v in self.expansions: + if isinstance(v, dict): + expansions_list.append(v) + else: + expansions_list.append(v.to_dict()) + _dict['expansions'] = expansions_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Expansions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Expansions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Expansions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Field: """ Object that contains field details. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. - :attr str collection_id: (optional) The collection Id of the collection where + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. + :param str collection_id: (optional) The collection Id of the collection where the field was found. """ - def __init__(self, - *, - field: str = None, - type: str = None, - collection_id: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + type: Optional[str] = None, + collection_id: Optional[str] = None, + ) -> None: """ Initialize a Field object. @@ -3864,12 +7839,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (field := _dict.get('field')) is not None: + args['field'] = field + if (type := _dict.get('type')) is not None: + args['type'] = type + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id return cls(**args) @classmethod @@ -3907,60 +7882,219 @@ def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of the field. - """ - NESTED = 'nested' - STRING = 'string' - DATE = 'date' - LONG = 'long' - INTEGER = 'integer' - SHORT = 'short' - BYTE = 'byte' - DOUBLE = 'double' - FLOAT = 'float' - BOOLEAN = 'boolean' - BINARY = 'binary' - + class TypeEnum(str, Enum): + """ + The type of the field. + """ + + NESTED = 'nested' + STRING = 'string' + DATE = 'date' + LONG = 'long' + INTEGER = 'integer' + SHORT = 'short' + BYTE = 'byte' + DOUBLE = 'double' + FLOAT = 'float' + BOOLEAN = 'boolean' + BINARY = 'binary' + + +class ListBatchesResponse: + """ + An object that contains a list of batches that are ready for enrichment by the + external application. + + :param List[BatchDetails] batches: (optional) An array that lists the batches in + a collection. + """ + + def __init__( + self, + *, + batches: Optional[List['BatchDetails']] = None, + ) -> None: + """ + Initialize a ListBatchesResponse object. + + :param List[BatchDetails] batches: (optional) An array that lists the + batches in a collection. + """ + self.batches = batches + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListBatchesResponse': + """Initialize a ListBatchesResponse object from a json dictionary.""" + args = {} + if (batches := _dict.get('batches')) is not None: + args['batches'] = [BatchDetails.from_dict(v) for v in batches] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListBatchesResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'batches') and self.batches is not None: + batches_list = [] + for v in self.batches: + if isinstance(v, dict): + batches_list.append(v) + else: + batches_list.append(v.to_dict()) + _dict['batches'] = batches_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ListBatchesResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListBatchesResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ListBatchesResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListCollectionsResponse: + """ + Response object that contains an array of collection details. + + :param List[Collection] collections: (optional) An array that contains + information about each collection in the project. + """ + + def __init__( + self, + *, + collections: Optional[List['Collection']] = None, + ) -> None: + """ + Initialize a ListCollectionsResponse object. + + :param List[Collection] collections: (optional) An array that contains + information about each collection in the project. + """ + self.collections = collections + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': + """Initialize a ListCollectionsResponse object from a json dictionary.""" + args = {} + if (collections := _dict.get('collections')) is not None: + args['collections'] = [Collection.from_dict(v) for v in collections] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collections') and self.collections is not None: + collections_list = [] + for v in self.collections: + if isinstance(v, dict): + collections_list.append(v) + else: + collections_list.append(v.to_dict()) + _dict['collections'] = collections_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ListCollectionsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListCollectionsResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ListCollectionsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + -class ListCollectionsResponse(): +class ListDocumentsResponse: """ - Response object that contains an array of collection details. + Response object that contains an array of documents. - :attr List[Collection] collections: (optional) An array that contains - information about each collection in the project. + :param int matching_results: (optional) The number of matching results for the + document query. + :param List[DocumentDetails] documents: (optional) An array that lists the + documents in a collection. Only the document ID of each document is returned in + the list. You can use the [Get document](#getdocument) method to get more + information about an individual document. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + documents: Optional[List['DocumentDetails']] = None, + ) -> None: """ - Initialize a ListCollectionsResponse object. + Initialize a ListDocumentsResponse object. - :param List[Collection] collections: (optional) An array that contains - information about each collection in the project. + :param int matching_results: (optional) The number of matching results for + the document query. + :param List[DocumentDetails] documents: (optional) An array that lists the + documents in a collection. Only the document ID of each document is + returned in the list. You can use the [Get document](#getdocument) method + to get more information about an individual document. """ - self.collections = collections + self.matching_results = matching_results + self.documents = documents @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListDocumentsResponse': + """Initialize a ListDocumentsResponse object from a json dictionary.""" args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (documents := _dict.get('documents')) is not None: + args['documents'] = [ + DocumentDetails.from_dict(v) for v in documents ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListCollectionsResponse object from a json dictionary.""" + """Initialize a ListDocumentsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'documents') and self.documents is not None: + documents_list = [] + for v in self.documents: + if isinstance(v, dict): + documents_list.append(v) + else: + documents_list.append(v.to_dict()) + _dict['documents'] = documents_list return _dict def _to_dict(self): @@ -3968,21 +8102,21 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListCollectionsResponse object.""" + """Return a `str` version of this ListDocumentsResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListCollectionsResponse') -> bool: + def __eq__(self, other: 'ListDocumentsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListCollectionsResponse') -> bool: + def __ne__(self, other: 'ListDocumentsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ListFieldsResponse(): +class ListFieldsResponse: """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format @@ -3992,11 +8126,15 @@ class ListFieldsResponse(): example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). - :attr List[Field] fields: (optional) An array that contains information about + :param List[Field] fields: (optional) An array that contains information about each field in the collections. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__( + self, + *, + fields: Optional[List['Field']] = None, + ) -> None: """ Initialize a ListFieldsResponse object. @@ -4009,8 +8147,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + if (fields := _dict.get('fields')) is not None: + args['fields'] = [Field.from_dict(v) for v in fields] return cls(**args) @classmethod @@ -4022,7 +8160,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] + fields_list = [] + for v in self.fields: + if isinstance(v, dict): + fields_list.append(v) + else: + fields_list.append(v.to_dict()) + _dict['fields'] = fields_list return _dict def _to_dict(self): @@ -4044,14 +8188,19 @@ def __ne__(self, other: 'ListFieldsResponse') -> bool: return not self == other -class ListProjectsResponse(): +class ListProjectsResponse: """ A list of projects in this instance. - :attr List[ProjectListDetails] projects: (optional) An array of project details. + :param List[ProjectListDetails] projects: (optional) An array of project + details. """ - def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + def __init__( + self, + *, + projects: Optional[List['ProjectListDetails']] = None, + ) -> None: """ Initialize a ListProjectsResponse object. @@ -4064,9 +8213,9 @@ def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - if 'projects' in _dict: + if (projects := _dict.get('projects')) is not None: args['projects'] = [ - ProjectListDetails.from_dict(x) for x in _dict.get('projects') + ProjectListDetails.from_dict(v) for v in projects ] return cls(**args) @@ -4079,7 +8228,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'projects') and self.projects is not None: - _dict['projects'] = [x.to_dict() for x in self.projects] + projects_list = [] + for v in self.projects: + if isinstance(v, dict): + projects_list.append(v) + else: + projects_list.append(v.to_dict()) + _dict['projects'] = projects_list return _dict def _to_dict(self): @@ -4101,14 +8256,209 @@ def __ne__(self, other: 'ListProjectsResponse') -> bool: return not self == other -class Notice(): +class ModelEvaluationMacroAverage: + """ + A macro-average computes metric independently for each class and then takes the + average. Class refers to the classification label that is specified in the + **answer_field**. + + :param float precision: A metric that measures how many of the overall documents + are classified correctly. + :param float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. + """ + + def __init__( + self, + precision: float, + recall: float, + f1: float, + ) -> None: + """ + Initialize a ModelEvaluationMacroAverage object. + + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. + """ + self.precision = precision + self.recall = recall + self.f1 = f1 + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMacroAverage': + """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" + args = {} + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision + else: + raise ValueError( + 'Required property \'precision\' not present in ModelEvaluationMacroAverage JSON' + ) + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall + else: + raise ValueError( + 'Required property \'recall\' not present in ModelEvaluationMacroAverage JSON' + ) + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 + else: + raise ValueError( + 'Required property \'f1\' not present in ModelEvaluationMacroAverage JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ModelEvaluationMacroAverage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ModelEvaluationMacroAverage') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ModelEvaluationMacroAverage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ModelEvaluationMicroAverage: + """ + A micro-average aggregates the contributions of all classes to compute the average + metric. Classes refers to the classification labels that are specified in the + **answer_field**. + + :param float precision: A metric that measures how many of the overall documents + are classified correctly. + :param float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. + """ + + def __init__( + self, + precision: float, + recall: float, + f1: float, + ) -> None: + """ + Initialize a ModelEvaluationMicroAverage object. + + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. + """ + self.precision = precision + self.recall = recall + self.f1 = f1 + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMicroAverage': + """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" + args = {} + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision + else: + raise ValueError( + 'Required property \'precision\' not present in ModelEvaluationMicroAverage JSON' + ) + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall + else: + raise ValueError( + 'Required property \'recall\' not present in ModelEvaluationMicroAverage JSON' + ) + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 + else: + raise ValueError( + 'Required property \'f1\' not present in ModelEvaluationMicroAverage JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ModelEvaluationMicroAverage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ModelEvaluationMicroAverage') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ModelEvaluationMicroAverage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Notice: """ A notice produced for the collection. - :attr str notice_id: (optional) Identifies the notice. Many notices might have + :param str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, + include: + `index_failed`, `index_failed_too_many_requests`, `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, @@ -4118,29 +8468,31 @@ class Notice(): `smart_document_understanding_failed_warning`, `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the + list. Other values might be returned. + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str collection_id: (optional) Unique identifier of the collection. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice + :param str document_id: (optional) Unique identifier of the document. + :param str collection_id: (optional) Unique identifier of the collection. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice occurred. - :attr str description: (optional) The description of the notice. + :param str description: (optional) The description of the notice. """ - def __init__(self, - *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - collection_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: + def __init__( + self, + *, + notice_id: Optional[str] = None, + created: Optional[datetime] = None, + document_id: Optional[str] = None, + collection_id: Optional[str] = None, + query_id: Optional[str] = None, + severity: Optional[str] = None, + step: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -4158,22 +8510,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (notice_id := _dict.get('notice_id')) is not None: + args['notice_id'] = notice_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (severity := _dict.get('severity')) is not None: + args['severity'] = severity + if (step := _dict.get('step')) is not None: + args['step'] = step + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -4228,38 +8580,154 @@ class SeverityEnum(str, Enum): """ Severity level of the notice. """ + WARNING = 'warning' ERROR = 'error' -class ProjectDetails(): +class PerClassModelEvaluation: + """ + An object that measures the metrics from a training run for each classification label + separately. + + :param str name: Class name. Each class name is derived from a value in the + **answer_field**. + :param float precision: A metric that measures how many of the overall documents + are classified correctly. + :param float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. + """ + + def __init__( + self, + name: str, + precision: float, + recall: float, + f1: float, + ) -> None: + """ + Initialize a PerClassModelEvaluation object. + + :param str name: Class name. Each class name is derived from a value in the + **answer_field**. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. + """ + self.name = name + self.precision = precision + self.recall = recall + self.f1 = f1 + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PerClassModelEvaluation': + """Initialize a PerClassModelEvaluation object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in PerClassModelEvaluation JSON' + ) + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision + else: + raise ValueError( + 'Required property \'precision\' not present in PerClassModelEvaluation JSON' + ) + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall + else: + raise ValueError( + 'Required property \'recall\' not present in PerClassModelEvaluation JSON' + ) + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 + else: + raise ValueError( + 'Required property \'f1\' not present in PerClassModelEvaluation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PerClassModelEvaluation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this PerClassModelEvaluation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PerClassModelEvaluation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'PerClassModelEvaluation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProjectDetails: """ Detailed information about the specified project. - :attr str project_id: (optional) The unique identifier of this project. - :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The type of project. + :param str project_id: (optional) The Universally Unique Identifier (UUID) of + this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :attr int collection_count: (optional) The number of collections configured in + :param int collection_count: (optional) The number of collections configured in this project. - :attr DefaultQueryParams default_query_parameters: (optional) Default query + :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ - def __init__(self, - *, - project_id: str = None, - name: str = None, - type: str = None, - relevancy_training_status: - 'ProjectListDetailsRelevancyTrainingStatus' = None, - collection_count: int = None, - default_query_parameters: 'DefaultQueryParams' = None) -> None: + def __init__( + self, + *, + project_id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + relevancy_training_status: Optional[ + 'ProjectListDetailsRelevancyTrainingStatus'] = None, + collection_count: Optional[int] = None, + default_query_parameters: Optional['DefaultQueryParams'] = None, + ) -> None: """ Initialize a ProjectDetails object. @@ -4269,8 +8737,8 @@ def __init__(self, project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: - (optional) Relevancy training status information for this project. + The Intelligent Document Processing (IDP) project type is available from + IBM Cloud-managed instances only. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ @@ -4285,21 +8753,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectDetails': """Initialize a ProjectDetails object from a json dictionary.""" args = {} - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'relevancy_training_status' in _dict: + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (type := _dict.get('type')) is not None: + args['type'] = type + if (relevancy_training_status := + _dict.get('relevancy_training_status')) is not None: args[ 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( - _dict.get('relevancy_training_status')) - if 'collection_count' in _dict: - args['collection_count'] = _dict.get('collection_count') - if 'default_query_parameters' in _dict: + relevancy_training_status) + if (collection_count := _dict.get('collection_count')) is not None: + args['collection_count'] = collection_count + if (default_query_parameters := + _dict.get('default_query_parameters')) is not None: args['default_query_parameters'] = DefaultQueryParams.from_dict( - _dict.get('default_query_parameters')) + default_query_parameters) return cls(**args) @classmethod @@ -4317,19 +8787,26 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'relevancy_training_status' - ) and self.relevancy_training_status is not None: - _dict[ - 'relevancy_training_status'] = self.relevancy_training_status.to_dict( - ) + if hasattr(self, 'relevancy_training_status') and getattr( + self, 'relevancy_training_status') is not None: + if isinstance(getattr(self, 'relevancy_training_status'), dict): + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status') + else: + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status').to_dict() if hasattr(self, 'collection_count') and getattr( self, 'collection_count') is not None: _dict['collection_count'] = getattr(self, 'collection_count') if hasattr(self, 'default_query_parameters' ) and self.default_query_parameters is not None: - _dict[ - 'default_query_parameters'] = self.default_query_parameters.to_dict( - ) + if isinstance(self.default_query_parameters, dict): + _dict[ + 'default_query_parameters'] = self.default_query_parameters + else: + _dict[ + 'default_query_parameters'] = self.default_query_parameters.to_dict( + ) return _dict def _to_dict(self): @@ -4357,7 +8834,11 @@ class TypeEnum(str, Enum): and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. """ + + INTELLIGENT_DOCUMENT_PROCESSING = 'intelligent_document_processing' DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -4365,31 +8846,36 @@ class TypeEnum(str, Enum): OTHER = 'other' -class ProjectListDetails(): +class ProjectListDetails: """ Details about a specific project. - :attr str project_id: (optional) The unique identifier of this project. - :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The type of project. + :param str project_id: (optional) The Universally Unique Identifier (UUID) of + this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :attr int collection_count: (optional) The number of collections configured in + :param int collection_count: (optional) The number of collections configured in this project. """ - def __init__(self, - *, - project_id: str = None, - name: str = None, - type: str = None, - relevancy_training_status: - 'ProjectListDetailsRelevancyTrainingStatus' = None, - collection_count: int = None) -> None: + def __init__( + self, + *, + project_id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + relevancy_training_status: Optional[ + 'ProjectListDetailsRelevancyTrainingStatus'] = None, + collection_count: Optional[int] = None, + ) -> None: """ Initialize a ProjectListDetails object. @@ -4399,8 +8885,8 @@ def __init__(self, project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: - (optional) Relevancy training status information for this project. + The Intelligent Document Processing (IDP) project type is available from + IBM Cloud-managed instances only. """ self.project_id = project_id self.name = name @@ -4412,18 +8898,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': """Initialize a ProjectListDetails object from a json dictionary.""" args = {} - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'relevancy_training_status' in _dict: + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (type := _dict.get('type')) is not None: + args['type'] = type + if (relevancy_training_status := + _dict.get('relevancy_training_status')) is not None: args[ 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( - _dict.get('relevancy_training_status')) - if 'collection_count' in _dict: - args['collection_count'] = _dict.get('collection_count') + relevancy_training_status) + if (collection_count := _dict.get('collection_count')) is not None: + args['collection_count'] = collection_count return cls(**args) @classmethod @@ -4441,11 +8928,14 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'relevancy_training_status' - ) and self.relevancy_training_status is not None: - _dict[ - 'relevancy_training_status'] = self.relevancy_training_status.to_dict( - ) + if hasattr(self, 'relevancy_training_status') and getattr( + self, 'relevancy_training_status') is not None: + if isinstance(getattr(self, 'relevancy_training_status'), dict): + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status') + else: + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status').to_dict() if hasattr(self, 'collection_count') and getattr( self, 'collection_count') is not None: _dict['collection_count'] = getattr(self, 'collection_count') @@ -4476,7 +8966,11 @@ class TypeEnum(str, Enum): and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. """ + + INTELLIGENT_DOCUMENT_PROCESSING = 'intelligent_document_processing' DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -4484,39 +8978,41 @@ class TypeEnum(str, Enum): OTHER = 'other' -class ProjectListDetailsRelevancyTrainingStatus(): +class ProjectListDetailsRelevancyTrainingStatus: """ Relevancy training status information for this project. - :attr str data_updated: (optional) When the training data was updated. - :attr int total_examples: (optional) The total number of examples. - :attr bool sufficient_label_diversity: (optional) When `true`, sufficient label + :param str data_updated: (optional) When the training data was updated. + :param int total_examples: (optional) The total number of examples. + :param bool sufficient_label_diversity: (optional) When `true`, sufficient label diversity is present to allow training for this project. - :attr bool processing: (optional) When `true`, the relevancy training is in + :param bool processing: (optional) When `true`, the relevancy training is in processing. - :attr bool minimum_examples_added: (optional) When `true`, the minimum number of - examples required to train has been met. - :attr str successfully_trained: (optional) The time that the most recent + :param bool minimum_examples_added: (optional) When `true`, the minimum number + of examples required to train has been met. + :param str successfully_trained: (optional) The time that the most recent successful training occurred. - :attr bool available: (optional) When `true`, relevancy training is available + :param bool available: (optional) When `true`, relevancy training is available when querying collections in the project. - :attr int notices: (optional) The number of notices generated during the + :param int notices: (optional) The number of notices generated during the relevancy training. - :attr bool minimum_queries_added: (optional) When `true`, the minimum number of + :param bool minimum_queries_added: (optional) When `true`, the minimum number of queries required to train has been met. """ - def __init__(self, - *, - data_updated: str = None, - total_examples: int = None, - sufficient_label_diversity: bool = None, - processing: bool = None, - minimum_examples_added: bool = None, - successfully_trained: str = None, - available: bool = None, - notices: int = None, - minimum_queries_added: bool = None) -> None: + def __init__( + self, + *, + data_updated: Optional[str] = None, + total_examples: Optional[int] = None, + sufficient_label_diversity: Optional[bool] = None, + processing: Optional[bool] = None, + minimum_examples_added: Optional[bool] = None, + successfully_trained: Optional[str] = None, + available: Optional[bool] = None, + notices: Optional[int] = None, + minimum_queries_added: Optional[bool] = None, + ) -> None: """ Initialize a ProjectListDetailsRelevancyTrainingStatus object. @@ -4552,25 +9048,28 @@ def from_dict(cls, _dict: Dict) -> 'ProjectListDetailsRelevancyTrainingStatus': """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" args = {} - if 'data_updated' in _dict: - args['data_updated'] = _dict.get('data_updated') - if 'total_examples' in _dict: - args['total_examples'] = _dict.get('total_examples') - if 'sufficient_label_diversity' in _dict: - args['sufficient_label_diversity'] = _dict.get( - 'sufficient_label_diversity') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'minimum_examples_added' in _dict: - args['minimum_examples_added'] = _dict.get('minimum_examples_added') - if 'successfully_trained' in _dict: - args['successfully_trained'] = _dict.get('successfully_trained') - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'notices' in _dict: - args['notices'] = _dict.get('notices') - if 'minimum_queries_added' in _dict: - args['minimum_queries_added'] = _dict.get('minimum_queries_added') + if (data_updated := _dict.get('data_updated')) is not None: + args['data_updated'] = data_updated + if (total_examples := _dict.get('total_examples')) is not None: + args['total_examples'] = total_examples + if (sufficient_label_diversity := + _dict.get('sufficient_label_diversity')) is not None: + args['sufficient_label_diversity'] = sufficient_label_diversity + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (minimum_examples_added := + _dict.get('minimum_examples_added')) is not None: + args['minimum_examples_added'] = minimum_examples_added + if (successfully_trained := + _dict.get('successfully_trained')) is not None: + args['successfully_trained'] = successfully_trained + if (available := _dict.get('available')) is not None: + args['available'] = available + if (notices := _dict.get('notices')) is not None: + args['notices'] = notices + if (minimum_queries_added := + _dict.get('minimum_queries_added')) is not None: + args['minimum_queries_added'] = minimum_queries_added return cls(**args) @classmethod @@ -4627,24 +9126,32 @@ def __ne__(self, return not self == other -class QueryAggregation(): +class QueryAggregation: """ - An abstract aggregation type produced by Discovery to analyze the input provided. + An object that defines how to aggregate query results. - :attr str type: The type of aggregation command used. Options include: term, - histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and - top_hits. """ - def __init__(self, type: str) -> None: + def __init__(self,) -> None: """ Initialize a QueryAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. """ - self.type = type + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) + raise Exception(msg) @classmethod def from_dict(cls, _dict: Dict) -> 'QueryAggregation': @@ -4652,60 +9159,45 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryAggregation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): + msg = "Cannot convert dictionary into an instance of base class 'QueryAggregation'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): """Initialize a QueryAggregation object from a json dictionary.""" return cls.from_dict(_dict) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} - mapping['term'] = 'QueryTermAggregation' - mapping['histogram'] = 'QueryHistogramAggregation' - mapping['timeslice'] = 'QueryTimesliceAggregation' - mapping['nested'] = 'QueryNestedAggregation' - mapping['filter'] = 'QueryFilterAggregation' - mapping['min'] = 'QueryCalculationAggregation' - mapping['max'] = 'QueryCalculationAggregation' - mapping['sum'] = 'QueryCalculationAggregation' - mapping['average'] = 'QueryCalculationAggregation' - mapping['unique_count'] = 'QueryCalculationAggregation' - mapping['top_hits'] = 'QueryTopHitsAggregation' - mapping['group_by'] = 'QueryGroupByAggregation' + mapping['term'] = 'QueryAggregationQueryTermAggregation' + mapping['group_by'] = 'QueryAggregationQueryGroupByAggregation' + mapping['histogram'] = 'QueryAggregationQueryHistogramAggregation' + mapping['timeslice'] = 'QueryAggregationQueryTimesliceAggregation' + mapping['nested'] = 'QueryAggregationQueryNestedAggregation' + mapping['filter'] = 'QueryAggregationQueryFilterAggregation' + mapping['min'] = 'QueryAggregationQueryCalculationAggregation' + mapping['max'] = 'QueryAggregationQueryCalculationAggregation' + mapping['sum'] = 'QueryAggregationQueryCalculationAggregation' + mapping['average'] = 'QueryAggregationQueryCalculationAggregation' + mapping['unique_count'] = 'QueryAggregationQueryCalculationAggregation' + mapping['top_hits'] = 'QueryAggregationQueryTopHitsAggregation' + mapping['pair'] = 'QueryAggregationQueryPairAggregation' + mapping['trend'] = 'QueryAggregationQueryTrendAggregation' + mapping['topic'] = 'QueryAggregationQueryTopicAggregation' disc_value = _dict.get('type') if disc_value is None: raise ValueError( @@ -4721,83 +9213,87 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class QueryGroupByAggregationResult(): +class QueryGroupByAggregationResult: """ - Top value result for the term aggregation. + Result group for the `group_by` aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this group. - :attr int total_matching_documents: (optional) The number of documents which - have the group as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str key: The condition that is met by the documents in this group. For + example, `YEARTXT<2000`. + :param int matching_results: Number of documents that meet the query and + condition. + :param float relevancy: (optional) The relevancy for this group. Returned only + if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents that meet + the condition in the whole set of documents in this collection. Returned only + when `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) The number of documents that + are estimated to match the query and condition. Returned only when + `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_results: Optional[float] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryGroupByAggregationResult object. - :param str key: Value of the field with a non-zero frequency in the - document set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this group. - :param int total_matching_documents: (optional) The number of documents - which have the group as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str key: The condition that is met by the documents in this group. + For example, `YEARTXT<2000`. + :param int matching_results: Number of documents that meet the query and + condition. + :param float relevancy: (optional) The relevancy for this group. Returned + only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents that + meet the condition in the whole set of documents in this collection. + Returned only when `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) The number of documents + that are estimated to match the query and condition. Returned only when + `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key = key self.matching_results = matching_results self.relevancy = relevancy self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents + self.estimated_matching_results = estimated_matching_results self.aggregations = aggregations @classmethod def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryGroupByAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryGroupByAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_results := + _dict.get('estimated_matching_results')) is not None: + args['estimated_matching_results'] = estimated_matching_results + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -4818,12 +9314,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'total_matching_documents' ) and self.total_matching_documents is not None: _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: + if hasattr(self, 'estimated_matching_results' + ) and self.estimated_matching_results is not None: _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents + 'estimated_matching_results'] = self.estimated_matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -4845,30 +9341,32 @@ def __ne__(self, other: 'QueryGroupByAggregationResult') -> bool: return not self == other -class QueryHistogramAggregationResult(): +class QueryHistogramAggregationResult: """ Histogram numeric interval result. - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: int, + matching_results: int, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryHistogramAggregationResult object. :param int key: The value of the upper bound for the numeric segment. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key = key self.matching_results = matching_results @@ -4878,22 +9376,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -4910,7 +9406,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -4932,28 +9428,30 @@ def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: return not self == other -class QueryLargePassages(): +class QueryLargePassages: """ Configuration for passage retrieval. - :attr bool enabled: (optional) A passages query that returns the most relevant + :param bool enabled: (optional) A passages query that returns the most relevant passages from the results. - :attr bool per_document: (optional) If `true`, ranks the documents by document + :param bool per_document: (optional) If `true`, ranks the documents by document quality, and then returns the highest-ranked passages per document in a `document_passages` field for each document entry in the results list of the response. If `false`, ranks the passages from all of the documents by passage quality regardless of the document quality and returns them in a separate `passages` field in the response. - :attr int max_per_document: (optional) Maximum number of passages to return per - document in the result. Ignored if `passages.per_document` is `false`. - :attr List[str] fields: (optional) A list of fields to extract passages from. If - this parameter is an empty list, then all root-level fields are included. - :attr int count: (optional) The maximum number of passages to return. Ignored if - `passages.per_document` is `true`. - :attr int characters: (optional) The approximate number of characters that any + :param int max_per_document: (optional) Maximum number of passages to return per + document in the result. Ignored if **passages.per_document** is `false`. + :param List[str] fields: (optional) A list of fields to extract passages from. + By default, passages are extracted from the `text` and `title` fields only. If + you add this parameter and specify an empty list (`[]`) as its value, then the + service searches all root-level fields for suitable passages. + :param int count: (optional) The maximum number of passages to return. Ignored + if **passages.per_document** is `true`. + :param int characters: (optional) The approximate number of characters that any one passage will have. - :attr bool find_answers: (optional) When true, `answer` objects are returned as + :param bool find_answers: (optional) When true, `answer` objects are returned as part of each passage in the query results. The primary difference between an `answer` and a `passage` is that the length of a passage is defined by the query, where the length of an `answer` is calculated by Discovery based on how @@ -4970,20 +9468,22 @@ class QueryLargePassages(): order of the highest confidence answer for each document and passage. The **find_answers** parameter is available only on managed instances of Discovery. - :attr int max_answers_per_passage: (optional) The number of `answer` objects to + :param int max_answers_per_passage: (optional) The number of `answer` objects to return per passage if the **find_answers** parmeter is specified as `true`. """ - def __init__(self, - *, - enabled: bool = None, - per_document: bool = None, - max_per_document: int = None, - fields: List[str] = None, - count: int = None, - characters: int = None, - find_answers: bool = None, - max_answers_per_passage: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + per_document: Optional[bool] = None, + max_per_document: Optional[int] = None, + fields: Optional[List[str]] = None, + count: Optional[int] = None, + characters: Optional[int] = None, + find_answers: Optional[bool] = None, + max_answers_per_passage: Optional[int] = None, + ) -> None: """ Initialize a QueryLargePassages object. @@ -4997,13 +9497,15 @@ def __init__(self, regardless of the document quality and returns them in a separate `passages` field in the response. :param int max_per_document: (optional) Maximum number of passages to - return per document in the result. Ignored if `passages.per_document` is + return per document in the result. Ignored if **passages.per_document** is `false`. :param List[str] fields: (optional) A list of fields to extract passages - from. If this parameter is an empty list, then all root-level fields are - included. + from. By default, passages are extracted from the `text` and `title` fields + only. If you add this parameter and specify an empty list (`[]`) as its + value, then the service searches all root-level fields for suitable + passages. :param int count: (optional) The maximum number of passages to return. - Ignored if `passages.per_document` is `true`. + Ignored if **passages.per_document** is `true`. :param int characters: (optional) The approximate number of characters that any one passage will have. :param bool find_answers: (optional) When true, `answer` objects are @@ -5042,23 +9544,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': """Initialize a QueryLargePassages object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'find_answers' in _dict: - args['find_answers'] = _dict.get('find_answers') - if 'max_answers_per_passage' in _dict: - args['max_answers_per_passage'] = _dict.get( - 'max_answers_per_passage') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document + if (max_per_document := _dict.get('max_per_document')) is not None: + args['max_per_document'] = max_per_document + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + if (count := _dict.get('count')) is not None: + args['count'] = count + if (characters := _dict.get('characters')) is not None: + args['characters'] = characters + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (max_answers_per_passage := + _dict.get('max_answers_per_passage')) is not None: + args['max_answers_per_passage'] = max_answers_per_passage return cls(**args) @classmethod @@ -5108,16 +9610,108 @@ def __ne__(self, other: 'QueryLargePassages') -> bool: return not self == other -class QueryLargeSuggestedRefinements(): +class QueryLargeSimilar: + """ + Finds results from documents that are similar to documents of interest. Use this + parameter to add a *More like these* function to your search. You can include this + parameter with or without a **query**, **filter** or **natural_language_query** + parameter. + + :param bool enabled: (optional) When `true`, includes documents in the query + results that are similar to documents you specify. + :param List[str] document_ids: (optional) The list of documents of interest. + Required if **enabled** is `true`. + :param List[str] fields: (optional) Looks for similarities in the specified + subset of fields in the documents. If not specified, all of the document fields + are used. + """ + + def __init__( + self, + *, + enabled: Optional[bool] = None, + document_ids: Optional[List[str]] = None, + fields: Optional[List[str]] = None, + ) -> None: + """ + Initialize a QueryLargeSimilar object. + + :param bool enabled: (optional) When `true`, includes documents in the + query results that are similar to documents you specify. + :param List[str] document_ids: (optional) The list of documents of + interest. Required if **enabled** is `true`. + :param List[str] fields: (optional) Looks for similarities in the specified + subset of fields in the documents. If not specified, all of the document + fields are used. + """ + self.enabled = enabled + self.document_ids = document_ids + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryLargeSimilar': + """Initialize a QueryLargeSimilar object from a json dictionary.""" + args = {} + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (document_ids := _dict.get('document_ids')) is not None: + args['document_ids'] = document_ids + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeSimilar object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'document_ids') and self.document_ids is not None: + _dict['document_ids'] = self.document_ids + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryLargeSimilar object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryLargeSimilar') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryLargeSimilar') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryLargeSuggestedRefinements: """ - Configuration for suggested refinements. Available with Premium plans only. + Configuration for suggested refinements. + **Note**: The **suggested_refinements** parameter that identified dynamic facets from + the data is deprecated. - :attr bool enabled: (optional) Whether to perform suggested refinements. - :attr int count: (optional) Maximum number of suggested refinements texts to be + :param bool enabled: (optional) Whether to perform suggested refinements. + :param int count: (optional) Maximum number of suggested refinements texts to be returned. The maximum is `100`. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a QueryLargeSuggestedRefinements object. @@ -5132,10 +9726,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeSuggestedRefinements': """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -5171,15 +9765,20 @@ def __ne__(self, other: 'QueryLargeSuggestedRefinements') -> bool: return not self == other -class QueryLargeTableResults(): +class QueryLargeTableResults: """ Configuration for table retrieval. - :attr bool enabled: (optional) Whether to enable table retrieval. - :attr int count: (optional) Maximum number of tables to return. + :param bool enabled: (optional) Whether to enable table retrieval. + :param int count: (optional) Maximum number of tables to return. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a QueryLargeTableResults object. @@ -5193,10 +9792,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeTableResults': """Initialize a QueryLargeTableResults object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -5232,19 +9831,21 @@ def __ne__(self, other: 'QueryLargeTableResults') -> bool: return not self == other -class QueryNoticesResponse(): +class QueryNoticesResponse: """ Object that contains notice query results. - :attr int matching_results: (optional) The number of matching results. - :attr List[Notice] notices: (optional) Array of document results that match the + :param int matching_results: (optional) The number of matching results. + :param List[Notice] notices: (optional) Array of document results that match the query. """ - def __init__(self, - *, - matching_results: int = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a QueryNoticesResponse object. @@ -5259,12 +9860,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -5279,7 +9878,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -5301,37 +9906,107 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other -class QueryResponse(): +class QueryPairAggregationResult: + """ + Result for the `pair` aggregation. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix that + is returned contains a **relevancy** value that is calculated from the + combination of each value from the first and second aggregations. + """ + + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: + """ + Initialize a QueryPairAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix + that is returned contains a **relevancy** value that is calculated from the + combination of each value from the first and second aggregations. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryPairAggregationResult': + """Initialize a QueryPairAggregationResult object from a json dictionary.""" + args = {} + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryPairAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryPairAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryPairAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryPairAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryResponse: """ A response that contains the documents and aggregations for the query. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the query. Results that match due to a curation only are not counted in the total. - :attr List[QueryResult] results: (optional) Array of document results for the + :param List[QueryResult] results: (optional) Array of document results for the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregations for + :param List[QueryAggregation] aggregations: (optional) Array of aggregations for the query. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. - :attr str suggested_query: (optional) Suggested correction to the submitted + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. + :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of - suggested refinements. - :attr List[QueryTableResult] table_results: (optional) Array of table results. - :attr List[QueryResponsePassage] passages: (optional) Passages that best match - the query from across all of the collections in the project. - """ - - def __init__(self, - *, - matching_results: int = None, - results: List['QueryResult'] = None, - aggregations: List['QueryAggregation'] = None, - retrieval_details: 'RetrievalDetails' = None, - suggested_query: str = None, - suggested_refinements: List['QuerySuggestedRefinement'] = None, - table_results: List['QueryTableResult'] = None, - passages: List['QueryResponsePassage'] = None) -> None: + :param List[QuerySuggestedRefinement] suggested_refinements: (optional) + Deprecated: Array of suggested refinements. **Note**: The + `suggested_refinements` parameter that identified dynamic facets from the data + is deprecated. + :param List[QueryTableResult] table_results: (optional) Array of table results. + :param List[QueryResponsePassage] passages: (optional) Passages that best match + the query from across all of the collections in the project. Returned if + **passages.per_document** is `false`. + """ + + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + retrieval_details: Optional['RetrievalDetails'] = None, + suggested_query: Optional[str] = None, + suggested_refinements: Optional[ + List['QuerySuggestedRefinement']] = None, + table_results: Optional[List['QueryTableResult']] = None, + passages: Optional[List['QueryResponsePassage']] = None, + ) -> None: """ Initialize a QueryResponse object. @@ -5347,11 +10022,14 @@ def __init__(self, :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. :param List[QuerySuggestedRefinement] suggested_refinements: (optional) - Array of suggested refinements. + Deprecated: Array of suggested refinements. **Note**: The + `suggested_refinements` parameter that identified dynamic facets from the + data is deprecated. :param List[QueryTableResult] table_results: (optional) Array of table results. :param List[QueryResponsePassage] passages: (optional) Passages that best - match the query from across all of the collections in the project. + match the query from across all of the collections in the project. Returned + if **passages.per_document** is `false`. """ self.matching_results = matching_results self.results = results @@ -5366,34 +10044,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryResult.from_dict(x) for x in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'retrieval_details' in _dict: + if (retrieval_details := _dict.get('retrieval_details')) is not None: args['retrieval_details'] = RetrievalDetails.from_dict( - _dict.get('retrieval_details')) - if 'suggested_query' in _dict: - args['suggested_query'] = _dict.get('suggested_query') - if 'suggested_refinements' in _dict: + retrieval_details) + if (suggested_query := _dict.get('suggested_query')) is not None: + args['suggested_query'] = suggested_query + if (suggested_refinements := + _dict.get('suggested_refinements')) is not None: args['suggested_refinements'] = [ - QuerySuggestedRefinement.from_dict(x) - for x in _dict.get('suggested_refinements') + QuerySuggestedRefinement.from_dict(v) + for v in suggested_refinements ] - if 'table_results' in _dict: + if (table_results := _dict.get('table_results')) is not None: args['table_results'] = [ - QueryTableResult.from_dict(x) - for x in _dict.get('table_results') + QueryTableResult.from_dict(v) for v in table_results ] - if 'passages' in _dict: + if (passages := _dict.get('passages')) is not None: args['passages'] = [ - QueryResponsePassage.from_dict(x) for x in _dict.get('passages') + QueryResponsePassage.from_dict(v) for v in passages ] return cls(**args) @@ -5409,24 +10085,55 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details.to_dict() + if isinstance(self.retrieval_details, dict): + _dict['retrieval_details'] = self.retrieval_details + else: + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query if hasattr(self, 'suggested_refinements' ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = [ - x.to_dict() for x in self.suggested_refinements - ] + suggested_refinements_list = [] + for v in self.suggested_refinements: + if isinstance(v, dict): + suggested_refinements_list.append(v) + else: + suggested_refinements_list.append(v.to_dict()) + _dict['suggested_refinements'] = suggested_refinements_list if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = [x.to_dict() for x in self.table_results] + table_results_list = [] + for v in self.table_results: + if isinstance(v, dict): + table_results_list.append(v) + else: + table_results_list.append(v.to_dict()) + _dict['table_results'] = table_results_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list return _dict def _to_dict(self): @@ -5448,45 +10155,49 @@ def __ne__(self, other: 'QueryResponse') -> bool: return not self == other -class QueryResponsePassage(): +class QueryResponsePassage: """ A passage query response. - :attr str passage_text: (optional) The content of the extracted passage. - :attr float passage_score: (optional) The confidence score of the passage's - analysis. A higher score indicates greater confidence. - :attr str document_id: (optional) The unique identifier of the ingested + :param str passage_text: (optional) The content of the extracted passage. + :param float passage_score: (optional) The confidence score of the passage's + analysis. A higher score indicates greater confidence. The score is used to rank + the passages from all documents and is returned only if + **passages.per_document** is `false`. + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr int start_offset: (optional) The position of the first character of the + :param str collection_id: (optional) The unique identifier of the collection. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. - :attr float confidence: (optional) An estimate of the probability that the - passage is relevant. - :attr List[ResultPassageAnswer] answers: (optional) An array of extracted - answers to the specified query. - """ - - def __init__(self, - *, - passage_text: str = None, - passage_score: float = None, - document_id: str = None, - collection_id: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None, - confidence: float = None, - answers: List['ResultPassageAnswer'] = None) -> None: + :param List[ResultPassageAnswer] answers: (optional) An array of extracted + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `false`. + """ + + def __init__( + self, + *, + passage_text: Optional[str] = None, + passage_score: Optional[float] = None, + document_id: Optional[str] = None, + collection_id: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + answers: Optional[List['ResultPassageAnswer']] = None, + ) -> None: """ Initialize a QueryResponsePassage object. :param str passage_text: (optional) The content of the extracted passage. :param float passage_score: (optional) The confidence score of the - passage's analysis. A higher score indicates greater confidence. + passage's analysis. A higher score indicates greater confidence. The score + is used to rank the passages from all documents and is returned only if + **passages.per_document** is `false`. :param str document_id: (optional) The unique identifier of the ingested document. :param str collection_id: (optional) The unique identifier of the @@ -5497,10 +10208,9 @@ def __init__(self, the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. - :param float confidence: (optional) An estimate of the probability that the - passage is relevant. :param List[ResultPassageAnswer] answers: (optional) An array of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `false`. """ self.passage_text = passage_text self.passage_score = passage_score @@ -5509,32 +10219,29 @@ def __init__(self, self.start_offset = start_offset self.end_offset = end_offset self.field = field - self.confidence = confidence self.answers = answers @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': """Initialize a QueryResponsePassage object from a json dictionary.""" args = {} - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'answers' in _dict: + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (passage_score := _dict.get('passage_score')) is not None: + args['passage_score'] = passage_score + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field + if (answers := _dict.get('answers')) is not None: args['answers'] = [ - ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in answers ] return cls(**args) @@ -5560,10 +10267,14 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -5585,28 +10296,34 @@ def __ne__(self, other: 'QueryResponsePassage') -> bool: return not self == other -class QueryResult(): +class QueryResult: """ Result document for the specified query. - :attr str document_id: The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr QueryResultMetadata result_metadata: Metadata of a query result. - :attr List[QueryResultPassage] document_passages: (optional) Passages from the - document that best matches the query. + :param str document_id: The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param QueryResultMetadata result_metadata: Metadata of a query result. + :param List[QueryResultPassage] document_passages: (optional) Passages from the + document that best matches the query. Returned if **passages.per_document** is + `true`. + + This type supports additional properties of type object. The remaining key-value + pairs. """ # The set of defined properties for the class _properties = frozenset( ['document_id', 'metadata', 'result_metadata', 'document_passages']) - def __init__(self, - document_id: str, - result_metadata: 'QueryResultMetadata', - *, - metadata: dict = None, - document_passages: List['QueryResultPassage'] = None, - **kwargs) -> None: + def __init__( + self, + document_id: str, + result_metadata: 'QueryResultMetadata', + *, + metadata: Optional[dict] = None, + document_passages: Optional[List['QueryResultPassage']] = None, + **kwargs: Optional[object], + ) -> None: """ Initialize a QueryResult object. @@ -5614,42 +10331,56 @@ def __init__(self, :param QueryResultMetadata result_metadata: Metadata of a query result. :param dict metadata: (optional) Metadata of the document. :param List[QueryResultPassage] document_passages: (optional) Passages from - the document that best matches the query. - :param **kwargs: (optional) Any additional properties. + the document that best matches the query. Returned if + **passages.per_document** is `true`. + :param object **kwargs: (optional) The remaining key-value pairs. """ self.document_id = document_id self.metadata = metadata self.result_metadata = result_metadata self.document_passages = document_passages - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in QueryResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in QueryResult JSON' ) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'result_metadata' in _dict: + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) else: raise ValueError( 'Required property \'result_metadata\' not present in QueryResult JSON' ) - if 'document_passages' in _dict: + if (document_passages := _dict.get('document_passages')) is not None: args['document_passages'] = [ - QueryResultPassage.from_dict(x) - for x in _dict.get('document_passages') + QueryResultPassage.from_dict(v) for v in document_passages ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -5666,17 +10397,24 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'document_passages') and self.document_passages is not None: - _dict['document_passages'] = [ - x.to_dict() for x in self.document_passages - ] - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + document_passages_list = [] + for v in self.document_passages: + if isinstance(v, dict): + document_passages_list.append(v) + else: + document_passages_list.append(v.to_dict()) + _dict['document_passages'] = document_passages_list + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -5684,25 +10422,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryResult""" + """Return the additional properties from this instance of QueryResult in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryResult""" - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + """Set a dictionary of additional properties in this instance of QueryResult""" + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryResult._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in QueryResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" @@ -5719,28 +10465,30 @@ def __ne__(self, other: 'QueryResult') -> bool: return not self == other -class QueryResultMetadata(): +class QueryResultMetadata: """ Metadata of a query result. - :attr str document_retrieval_source: (optional) The document retrieval source + :param str document_retrieval_source: (optional) The document retrieval source that produced this search result. - :attr str collection_id: The collection id associated with this training data + :param str collection_id: The collection id associated with this training data set. - :attr float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can + :param float confidence: (optional) The confidence score for the given result. + Calculated based on how relevant the result is estimated to be. The score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. This - field is only returned if the **natural_language_query** parameter is specified + field is returned only if the **natural_language_query** parameter is specified in the query. """ - def __init__(self, - collection_id: str, - *, - document_retrieval_source: str = None, - confidence: float = None) -> None: + def __init__( + self, + collection_id: str, + *, + document_retrieval_source: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a QueryResultMetadata object. @@ -5749,11 +10497,11 @@ def __init__(self, :param str document_retrieval_source: (optional) The document retrieval source that produced this search result. :param float confidence: (optional) The confidence score for the given - result. Calculated based on how relevant the result is estimated to be. - confidence can range from `0.0` to `1.0`. The higher the number, the more + result. Calculated based on how relevant the result is estimated to be. The + score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the - result set. This field is only returned if the **natural_language_query** + result set. This field is returned only if the **natural_language_query** parameter is specified in the query. """ self.document_retrieval_source = document_retrieval_source @@ -5764,17 +10512,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - if 'document_retrieval_source' in _dict: - args['document_retrieval_source'] = _dict.get( - 'document_retrieval_source') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (document_retrieval_source := + _dict.get('document_retrieval_source')) is not None: + args['document_retrieval_source'] = document_retrieval_source + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in QueryResultMetadata JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -5816,35 +10564,36 @@ class DocumentRetrievalSourceEnum(str, Enum): """ The document retrieval source that produced this search result. """ + SEARCH = 'search' CURATION = 'curation' -class QueryResultPassage(): +class QueryResultPassage: """ A passage query result. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. - :attr float confidence: (optional) Estimate of the probability that the passage - is relevant. - :attr List[ResultPassageAnswer] answers: (optional) An arry of extracted answers - to the specified query. + :param List[ResultPassageAnswer] answers: (optional) An arry of extracted + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `true`. """ - def __init__(self, - *, - passage_text: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None, - confidence: float = None, - answers: List['ResultPassageAnswer'] = None) -> None: + def __init__( + self, + *, + passage_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + answers: Optional[List['ResultPassageAnswer']] = None, + ) -> None: """ Initialize a QueryResultPassage object. @@ -5855,35 +10604,31 @@ def __init__(self, the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. - :param float confidence: (optional) Estimate of the probability that the - passage is relevant. :param List[ResultPassageAnswer] answers: (optional) An arry of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `true`. """ self.passage_text = passage_text self.start_offset = start_offset self.end_offset = end_offset self.field = field - self.confidence = confidence self.answers = answers @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': """Initialize a QueryResultPassage object from a json dictionary.""" args = {} - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'answers' in _dict: + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field + if (answers := _dict.get('answers')) is not None: args['answers'] = [ - ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in answers ] return cls(**args) @@ -5903,10 +10648,14 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -5928,14 +10677,19 @@ def __ne__(self, other: 'QueryResultPassage') -> bool: return not self == other -class QuerySuggestedRefinement(): +class QuerySuggestedRefinement: """ - A suggested additional query term or terms user to filter results. + A suggested additional query term or terms user to filter results. **Note**: The + `suggested_refinements` parameter is deprecated. - :attr str text: (optional) The text used to filter. + :param str text: (optional) The text used to filter. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a QuerySuggestedRefinement object. @@ -5947,8 +10701,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'QuerySuggestedRefinement': """Initialize a QuerySuggestedRefinement object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -5982,30 +10736,32 @@ def __ne__(self, other: 'QuerySuggestedRefinement') -> bool: return not self == other -class QueryTableResult(): +class QueryTableResult: """ A tables whose content or context match a search query. - :attr str table_id: (optional) The identifier for the retrieved table. - :attr str source_document_id: (optional) The identifier of the document the + :param str table_id: (optional) The identifier for the retrieved table. + :param str source_document_id: (optional) The identifier of the document the table was retrieved from. - :attr str collection_id: (optional) The identifier of the collection the table + :param str collection_id: (optional) The identifier of the collection the table was retrieved from. - :attr str table_html: (optional) HTML snippet of the table info. - :attr int table_html_offset: (optional) The offset of the table html snippet in + :param str table_html: (optional) HTML snippet of the table info. + :param int table_html_offset: (optional) The offset of the table html snippet in the original document html. - :attr TableResultTable table: (optional) Full table object retrieved from Table + :param TableResultTable table: (optional) Full table object retrieved from Table Understanding Enrichment. """ - def __init__(self, - *, - table_id: str = None, - source_document_id: str = None, - collection_id: str = None, - table_html: str = None, - table_html_offset: int = None, - table: 'TableResultTable' = None) -> None: + def __init__( + self, + *, + table_id: Optional[str] = None, + source_document_id: Optional[str] = None, + collection_id: Optional[str] = None, + table_html: Optional[str] = None, + table_html_offset: Optional[int] = None, + table: Optional['TableResultTable'] = None, + ) -> None: """ Initialize a QueryTableResult object. @@ -6031,18 +10787,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTableResult': """Initialize a QueryTableResult object from a json dictionary.""" args = {} - if 'table_id' in _dict: - args['table_id'] = _dict.get('table_id') - if 'source_document_id' in _dict: - args['source_document_id'] = _dict.get('source_document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'table_html' in _dict: - args['table_html'] = _dict.get('table_html') - if 'table_html_offset' in _dict: - args['table_html_offset'] = _dict.get('table_html_offset') - if 'table' in _dict: - args['table'] = TableResultTable.from_dict(_dict.get('table')) + if (table_id := _dict.get('table_id')) is not None: + args['table_id'] = table_id + if (source_document_id := _dict.get('source_document_id')) is not None: + args['source_document_id'] = source_document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (table_html := _dict.get('table_html')) is not None: + args['table_html'] = table_html + if (table_html_offset := _dict.get('table_html_offset')) is not None: + args['table_html_offset'] = table_html_offset + if (table := _dict.get('table')) is not None: + args['table'] = TableResultTable.from_dict(table) return cls(**args) @classmethod @@ -6067,7 +10823,10 @@ def to_dict(self) -> Dict: 'table_html_offset') and self.table_html_offset is not None: _dict['table_html_offset'] = self.table_html_offset if hasattr(self, 'table') and self.table is not None: - _dict['table'] = self.table.to_dict() + if isinstance(self.table, dict): + _dict['table'] = self.table + else: + _dict['table'] = self.table.to_dict() return _dict def _to_dict(self): @@ -6089,83 +10848,86 @@ def __ne__(self, other: 'QueryTableResult') -> bool: return not self == other -class QueryTermAggregationResult(): +class QueryTermAggregationResult: """ - Top value result for the term aggregation. + Top value result for the `term` aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this term. - :attr int total_matching_documents: (optional) The number of documents which - have the term as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str key: Value of the field with a nonzero frequency in the document set. + :param int matching_results: Number of documents that contain the 'key'. + :param float relevancy: (optional) The relevancy score for this result. Returned + only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents in the + collection that contain the term in the specified field. Returned only when + `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) Number of documents that are + estimated to match the query and also meet the condition. Returned only when + `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is combined with other aggregations in the request or + is returned as a subaggregation. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_results: Optional[float] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTermAggregationResult object. - :param str key: Value of the field with a non-zero frequency in the - document set. + :param str key: Value of the field with a nonzero frequency in the document + set. :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents - which have the term as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param float relevancy: (optional) The relevancy score for this result. + Returned only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents in the + collection that contain the term in the specified field. Returned only when + `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) Number of documents + that are estimated to match the query and also meet the condition. Returned + only when `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is combined with other aggregations in + the request or is returned as a subaggregation. """ self.key = key self.matching_results = matching_results self.relevancy = relevancy self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents + self.estimated_matching_results = estimated_matching_results self.aggregations = aggregations @classmethod def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTermAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_results := + _dict.get('estimated_matching_results')) is not None: + args['estimated_matching_results'] = estimated_matching_results + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -6186,12 +10948,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'total_matching_documents' ) and self.total_matching_documents is not None: _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: + if hasattr(self, 'estimated_matching_results' + ) and self.estimated_matching_results is not None: _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents + 'estimated_matching_results'] = self.estimated_matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -6213,26 +10975,28 @@ def __ne__(self, other: 'QueryTermAggregationResult') -> bool: return not self == other -class QueryTimesliceAggregationResult(): +class QueryTimesliceAggregationResult: """ A timeslice interval segment. - :attr str key_as_string: String date value of the upper bound for the timeslice + :param str key_as_string: String date value of the upper bound for the timeslice interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval + :param int key: Numeric date value of the upper bound for the timeslice interval in UNIX milliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTimesliceAggregationResult object. @@ -6242,8 +11006,8 @@ def __init__(self, interval in UNIX milliseconds since epoch. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key_as_string = key_as_string self.key = key @@ -6254,47 +11018,182 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = _dict.get('key_as_string') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = key_as_string else: raise ValueError( 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' ) - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'key_as_string') and self.key_as_string is not None: + _dict['key_as_string'] = self.key_as_string + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryTimesliceAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTimesliceAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopHitsAggregationResult: + """ + A query response that contains the matching documents for the preceding aggregations. + + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results in an + ordered list. + """ + + def __init__( + self, + matching_results: int, + *, + hits: Optional[List[dict]] = None, + ) -> None: + """ + Initialize a QueryTopHitsAggregationResult object. + + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results in an + ordered list. + """ + self.matching_results = matching_results + self.hits = hits + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': + """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" + args = {} + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' + ) + if (hits := _dict.get('hits')) is not None: + args['hits'] = hits + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryTopHitsAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTopHitsAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopicAggregationResult: + """ + Result for the `topic` aggregation. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **topic_indicator** that is calculated from the combination + of each aggregation value and segment of time. + """ + + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: + """ + Initialize a QueryTopicAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of + type `term` or `group_by` and `timeslice`. Each element of the matrix that + is returned contains a **topic_indicator** that is calculated from the + combination of each aggregation value and segment of time. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopicAggregationResult': + """Initialize a QueryTopicAggregationResult object from a json dictionary.""" + args = {} + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" + """Initialize a QueryTopicAggregationResult object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'key_as_string') and self.key_as_string is not None: - _dict['key_as_string'] = self.key_as_string - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -6302,68 +11201,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregationResult object.""" + """Return a `str` version of this QueryTopicAggregationResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTimesliceAggregationResult') -> bool: + def __eq__(self, other: 'QueryTopicAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: + def __ne__(self, other: 'QueryTopicAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTopHitsAggregationResult(): +class QueryTrendAggregationResult: """ - A query response that contains the matching documents for the preceding aggregations. + Result for the `trend` aggregation. - :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results. + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **trend_indicator** that is calculated from the combination + of each aggregation value and segment of time. """ - def __init__(self, - matching_results: int, - *, - hits: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ - Initialize a QueryTopHitsAggregationResult object. + Initialize a QueryTrendAggregationResult object. - :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **trend_indicator** that is calculated from the + combination of each aggregation value and segment of time. """ - self.matching_results = matching_results - self.hits = hits + self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': - """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryTrendAggregationResult': + """Initialize a QueryTrendAggregationResult object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' - ) - if 'hits' in _dict: - args['hits'] = _dict.get('hits') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" + """Initialize a QueryTrendAggregationResult object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -6371,40 +11265,42 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTopHitsAggregationResult object.""" + """Return a `str` version of this QueryTrendAggregationResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTopHitsAggregationResult') -> bool: + def __eq__(self, other: 'QueryTrendAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: + def __ne__(self, other: 'QueryTrendAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ResultPassageAnswer(): +class ResultPassageAnswer: """ Object that contains a potential answer to the specified query. - :attr str answer_text: (optional) Answer text for the specified query as + :param str answer_text: (optional) Answer text for the specified query as identified by Discovery. - :attr int start_offset: (optional) The position of the first character of the + :param int start_offset: (optional) The position of the first character of the extracted answer in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted answer in the originating field. - :attr float confidence: (optional) An estimate of the probability that the + :param float confidence: (optional) An estimate of the probability that the answer is relevant. """ - def __init__(self, - *, - answer_text: str = None, - start_offset: int = None, - end_offset: int = None, - confidence: float = None) -> None: + def __init__( + self, + *, + answer_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a ResultPassageAnswer object. @@ -6426,14 +11322,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ResultPassageAnswer': """Initialize a ResultPassageAnswer object from a json dictionary.""" args = {} - if 'answer_text' in _dict: - args['answer_text'] = _dict.get('answer_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (answer_text := _dict.get('answer_text')) is not None: + args['answer_text'] = answer_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -6473,11 +11369,11 @@ def __ne__(self, other: 'ResultPassageAnswer') -> bool: return not self == other -class RetrievalDetails(): +class RetrievalDetails: """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Identifies the document + :param str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. **Note**: In the event of trained collections being queried, but the trained @@ -6485,7 +11381,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy: str = None) -> None: + def __init__( + self, + *, + document_retrieval_strategy: Optional[str] = None, + ) -> None: """ Initialize a RetrievalDetails object. @@ -6502,9 +11402,9 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') + if (document_retrieval_strategy := + _dict.get('document_retrieval_strategy')) is not None: + args['document_retrieval_strategy'] = document_retrieval_strategy return cls(**args) @classmethod @@ -6548,62 +11448,124 @@ class DocumentRetrievalStrategyEnum(str, Enum): is not used to return results, the **document_retrieval_strategy** is listed as `untrained`. """ + UNTRAINED = 'untrained' RELEVANCY_TRAINING = 'relevancy_training' -class TableBodyCells(): +class StopWordList: + """ + List of words to filter out of text that is submitted in queries. + + :param List[str] stopwords: List of stop words. + """ + + def __init__( + self, + stopwords: List[str], + ) -> None: + """ + Initialize a StopWordList object. + + :param List[str] stopwords: List of stop words. + """ + self.stopwords = stopwords + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StopWordList': + """Initialize a StopWordList object from a json dictionary.""" + args = {} + if (stopwords := _dict.get('stopwords')) is not None: + args['stopwords'] = stopwords + else: + raise ValueError( + 'Required property \'stopwords\' not present in StopWordList JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StopWordList object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'stopwords') and self.stopwords is not None: + _dict['stopwords'] = self.stopwords + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StopWordList object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StopWordList') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StopWordList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableBodyCells: """ Cells that are not table header, column header, or row header cells. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :attr List[TableRowHeaderIds] row_header_ids: (optional) A list of table row - header ids. - :attr List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row - header texts. - :attr List[TableRowHeaderTextsNormalized] row_header_texts_normalized: - (optional) A list of table row header texts normalized. - :attr List[TableColumnHeaderIds] column_header_ids: (optional) A list of table - column header ids. - :attr List[TableColumnHeaderTexts] column_header_texts: (optional) A list of - table column header texts. - :attr List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: - (optional) A list of table column header texts normalized. - :attr List[DocumentAttribute] attributes: (optional) A list of document + :param List[str] row_header_ids: (optional) A list of ID values that represent + the table row headers that are associated with this body cell. + :param List[str] row_header_texts: (optional) A list of row header values that + are associated with this body cell. + :param List[str] row_header_texts_normalized: (optional) A list of normalized + row header values that are associated with this body cell. + :param List[str] column_header_ids: (optional) A list of ID values that + represent the column headers that are associated with this body cell. + :param List[str] column_header_texts: (optional) A list of column header values + that are associated with this body cell. + :param List[str] column_header_texts_normalized: (optional) A list of normalized + column header values that are associated with this body cell. + :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None, - row_header_ids: List['TableRowHeaderIds'] = None, - row_header_texts: List['TableRowHeaderTexts'] = None, - row_header_texts_normalized: List[ - 'TableRowHeaderTextsNormalized'] = None, - column_header_ids: List['TableColumnHeaderIds'] = None, - column_header_texts: List['TableColumnHeaderTexts'] = None, - column_header_texts_normalized: List[ - 'TableColumnHeaderTextsNormalized'] = None, - attributes: List['DocumentAttribute'] = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + row_header_ids: Optional[List[str]] = None, + row_header_texts: Optional[List[str]] = None, + row_header_texts_normalized: Optional[List[str]] = None, + column_header_ids: Optional[List[str]] = None, + column_header_texts: Optional[List[str]] = None, + column_header_texts_normalized: Optional[List[str]] = None, + attributes: Optional[List['DocumentAttribute']] = None, + ) -> None: """ Initialize a TableBodyCells object. @@ -6622,19 +11584,18 @@ def __init__(self, `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table - row header ids. - :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of - table row header texts. - :param List[TableRowHeaderTextsNormalized] row_header_texts_normalized: - (optional) A list of table row header texts normalized. - :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of - table column header ids. - :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list - of table column header texts. - :param List[TableColumnHeaderTextsNormalized] - column_header_texts_normalized: (optional) A list of table column header - texts normalized. + :param List[str] row_header_ids: (optional) A list of ID values that + represent the table row headers that are associated with this body cell. + :param List[str] row_header_texts: (optional) A list of row header values + that are associated with this body cell. + :param List[str] row_header_texts_normalized: (optional) A list of + normalized row header values that are associated with this body cell. + :param List[str] column_header_ids: (optional) A list of ID values that + represent the column headers that are associated with this body cell. + :param List[str] column_header_texts: (optional) A list of column header + values that are associated with this body cell. + :param List[str] column_header_texts_normalized: (optional) A list of + normalized column header values that are associated with this body cell. :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ @@ -6657,54 +11618,39 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableBodyCells': """Initialize a TableBodyCells object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - if 'row_header_ids' in _dict: - args['row_header_ids'] = [ - TableRowHeaderIds.from_dict(x) - for x in _dict.get('row_header_ids') - ] - if 'row_header_texts' in _dict: - args['row_header_texts'] = [ - TableRowHeaderTexts.from_dict(x) - for x in _dict.get('row_header_texts') - ] - if 'row_header_texts_normalized' in _dict: - args['row_header_texts_normalized'] = [ - TableRowHeaderTextsNormalized.from_dict(x) - for x in _dict.get('row_header_texts_normalized') - ] - if 'column_header_ids' in _dict: - args['column_header_ids'] = [ - TableColumnHeaderIds.from_dict(x) - for x in _dict.get('column_header_ids') - ] - if 'column_header_texts' in _dict: - args['column_header_texts'] = [ - TableColumnHeaderTexts.from_dict(x) - for x in _dict.get('column_header_texts') - ] - if 'column_header_texts_normalized' in _dict: - args['column_header_texts_normalized'] = [ - TableColumnHeaderTextsNormalized.from_dict(x) - for x in _dict.get('column_header_texts_normalized') - ] - if 'attributes' in _dict: + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end + if (row_header_ids := _dict.get('row_header_ids')) is not None: + args['row_header_ids'] = row_header_ids + if (row_header_texts := _dict.get('row_header_texts')) is not None: + args['row_header_texts'] = row_header_texts + if (row_header_texts_normalized := + _dict.get('row_header_texts_normalized')) is not None: + args['row_header_texts_normalized'] = row_header_texts_normalized + if (column_header_ids := _dict.get('column_header_ids')) is not None: + args['column_header_ids'] = column_header_ids + if (column_header_texts := + _dict.get('column_header_texts')) is not None: + args['column_header_texts'] = column_header_texts + if (column_header_texts_normalized := + _dict.get('column_header_texts_normalized')) is not None: + args[ + 'column_header_texts_normalized'] = column_header_texts_normalized + if (attributes := _dict.get('attributes')) is not None: args['attributes'] = [ - DocumentAttribute.from_dict(x) for x in _dict.get('attributes') + DocumentAttribute.from_dict(v) for v in attributes ] return cls(**args) @@ -6719,7 +11665,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -6735,35 +11684,33 @@ def to_dict(self) -> Dict: 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - _dict['row_header_ids'] = [x.to_dict() for x in self.row_header_ids] + _dict['row_header_ids'] = self.row_header_ids if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: - _dict['row_header_texts'] = [ - x.to_dict() for x in self.row_header_texts - ] + _dict['row_header_texts'] = self.row_header_texts if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: - _dict['row_header_texts_normalized'] = [ - x.to_dict() for x in self.row_header_texts_normalized - ] + _dict[ + 'row_header_texts_normalized'] = self.row_header_texts_normalized if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: - _dict['column_header_ids'] = [ - x.to_dict() for x in self.column_header_ids - ] + _dict['column_header_ids'] = self.column_header_ids if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: - _dict['column_header_texts'] = [ - x.to_dict() for x in self.column_header_texts - ] + _dict['column_header_texts'] = self.column_header_texts if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: - _dict['column_header_texts_normalized'] = [ - x.to_dict() for x in self.column_header_texts_normalized - ] + _dict[ + 'column_header_texts_normalized'] = self.column_header_texts_normalized if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] + attributes_list = [] + for v in self.attributes: + if isinstance(v, dict): + attributes_list.append(v) + else: + attributes_list.append(v.to_dict()) + _dict['attributes'] = attributes_list return _dict def _to_dict(self): @@ -6785,23 +11732,25 @@ def __ne__(self, other: 'TableBodyCells') -> bool: return not self == other -class TableCellKey(): +class TableCellKey: """ A key in a key-value pair. - :attr str cell_id: (optional) The unique ID of the key in the table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the key in the table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML + :param str text: (optional) The text content of the table cell without HTML markup. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a TableCellKey object. @@ -6820,13 +11769,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellKey': """Initialize a TableCellKey object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -6840,7 +11788,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -6864,232 +11815,68 @@ def __ne__(self, other: 'TableCellKey') -> bool: return not self == other -class TableCellValues(): - """ - A value in a key-value pair. - - :attr str cell_id: (optional) The unique ID of the value in the table. - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML - markup. - """ - - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None) -> None: - """ - Initialize a TableCellValues object. - - :param str cell_id: (optional) The unique ID of the value in the table. - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. - :param str text: (optional) The text content of the table cell without HTML - markup. - """ - self.cell_id = cell_id - self.location = location - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableCellValues': - """Initialize a TableCellValues object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableCellValues object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableCellValues object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableCellValues') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableCellValues') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderIds(): - """ - An array of values, each being the `id` value of a column header that is applicable to - the current cell. - - :attr str id: (optional) The `id` value of a column header. - """ - - def __init__(self, *, id: str = None) -> None: - """ - Initialize a TableColumnHeaderIds object. - - :param str id: (optional) The `id` value of a column header. - """ - self.id = id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': - """Initialize a TableColumnHeaderIds object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderIds object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableColumnHeaderIds object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderIds') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableColumnHeaderIds') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderTexts(): - """ - An array of values, each being the `text` value of a column header that is applicable - to the current cell. - - :attr str text: (optional) The `text` value of a column header. - """ - - def __init__(self, *, text: str = None) -> None: - """ - Initialize a TableColumnHeaderTexts object. - - :param str text: (optional) The `text` value of a column header. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': - """Initialize a TableColumnHeaderTexts object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderTexts object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableColumnHeaderTexts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderTexts') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableColumnHeaderTexts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderTextsNormalized(): +class TableCellValues: """ - If you provide customization input, the normalized version of the column header texts - according to the customization; otherwise, the same value as `column_header_texts`. + A value in a key-value pair. - :attr str text_normalized: (optional) The normalized version of a column header - text. + :param str cell_id: (optional) The unique ID of the value in the table. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :param str text: (optional) The text content of the table cell without HTML + markup. """ - def __init__(self, *, text_normalized: str = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + ) -> None: """ - Initialize a TableColumnHeaderTextsNormalized object. + Initialize a TableCellValues object. - :param str text_normalized: (optional) The normalized version of a column - header text. + :param str cell_id: (optional) The unique ID of the value in the table. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The text content of the table cell without HTML + markup. """ - self.text_normalized = text_normalized + self.cell_id = cell_id + self.location = location + self.text = text @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': - """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TableCellValues': + """Initialize a TableCellValues object from a json dictionary.""" args = {} - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" + """Initialize a TableCellValues object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text return _dict def _to_dict(self): @@ -7097,67 +11884,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TableColumnHeaderTextsNormalized object.""" + """Return a `str` version of this TableCellValues object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: + def __eq__(self, other: 'TableCellValues') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: + def __ne__(self, other: 'TableCellValues') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TableColumnHeaders(): +class TableColumnHeaders: """ Column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the column header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :attr str text: (optional) The textual contents of this cell from the input + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param str text_normalized: (optional) Normalized column header text. + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: object = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + text_normalized: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableColumnHeaders object. :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the column header cell - in the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. + :param str text_normalized: (optional) Normalized column header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -7180,22 +11965,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': """Initialize a TableColumnHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -7209,7 +11994,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -7248,16 +12036,20 @@ def __ne__(self, other: 'TableColumnHeaders') -> bool: return not self == other -class TableElementLocation(): +class TableElementLocation: """ The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr int begin: The element's `begin` index. - :attr int end: The element's `end` index. + :param int begin: The element's `begin` index. + :param int end: The element's `end` index. """ - def __init__(self, begin: int, end: int) -> None: + def __init__( + self, + begin: int, + end: int, + ) -> None: """ Initialize a TableElementLocation object. @@ -7271,14 +12063,14 @@ def __init__(self, begin: int, end: int) -> None: def from_dict(cls, _dict: Dict) -> 'TableElementLocation': """Initialize a TableElementLocation object from a json dictionary.""" args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') + if (begin := _dict.get('begin')) is not None: + args['begin'] = begin else: raise ValueError( 'Required property \'begin\' not present in TableElementLocation JSON' ) - if 'end' in _dict: - args['end'] = _dict.get('end') + if (end := _dict.get('end')) is not None: + args['end'] = end else: raise ValueError( 'Required property \'end\' not present in TableElementLocation JSON' @@ -7318,43 +12110,45 @@ def __ne__(self, other: 'TableElementLocation') -> bool: return not self == other -class TableHeaders(): +class TableHeaders: """ The contents of the current table's header. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the table header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :attr str text: (optional) The textual contents of the cell from the input + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :param str text: (optional) The textual contents of the cell from the input document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: object = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableHeaders object. :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the table header cell in - the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. :param str text: (optional) The textual contents of the cell from the input document without associated markup content. :param int row_index_begin: (optional) The `begin` index of this cell's @@ -7378,20 +12172,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -7405,7 +12199,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -7441,339 +12238,62 @@ def __ne__(self, other: 'TableHeaders') -> bool: return not self == other -class TableKeyValuePairs(): +class TableKeyValuePairs: """ Key-value pairs detected across cell boundaries. - :attr TableCellKey key: (optional) A key in a key-value pair. - :attr List[TableCellValues] value: (optional) A list of values in a key-value + :param TableCellKey key: (optional) A key in a key-value pair. + :param List[TableCellValues] value: (optional) A list of values in a key-value pair. """ - def __init__(self, - *, - key: 'TableCellKey' = None, - value: List['TableCellValues'] = None) -> None: - """ - Initialize a TableKeyValuePairs object. - - :param TableCellKey key: (optional) A key in a key-value pair. - :param List[TableCellValues] value: (optional) A list of values in a - key-value pair. - """ - self.key = key - self.value = value - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': - """Initialize a TableKeyValuePairs object from a json dictionary.""" - args = {} - if 'key' in _dict: - args['key'] = TableCellKey.from_dict(_dict.get('key')) - if 'value' in _dict: - args['value'] = [ - TableCellValues.from_dict(x) for x in _dict.get('value') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableKeyValuePairs object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key.to_dict() - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = [x.to_dict() for x in self.value] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableKeyValuePairs object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableKeyValuePairs') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableKeyValuePairs') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableResultTable(): - """ - Full table object retrieved from Table Understanding Enrichment. - - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. - :attr str text: (optional) The textual contents of the current table from the - input document without associated markup content. - :attr TableTextLocation section_title: (optional) Text and associated location - within a table. - :attr TableTextLocation title: (optional) Text and associated location within a - table. - :attr List[TableHeaders] table_headers: (optional) An array of table-level cells - that apply as headers to all the other cells in the current table. - :attr List[TableRowHeaders] row_headers: (optional) An array of row-level cells, - each applicable as a header to other cells in the same row as itself, of the - current table. - :attr List[TableColumnHeaders] column_headers: (optional) An array of - column-level cells, each applicable as a header to other cells in the same - column as itself, of the current table. - :attr List[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value - pairs identified in the current table. - :attr List[TableBodyCells] body_cells: (optional) An array of cells that are - neither table header nor column header nor row header cells, of the current - table with corresponding row and column header associations. - :attr List[TableTextLocation] contexts: (optional) An array of lists of textual - entries across the document related to the current table being parsed. - """ - - def __init__(self, - *, - location: 'TableElementLocation' = None, - text: str = None, - section_title: 'TableTextLocation' = None, - title: 'TableTextLocation' = None, - table_headers: List['TableHeaders'] = None, - row_headers: List['TableRowHeaders'] = None, - column_headers: List['TableColumnHeaders'] = None, - key_value_pairs: List['TableKeyValuePairs'] = None, - body_cells: List['TableBodyCells'] = None, - contexts: List['TableTextLocation'] = None) -> None: - """ - Initialize a TableResultTable object. - - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. - :param str text: (optional) The textual contents of the current table from - the input document without associated markup content. - :param TableTextLocation section_title: (optional) Text and associated - location within a table. - :param TableTextLocation title: (optional) Text and associated location - within a table. - :param List[TableHeaders] table_headers: (optional) An array of table-level - cells that apply as headers to all the other cells in the current table. - :param List[TableRowHeaders] row_headers: (optional) An array of row-level - cells, each applicable as a header to other cells in the same row as - itself, of the current table. - :param List[TableColumnHeaders] column_headers: (optional) An array of - column-level cells, each applicable as a header to other cells in the same - column as itself, of the current table. - :param List[TableKeyValuePairs] key_value_pairs: (optional) An array of - key-value pairs identified in the current table. - :param List[TableBodyCells] body_cells: (optional) An array of cells that - are neither table header nor column header nor row header cells, of the - current table with corresponding row and column header associations. - :param List[TableTextLocation] contexts: (optional) An array of lists of - textual entries across the document related to the current table being - parsed. - """ - self.location = location - self.text = text - self.section_title = section_title - self.title = title - self.table_headers = table_headers - self.row_headers = row_headers - self.column_headers = column_headers - self.key_value_pairs = key_value_pairs - self.body_cells = body_cells - self.contexts = contexts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableResultTable': - """Initialize a TableResultTable object from a json dictionary.""" - args = {} - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'section_title' in _dict: - args['section_title'] = TableTextLocation.from_dict( - _dict.get('section_title')) - if 'title' in _dict: - args['title'] = TableTextLocation.from_dict(_dict.get('title')) - if 'table_headers' in _dict: - args['table_headers'] = [ - TableHeaders.from_dict(x) for x in _dict.get('table_headers') - ] - if 'row_headers' in _dict: - args['row_headers'] = [ - TableRowHeaders.from_dict(x) for x in _dict.get('row_headers') - ] - if 'column_headers' in _dict: - args['column_headers'] = [ - TableColumnHeaders.from_dict(x) - for x in _dict.get('column_headers') - ] - if 'key_value_pairs' in _dict: - args['key_value_pairs'] = [ - TableKeyValuePairs.from_dict(x) - for x in _dict.get('key_value_pairs') - ] - if 'body_cells' in _dict: - args['body_cells'] = [ - TableBodyCells.from_dict(x) for x in _dict.get('body_cells') - ] - if 'contexts' in _dict: - args['contexts'] = [ - TableTextLocation.from_dict(x) for x in _dict.get('contexts') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableResultTable object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'section_title') and self.section_title is not None: - _dict['section_title'] = self.section_title.to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() - if hasattr(self, 'table_headers') and self.table_headers is not None: - _dict['table_headers'] = [x.to_dict() for x in self.table_headers] - if hasattr(self, 'row_headers') and self.row_headers is not None: - _dict['row_headers'] = [x.to_dict() for x in self.row_headers] - if hasattr(self, 'column_headers') and self.column_headers is not None: - _dict['column_headers'] = [x.to_dict() for x in self.column_headers] - if hasattr(self, - 'key_value_pairs') and self.key_value_pairs is not None: - _dict['key_value_pairs'] = [ - x.to_dict() for x in self.key_value_pairs - ] - if hasattr(self, 'body_cells') and self.body_cells is not None: - _dict['body_cells'] = [x.to_dict() for x in self.body_cells] - if hasattr(self, 'contexts') and self.contexts is not None: - _dict['contexts'] = [x.to_dict() for x in self.contexts] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableResultTable object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableResultTable') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableResultTable') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaderIds(): - """ - An array of values, each being the `id` value of a row header that is applicable to - this body cell. - - :attr str id: (optional) The `id` values of a row header. - """ - - def __init__(self, *, id: str = None) -> None: - """ - Initialize a TableRowHeaderIds object. - - :param str id: (optional) The `id` values of a row header. - """ - self.id = id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': - """Initialize a TableRowHeaderIds object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderIds object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TableRowHeaderIds object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderIds') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TableRowHeaderIds') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaderTexts(): - """ - An array of values, each being the `text` value of a row header that is applicable to - this body cell. - - :attr str text: (optional) The `text` value of a row header. - """ - - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + key: Optional['TableCellKey'] = None, + value: Optional[List['TableCellValues']] = None, + ) -> None: """ - Initialize a TableRowHeaderTexts object. + Initialize a TableKeyValuePairs object. - :param str text: (optional) The `text` value of a row header. + :param TableCellKey key: (optional) A key in a key-value pair. + :param List[TableCellValues] value: (optional) A list of values in a + key-value pair. """ - self.text = text + self.key = key + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': - """Initialize a TableRowHeaderTexts object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': + """Initialize a TableKeyValuePairs object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (key := _dict.get('key')) is not None: + args['key'] = TableCellKey.from_dict(key) + if (value := _dict.get('value')) is not None: + args['value'] = [TableCellValues.from_dict(v) for v in value] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TableRowHeaderTexts object from a json dictionary.""" + """Initialize a TableKeyValuePairs object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text + if hasattr(self, 'key') and self.key is not None: + if isinstance(self.key, dict): + _dict['key'] = self.key + else: + _dict['key'] = self.key.to_dict() + if hasattr(self, 'value') and self.value is not None: + value_list = [] + for v in self.value: + if isinstance(v, dict): + value_list.append(v) + else: + value_list.append(v.to_dict()) + _dict['value'] = value_list return _dict def _to_dict(self): @@ -7781,57 +12301,216 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TableRowHeaderTexts object.""" + """Return a `str` version of this TableKeyValuePairs object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TableRowHeaderTexts') -> bool: + def __eq__(self, other: 'TableKeyValuePairs') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TableRowHeaderTexts') -> bool: + def __ne__(self, other: 'TableKeyValuePairs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TableRowHeaderTextsNormalized(): +class TableResultTable: """ - If you provide customization input, the normalized version of the row header texts - according to the customization; otherwise, the same value as `row_header_texts`. + Full table object retrieved from Table Understanding Enrichment. - :attr str text_normalized: (optional) The normalized version of a row header - text. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :param str text: (optional) The textual contents of the current table from the + input document without associated markup content. + :param TableTextLocation section_title: (optional) Text and associated location + within a table. + :param TableTextLocation title: (optional) Text and associated location within a + table. + :param List[TableHeaders] table_headers: (optional) An array of table-level + cells that apply as headers to all the other cells in the current table. + :param List[TableRowHeaders] row_headers: (optional) An array of row-level + cells, each applicable as a header to other cells in the same row as itself, of + the current table. + :param List[TableColumnHeaders] column_headers: (optional) An array of + column-level cells, each applicable as a header to other cells in the same + column as itself, of the current table. + :param List[TableKeyValuePairs] key_value_pairs: (optional) An array of + key-value pairs identified in the current table. + :param List[TableBodyCells] body_cells: (optional) An array of cells that are + neither table header nor column header nor row header cells, of the current + table with corresponding row and column header associations. + :param List[TableTextLocation] contexts: (optional) An array of lists of textual + entries across the document related to the current table being parsed. """ - def __init__(self, *, text_normalized: str = None) -> None: + def __init__( + self, + *, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + section_title: Optional['TableTextLocation'] = None, + title: Optional['TableTextLocation'] = None, + table_headers: Optional[List['TableHeaders']] = None, + row_headers: Optional[List['TableRowHeaders']] = None, + column_headers: Optional[List['TableColumnHeaders']] = None, + key_value_pairs: Optional[List['TableKeyValuePairs']] = None, + body_cells: Optional[List['TableBodyCells']] = None, + contexts: Optional[List['TableTextLocation']] = None, + ) -> None: """ - Initialize a TableRowHeaderTextsNormalized object. + Initialize a TableResultTable object. - :param str text_normalized: (optional) The normalized version of a row - header text. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The textual contents of the current table from + the input document without associated markup content. + :param TableTextLocation section_title: (optional) Text and associated + location within a table. + :param TableTextLocation title: (optional) Text and associated location + within a table. + :param List[TableHeaders] table_headers: (optional) An array of table-level + cells that apply as headers to all the other cells in the current table. + :param List[TableRowHeaders] row_headers: (optional) An array of row-level + cells, each applicable as a header to other cells in the same row as + itself, of the current table. + :param List[TableColumnHeaders] column_headers: (optional) An array of + column-level cells, each applicable as a header to other cells in the same + column as itself, of the current table. + :param List[TableKeyValuePairs] key_value_pairs: (optional) An array of + key-value pairs identified in the current table. + :param List[TableBodyCells] body_cells: (optional) An array of cells that + are neither table header nor column header nor row header cells, of the + current table with corresponding row and column header associations. + :param List[TableTextLocation] contexts: (optional) An array of lists of + textual entries across the document related to the current table being + parsed. """ - self.text_normalized = text_normalized + self.location = location + self.text = text + self.section_title = section_title + self.title = title + self.table_headers = table_headers + self.row_headers = row_headers + self.column_headers = column_headers + self.key_value_pairs = key_value_pairs + self.body_cells = body_cells + self.contexts = contexts @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': - """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TableResultTable': + """Initialize a TableResultTable object from a json dictionary.""" args = {} - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (section_title := _dict.get('section_title')) is not None: + args['section_title'] = TableTextLocation.from_dict(section_title) + if (title := _dict.get('title')) is not None: + args['title'] = TableTextLocation.from_dict(title) + if (table_headers := _dict.get('table_headers')) is not None: + args['table_headers'] = [ + TableHeaders.from_dict(v) for v in table_headers + ] + if (row_headers := _dict.get('row_headers')) is not None: + args['row_headers'] = [ + TableRowHeaders.from_dict(v) for v in row_headers + ] + if (column_headers := _dict.get('column_headers')) is not None: + args['column_headers'] = [ + TableColumnHeaders.from_dict(v) for v in column_headers + ] + if (key_value_pairs := _dict.get('key_value_pairs')) is not None: + args['key_value_pairs'] = [ + TableKeyValuePairs.from_dict(v) for v in key_value_pairs + ] + if (body_cells := _dict.get('body_cells')) is not None: + args['body_cells'] = [ + TableBodyCells.from_dict(v) for v in body_cells + ] + if (contexts := _dict.get('contexts')) is not None: + args['contexts'] = [ + TableTextLocation.from_dict(v) for v in contexts + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" + """Initialize a TableResultTable object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} + if hasattr(self, 'location') and self.location is not None: + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'section_title') and self.section_title is not None: + if isinstance(self.section_title, dict): + _dict['section_title'] = self.section_title + else: + _dict['section_title'] = self.section_title.to_dict() + if hasattr(self, 'title') and self.title is not None: + if isinstance(self.title, dict): + _dict['title'] = self.title + else: + _dict['title'] = self.title.to_dict() + if hasattr(self, 'table_headers') and self.table_headers is not None: + table_headers_list = [] + for v in self.table_headers: + if isinstance(v, dict): + table_headers_list.append(v) + else: + table_headers_list.append(v.to_dict()) + _dict['table_headers'] = table_headers_list + if hasattr(self, 'row_headers') and self.row_headers is not None: + row_headers_list = [] + for v in self.row_headers: + if isinstance(v, dict): + row_headers_list.append(v) + else: + row_headers_list.append(v.to_dict()) + _dict['row_headers'] = row_headers_list + if hasattr(self, 'column_headers') and self.column_headers is not None: + column_headers_list = [] + for v in self.column_headers: + if isinstance(v, dict): + column_headers_list.append(v) + else: + column_headers_list.append(v.to_dict()) + _dict['column_headers'] = column_headers_list if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized + 'key_value_pairs') and self.key_value_pairs is not None: + key_value_pairs_list = [] + for v in self.key_value_pairs: + if isinstance(v, dict): + key_value_pairs_list.append(v) + else: + key_value_pairs_list.append(v.to_dict()) + _dict['key_value_pairs'] = key_value_pairs_list + if hasattr(self, 'body_cells') and self.body_cells is not None: + body_cells_list = [] + for v in self.body_cells: + if isinstance(v, dict): + body_cells_list.append(v) + else: + body_cells_list.append(v.to_dict()) + _dict['body_cells'] = body_cells_list + if hasattr(self, 'contexts') and self.contexts is not None: + contexts_list = [] + for v in self.contexts: + if isinstance(v, dict): + contexts_list.append(v) + else: + contexts_list.append(v.to_dict()) + _dict['contexts'] = contexts_list return _dict def _to_dict(self): @@ -7839,54 +12518,54 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TableRowHeaderTextsNormalized object.""" + """Return a `str` version of this TableResultTable object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TableRowHeaderTextsNormalized') -> bool: + def __eq__(self, other: 'TableResultTable') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TableRowHeaderTextsNormalized') -> bool: + def __ne__(self, other: 'TableResultTable') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TableRowHeaders(): +class TableRowHeaders: """ Row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param str text_normalized: (optional) Normalized row header text. + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + text_normalized: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableRowHeaders object. @@ -7897,9 +12576,7 @@ def __init__(self, labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. + :param str text_normalized: (optional) Normalized row header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -7922,23 +12599,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableRowHeaders': """Initialize a TableRowHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -7952,7 +12628,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -7991,20 +12670,22 @@ def __ne__(self, other: 'TableRowHeaders') -> bool: return not self == other -class TableTextLocation(): +class TableTextLocation: """ Text and associated location within a table. - :attr str text: (optional) The text retrieved. - :attr TableElementLocation location: (optional) The numeric location of the + :param str text: (optional) The text retrieved. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ - def __init__(self, - *, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + ) -> None: """ Initialize a TableTextLocation object. @@ -8020,11 +12701,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableTextLocation': """Initialize a TableTextLocation object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) return cls(**args) @classmethod @@ -8038,7 +12718,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -8060,25 +12743,29 @@ def __ne__(self, other: 'TableTextLocation') -> bool: return not self == other -class TrainingExample(): +class TrainingExample: """ Object that contains example response details for a training query. - :attr str document_id: The document ID associated with this training example. - :attr str collection_id: The collection ID associated with this training + :param str document_id: The document ID associated with this training example. + :param str collection_id: The collection ID associated with this training example. - :attr int relevance: The relevance of the training example. - :attr datetime created: (optional) The date and time the example was created. - :attr datetime updated: (optional) The date and time the example was updated. + :param int relevance: The relevance score of the training example. Scores range + from `0` to `100`. Zero means not relevant. The higher the number, the more + relevant the example. + :param datetime created: (optional) The date and time the example was created. + :param datetime updated: (optional) The date and time the example was updated. """ - def __init__(self, - document_id: str, - collection_id: str, - relevance: int, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + document_id: str, + collection_id: str, + relevance: int, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingExample object. @@ -8086,7 +12773,9 @@ def __init__(self, example. :param str collection_id: The collection ID associated with this training example. - :param int relevance: The relevance of the training example. + :param int relevance: The relevance score of the training example. Scores + range from `0` to `100`. Zero means not relevant. The higher the number, + the more relevant the example. """ self.document_id = document_id self.collection_id = collection_id @@ -8098,28 +12787,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in TrainingExample JSON' ) - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in TrainingExample JSON' ) - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance else: raise ValueError( 'Required property \'relevance\' not present in TrainingExample JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -8161,35 +12850,46 @@ def __ne__(self, other: 'TrainingExample') -> bool: return not self == other -class TrainingQuery(): +class TrainingQuery: """ Object that contains training query details. - :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: The natural text query for the training query. - :attr str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :attr datetime created: (optional) The date and time the query was created. - :attr datetime updated: (optional) The date and time the query was updated. - :attr List[TrainingExample] examples: Array of training examples. + :param str query_id: (optional) The query ID associated with the training query. + :param str natural_language_query: The natural text query that is used as the + training query. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. Only specify a filter if the documents + that you consider to be most relevant are not included in the top 100 results + when you submit test queries. If you specify a filter during training, apply the + same filter to queries that are submitted at runtime for optimal ranking + results. + :param datetime created: (optional) The date and time the query was created. + :param datetime updated: (optional) The date and time the query was updated. + :param List[TrainingExample] examples: Array of training examples. """ - def __init__(self, - natural_language_query: str, - examples: List['TrainingExample'], - *, - query_id: str = None, - filter: str = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + natural_language_query: str, + examples: List['TrainingExample'], + *, + query_id: Optional[str] = None, + filter: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingQuery object. - :param str natural_language_query: The natural text query for the training - query. + :param str natural_language_query: The natural text query that is used as + the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -8202,24 +12902,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query else: raise ValueError( 'Required property \'natural_language_query\' not present in TrainingQuery JSON' ) - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') - ] + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in TrainingQuery JSON' @@ -8246,7 +12945,220 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TrainingQuery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TrainingQuery') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TrainingQuery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingQuerySet: + """ + Object specifying the training queries contained in the identified training set. + + :param List[TrainingQuery] queries: (optional) Array of training queries. At + least 50 queries are required for training to begin. A maximum of 10,000 queries + are returned. + """ + + def __init__( + self, + *, + queries: Optional[List['TrainingQuery']] = None, + ) -> None: + """ + Initialize a TrainingQuerySet object. + + :param List[TrainingQuery] queries: (optional) Array of training queries. + At least 50 queries are required for training to begin. A maximum of 10,000 + queries are returned. + """ + self.queries = queries + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': + """Initialize a TrainingQuerySet object from a json dictionary.""" + args = {} + if (queries := _dict.get('queries')) is not None: + args['queries'] = [TrainingQuery.from_dict(v) for v in queries] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuerySet object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'queries') and self.queries is not None: + queries_list = [] + for v in self.queries: + if isinstance(v, dict): + queries_list.append(v) + else: + queries_list.append(v.to_dict()) + _dict['queries'] = queries_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TrainingQuerySet object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TrainingQuerySet') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TrainingQuerySet') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class UpdateDocumentClassifier: + """ + An object that contains a new name or description for a document classifier, updated + training data, or new or updated test data. + + :param str name: (optional) A new name for the classifier. + :param str description: (optional) A new description for the classifier. + """ + + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ) -> None: + """ + Initialize a UpdateDocumentClassifier object. + + :param str name: (optional) A new name for the classifier. + :param str description: (optional) A new description for the classifier. + """ + self.name = name + self.description = description + + @classmethod + def from_dict(cls, _dict: Dict) -> 'UpdateDocumentClassifier': + """Initialize a UpdateDocumentClassifier object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdateDocumentClassifier object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this UpdateDocumentClassifier object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'UpdateDocumentClassifier') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'UpdateDocumentClassifier') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class WebhookHeader: + """ + An array of headers to pass with the HTTP request. Optional when `type` is `webhook`. + Not valid when creating any other type of enrichment. + + :param str name: The name of an HTTP header. + :param str value: The value of an HTTP header. + """ + + def __init__( + self, + name: str, + value: str, + ) -> None: + """ + Initialize a WebhookHeader object. + + :param str name: The name of an HTTP header. + :param str value: The value of an HTTP header. + """ + self.name = name + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WebhookHeader': + """Initialize a WebhookHeader object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in WebhookHeader JSON') + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in WebhookHeader JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WebhookHeader object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -8254,55 +13166,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TrainingQuery object.""" + """Return a `str` version of this WebhookHeader object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TrainingQuery') -> bool: + def __eq__(self, other: 'WebhookHeader') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TrainingQuery') -> bool: + def __ne__(self, other: 'WebhookHeader') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TrainingQuerySet(): +class PullBatchesResponse: """ - Object specifying the training queries contained in the identified training set. + A compressed newline delimited JSON (NDJSON) file containing the document. The NDJSON + format is used to describe structured data. The file name format is + `{batch_id}.ndjson.gz`. For more information, see [Binary attachment from the pull + batches + method](/docs/discovery-data?topic=discovery-data-external-enrichment#binary-attachment-pull-batches). - :attr List[TrainingQuery] queries: (optional) Array of training queries. + :param str file: (optional) A compressed NDJSON file containing the document. """ - def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: + def __init__( + self, + *, + file: Optional[str] = None, + ) -> None: """ - Initialize a TrainingQuerySet object. + Initialize a PullBatchesResponse object. - :param List[TrainingQuery] queries: (optional) Array of training queries. + :param str file: (optional) A compressed NDJSON file containing the + document. """ - self.queries = queries + self.file = file @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': - """Initialize a TrainingQuerySet object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'PullBatchesResponse': + """Initialize a PullBatchesResponse object from a json dictionary.""" args = {} - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(x) for x in _dict.get('queries') - ] + if (file := _dict.get('file')) is not None: + args['file'] = file return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TrainingQuerySet object from a json dictionary.""" + """Initialize a PullBatchesResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x.to_dict() for x in self.queries] + if hasattr(self, 'file') and self.file is not None: + _dict['file'] = self.file return _dict def _to_dict(self): @@ -8310,66 +13229,71 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TrainingQuerySet object.""" + """Return a `str` version of this PullBatchesResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TrainingQuerySet') -> bool: + def __eq__(self, other: 'PullBatchesResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TrainingQuerySet') -> bool: + def __ne__(self, other: 'PullBatchesResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryCalculationAggregation(QueryAggregation): +class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :param str type: (optional) Specifies the calculation type, such as 'average`, + `max`, `min`, `sum`, or `unique_count`. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. """ - def __init__(self, type: str, field: str, *, value: float = None) -> None: + def __init__( + self, + field: str, + *, + type: Optional[str] = None, + value: Optional[float] = None, + ) -> None: """ - Initialize a QueryCalculationAggregation object. + Initialize a QueryAggregationQueryCalculationAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The field to perform the calculation on. + :param str type: (optional) Specifies the calculation type, such as + 'average`, `max`, `min`, `sum`, or `unique_count`. :param float value: (optional) The value of the calculation. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryCalculationAggregation': + """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryCalculationAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryCalculationAggregation JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8388,85 +13312,82 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryCalculationAggregation object.""" + """Return a `str` version of this QueryAggregationQueryCalculationAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryCalculationAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryCalculationAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryCalculationAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryCalculationAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryFilterAggregation(QueryAggregation): +class QueryAggregationQueryFilterAggregation(QueryAggregation): """ - A modifier that narrows the document set of the sub-aggregations it precedes. + A modifier that narrows the document set of the subaggregations it precedes. - :attr str match: The filter that is written in Discovery Query Language syntax - and is applied to the documents before sub-aggregations are run. - :attr int matching_results: Number of documents that match the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is `filter`. + :param str match: The filter that is written in Discovery Query Language syntax + and is applied to the documents before subaggregations are run. + :param int matching_results: Number of documents that match the filter. + :param List[dict] aggregations: (optional) An array of subaggregations. """ - def __init__(self, - type: str, - match: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + match: str, + matching_results: int, + *, + type: Optional[str] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ - Initialize a QueryFilterAggregation object. + Initialize a QueryAggregationQueryFilterAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str match: The filter that is written in Discovery Query Language - syntax and is applied to the documents before sub-aggregations are run. + syntax and is applied to the documents before subaggregations are run. :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is + `filter`. + :param List[dict] aggregations: (optional) An array of subaggregations. """ + # pylint: disable=super-init-not-called self.type = type self.match = match self.matching_results = matching_results self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': - """Initialize a QueryFilterAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryFilterAggregation': + """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryFilterAggregation JSON' - ) - if 'match' in _dict: - args['match'] = _dict.get('match') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (match := _dict.get('match')) is not None: + args['match'] = match else: raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' + 'Required property \'match\' not present in QueryAggregationQueryFilterAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + 'Required property \'matching_results\' not present in QueryAggregationQueryFilterAggregation JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8480,7 +13401,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -8488,64 +13409,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryFilterAggregation object.""" + """Return a `str` version of this QueryAggregationQueryFilterAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryFilterAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryFilterAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryFilterAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryFilterAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryGroupByAggregation(QueryAggregation): +class QueryAggregationQueryGroupByAggregation(QueryAggregation): """ - Returns the top values for the field specified. + Separates document results into groups that meet the conditions you specify. - :attr List[QueryGroupByAggregationResult] results: (optional) Array of top - values for the field. + :param str type: (optional) Specifies that the aggregation type is `group_by`. + :param List[QueryGroupByAggregationResult] results: (optional) An array of + results. """ - def __init__(self, - type: str, - *, - results: List['QueryGroupByAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + results: Optional[List['QueryGroupByAggregationResult']] = None, + ) -> None: """ - Initialize a QueryGroupByAggregation object. + Initialize a QueryAggregationQueryGroupByAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param List[QueryGroupByAggregationResult] results: (optional) Array of top - values for the field. + :param str type: (optional) Specifies that the aggregation type is + `group_by`. + :param List[QueryGroupByAggregationResult] results: (optional) An array of + results. """ + # pylint: disable=super-init-not-called self.type = type self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': - """Initialize a QueryGroupByAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryGroupByAggregation': + """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryGroupByAggregation JSON' - ) - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryGroupByAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryGroupByAggregationResult.from_dict(v) for v in results ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryGroupByAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8554,7 +13474,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8562,55 +13488,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryGroupByAggregation object.""" + """Return a `str` version of this QueryAggregationQueryGroupByAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryGroupByAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryGroupByAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryGroupByAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryGroupByAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryHistogramAggregation(QueryAggregation): +class QueryAggregationQueryHistogramAggregation(QueryAggregation): """ Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. + :param str type: (optional) Specifies that the aggregation type is `histogram`. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections that the results are split into. + :param str name: (optional) Identifier that can optionally be specified in the + query request of this aggregation. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. """ def __init__( - self, - type: str, - field: str, - interval: int, - *, - name: str = None, - results: List['QueryHistogramAggregationResult'] = None) -> None: - """ - Initialize a QueryHistogramAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. + self, + field: str, + interval: int, + *, + type: Optional[str] = None, + name: Optional[str] = None, + results: Optional[List['QueryHistogramAggregationResult']] = None, + ) -> None: + """ + Initialize a QueryAggregationQueryHistogramAggregation object. + :param str field: The numeric field name used to create the histogram. :param int interval: The size of the sections that the results are split into. - :param str name: (optional) Identifier specified in the query request of - this aggregation. + :param str type: (optional) Specifies that the aggregation type is + `histogram`. + :param str name: (optional) Identifier that can optionally be specified in + the query request of this aggregation. :param List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.interval = interval @@ -8618,39 +13546,35 @@ def __init__( self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': - """Initialize a QueryHistogramAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryHistogramAggregation': + """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( - 'Required property \'type\' not present in QueryHistogramAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryHistogramAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' + 'Required property \'interval\' not present in QueryAggregationQueryHistogramAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryHistogramAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) for v in results ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8665,7 +13589,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8673,87 +13603,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryHistogramAggregation object.""" + """Return a `str` version of this QueryAggregationQueryHistogramAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryHistogramAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryHistogramAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryHistogramAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryHistogramAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryNestedAggregation(QueryAggregation): +class QueryAggregationQueryNestedAggregation(QueryAggregation): """ - A restriction that alters the document set that is used for sub-aggregations it - precedes to nested documents found in the field specified. + A restriction that alters the document set that is used by the aggregations that it + precedes. Subsequent aggregations are applied to nested documents from the specified + field. - :attr str path: The path to the document field to scope sub-aggregations to. - :attr int matching_results: Number of nested documents found in the specified + :param str type: (optional) Specifies that the aggregation type is `nested`. + :param str path: The path to the document field to scope subsequent aggregations + to. + :param int matching_results: Number of nested documents found in the specified field. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. """ - def __init__(self, - type: str, - path: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + path: str, + matching_results: int, + *, + type: Optional[str] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ - Initialize a QueryNestedAggregation object. + Initialize a QueryAggregationQueryNestedAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str path: The path to the document field to scope sub-aggregations - to. + :param str path: The path to the document field to scope subsequent + aggregations to. :param int matching_results: Number of nested documents found in the specified field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is + `nested`. + :param List[dict] aggregations: (optional) An array of subaggregations. """ + # pylint: disable=super-init-not-called self.type = type self.path = path self.matching_results = matching_results self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': - """Initialize a QueryNestedAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryNestedAggregation': + """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (path := _dict.get('path')) is not None: + args['path'] = path else: raise ValueError( - 'Required property \'type\' not present in QueryNestedAggregation JSON' + 'Required property \'path\' not present in QueryAggregationQueryNestedAggregation JSON' ) - if 'path' in _dict: - args['path'] = _dict.get('path') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' + 'Required property \'matching_results\' not present in QueryAggregationQueryNestedAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8767,7 +13696,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -8775,53 +13704,188 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryNestedAggregation object.""" + """Return a `str` version of this QueryAggregationQueryNestedAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryNestedAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryNestedAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryNestedAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryNestedAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTermAggregation(QueryAggregation): +class QueryAggregationQueryPairAggregation(QueryAggregation): """ - Returns the top values for the field specified. + Calculates relevancy values using combinations of document sets from results of the + specified pair of aggregations. - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryTermAggregationResult] results: (optional) Array of top values - for the field. - """ - - def __init__(self, - type: str, - field: str, - *, - count: int = None, - name: str = None, - results: List['QueryTermAggregationResult'] = None) -> None: - """ - Initialize a QueryTermAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. + :param str type: (optional) Specifies that the aggregation type is `pair`. + :param str first: (optional) Specifies the first aggregation in the pair. The + aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param str second: (optional) Specifies the second aggregation in the pair. The + aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryPairAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + first: Optional[str] = None, + second: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryPairAggregationResult']] = None, + ) -> None: + """ + Initialize a QueryAggregationQueryPairAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `pair`. + :param str first: (optional) Specifies the first aggregation in the pair. + The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param str second: (optional) Specifies the second aggregation in the pair. + The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryPairAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.first = first + self.second = second + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryPairAggregation': + """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (first := _dict.get('first')) is not None: + args['first'] = first + if (second := _dict.get('second')) is not None: + args['second'] = second + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: + args['results'] = [ + QueryPairAggregationResult.from_dict(v) for v in results + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'first') and self.first is not None: + _dict['first'] = self.first + if hasattr(self, 'second') and self.second is not None: + _dict['second'] = self.second + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryAggregationQueryPairAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryPairAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryAggregationQueryPairAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTermAggregation(QueryAggregation): + """ + Returns results from the field that is specified. + + :param str type: (optional) Specifies that the aggregation type is `term`. + :param str field: (optional) The field in the document where the values come + from. + :param int count: (optional) The number of results returned. Not returned if + `relevancy:true` is specified in the request. + :param str name: (optional) Identifier specified in the query request of this + aggregation. Not returned if `relevancy:true` is specified in the request. + :param List[QueryTermAggregationResult] results: (optional) An array of results. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + field: Optional[str] = None, + count: Optional[int] = None, + name: Optional[str] = None, + results: Optional[List['QueryTermAggregationResult']] = None, + ) -> None: + """ + Initialize a QueryAggregationQueryTermAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `term`. + :param str field: (optional) The field in the document where the values + come from. + :param int count: (optional) The number of results returned. Not returned + if `relevancy:true` is specified in the request. :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top - values for the field. + this aggregation. Not returned if `relevancy:true` is specified in the + request. + :param List[QueryTermAggregationResult] results: (optional) An array of + results. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.count = count @@ -8829,35 +13893,26 @@ def __init__(self, self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': - """Initialize a QueryTermAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTermAggregation': + """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTermAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field + if (count := _dict.get('count')) is not None: + args['count'] = count + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTermAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTermAggregationResult.from_dict(v) for v in results ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8872,7 +13927,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8880,55 +13941,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTermAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTermAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTermAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryTermAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTermAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryTermAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTimesliceAggregation(QueryAggregation): +class QueryAggregationQueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, + :param str type: (optional) Specifies that the aggregation type is `timeslice`. + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + :param str name: (optional) Identifier that can optionally be specified in the + query request of this aggregation. + :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( - self, - type: str, - field: str, - interval: str, - *, - name: str = None, - results: List['QueryTimesliceAggregationResult'] = None) -> None: - """ - Initialize a QueryTimesliceAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. + self, + field: str, + interval: str, + *, + type: Optional[str] = None, + name: Optional[str] = None, + results: Optional[List['QueryTimesliceAggregationResult']] = None, + ) -> None: + """ + Initialize a QueryAggregationQueryTimesliceAggregation object. + :param str field: The date field name used to create the timeslice. :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :param str name: (optional) Identifier specified in the query request of - this aggregation. + :param str type: (optional) Specifies that the aggregation type is + `timeslice`. + :param str name: (optional) Identifier that can optionally be specified in + the query request of this aggregation. :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.interval = interval @@ -8936,39 +13999,35 @@ def __init__( self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryTimesliceAggregation': + """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTimesliceAggregation JSON' - ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + 'Required property \'interval\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) for v in results ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8983,7 +14042,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8991,78 +14056,81 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTimesliceAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTimesliceAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryTimesliceAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTimesliceAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryTimesliceAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTopHitsAggregation(QueryAggregation): +class QueryAggregationQueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. - :attr int size: The number of documents to return. - :attr str name: (optional) Identifier specified in the query request of this + :param str type: (optional) Specifies that the aggregation type is `top_hits`. + :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) + :param QueryTopHitsAggregationResult hits: (optional) A query response that + contains the matching documents for the preceding aggregations. """ - def __init__(self, - type: str, - size: int, - *, - name: str = None, - hits: 'QueryTopHitsAggregationResult' = None) -> None: + def __init__( + self, + size: int, + *, + type: Optional[str] = None, + name: Optional[str] = None, + hits: Optional['QueryTopHitsAggregationResult'] = None, + ) -> None: """ - Initialize a QueryTopHitsAggregation object. + Initialize a QueryAggregationQueryTopHitsAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param int size: The number of documents to return. + :param str type: (optional) Specifies that the aggregation type is + `top_hits`. :param str name: (optional) Identifier specified in the query request of this aggregation. - :param QueryTopHitsAggregationResult hits: (optional) + :param QueryTopHitsAggregationResult hits: (optional) A query response that + contains the matching documents for the preceding aggregations. """ + # pylint: disable=super-init-not-called self.type = type self.size = size self.name = name self.hits = hits @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryTopHitsAggregation': + """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTopHitsAggregation JSON' - ) - if 'size' in _dict: - args['size'] = _dict.get('size') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (size := _dict.get('size')) is not None: + args['size'] = size else: raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + 'Required property \'size\' not present in QueryAggregationQueryTopHitsAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult.from_dict( - _dict.get('hits')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (hits := _dict.get('hits')) is not None: + args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -9075,7 +14143,264 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits.to_dict() + if isinstance(self.hits, dict): + _dict['hits'] = self.hits + else: + _dict['hits'] = self.hits.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryAggregationQueryTopHitsAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryTopHitsAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryAggregationQueryTopHitsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTopicAggregation(QueryAggregation): + """ + Detects how much the frequency of a given facet value deviates from the expected + average for the given time period. This aggregation type does not use data from + previous time periods. It calculates an index by using the averages of frequency + counts of other facet values for the given time period. + + :param str type: (optional) Specifies that the aggregation type is `topic`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation for + the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation that + defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTopicAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + facet: Optional[str] = None, + time_segments: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryTopicAggregationResult']] = None, + ) -> None: + """ + Initialize a QueryAggregationQueryTopicAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `topic`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation + for the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation + that defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTopicAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.facet = facet + self.time_segments = time_segments + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopicAggregation': + """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (facet := _dict.get('facet')) is not None: + args['facet'] = facet + if (time_segments := _dict.get('time_segments')) is not None: + args['time_segments'] = time_segments + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: + args['results'] = [ + QueryTopicAggregationResult.from_dict(v) for v in results + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'facet') and self.facet is not None: + _dict['facet'] = self.facet + if hasattr(self, 'time_segments') and self.time_segments is not None: + _dict['time_segments'] = self.time_segments + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryAggregationQueryTopicAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryTopicAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryAggregationQueryTopicAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTrendAggregation(QueryAggregation): + """ + Detects sharp and unexpected changes in the frequency of a facet or facet value over + time based on the past history of frequency changes of the facet value. + + :param str type: (optional) Specifies that the aggregation type is `trend`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation for + the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation that + defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTrendAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + facet: Optional[str] = None, + time_segments: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryTrendAggregationResult']] = None, + ) -> None: + """ + Initialize a QueryAggregationQueryTrendAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `trend`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation + for the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation + that defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTrendAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.facet = facet + self.time_segments = time_segments + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTrendAggregation': + """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (facet := _dict.get('facet')) is not None: + args['facet'] = facet + if (time_segments := _dict.get('time_segments')) is not None: + args['time_segments'] = time_segments + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: + args['results'] = [ + QueryTrendAggregationResult.from_dict(v) for v in results + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'facet') and self.facet is not None: + _dict['facet'] = self.facet + if hasattr(self, 'time_segments') and self.time_segments is not None: + _dict['time_segments'] = self.time_segments + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -9083,15 +14408,15 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTopHitsAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTrendAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTopHitsAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryTrendAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTopHitsAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryTrendAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py deleted file mode 100644 index d24244403..000000000 --- a/ibm_watson/language_translator_v3.py +++ /dev/null @@ -1,2091 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2022. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 -""" -IBM Watson™ Language Translator translates text from one language to another. The -service offers multiple IBM-provided translation models that you can customize based on -your unique terminology and language. Use Language Translator to take news from across the -globe and present it in your language, communicate with your customers in their own -language, and more. - -API Version: 3.0.0 -See: https://cloud.ibm.com/docs/language-translator -""" - -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List, TextIO, Union -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class LanguageTranslatorV3(BaseService): - """The Language Translator V3 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.language-translator.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'language_translator' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Language Translator service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2018-05-01`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Languages - ######################### - - def list_languages(self, **kwargs) -> DetailedResponse: - """ - List supported languages. - - Lists all supported languages for translation. The method returns an array of - supported languages with information about each language. Languages are listed in - alphabetical order by language code (for example, `af`, `ar`). In addition to - basic information about each language, the response indicates whether the language - is `supported_as_source` for translation and `supported_as_target` for - translation. It also lists whether the language is `identifiable`. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Languages` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_languages') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/languages' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Translation - ######################### - - def translate(self, - text: List[str], - *, - model_id: str = None, - source: str = None, - target: str = None, - **kwargs) -> DetailedResponse: - """ - Translate. - - Translates the input text from the source language to the target language. Specify - a model ID that indicates the source and target languages, or specify the source - and target languages individually. You can omit the source language to have the - service attempt to detect the language from the input text. If you omit the source - language, the request must contain sufficient input text for the service to - identify the source language. - You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. - All input text must be encoded in UTF-8 format. - - :param List[str] text: Input text in UTF-8 encoding. Submit a maximum of 50 - KB (51,200 bytes) of text with a single request. Multiple elements result - in multiple translations in the response. - :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and - is required if you use a custom model. If no model ID is specified, you - must specify at least a target language. - :param str source: (optional) Language code that specifies the language of - the input text. If omitted, the service derives the source language from - the input text. The input must contain sufficient text for the service to - identify the language reliably. - :param str target: (optional) Language code that specifies the target - language for translation. Required if model ID is not specified. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationResult` object - """ - - if text is None: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'text': text, - 'model_id': model_id, - 'source': source, - 'target': target - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data, ensure_ascii=False).encode('utf-8') - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/translate' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Identification - ######################### - - def list_identifiable_languages(self, **kwargs) -> DetailedResponse: - """ - List identifiable languages. - - Lists the languages that the service can identify. Returns the language code (for - example, `en` for English or `es` for Spanish) and name of each language. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `IdentifiableLanguages` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_identifiable_languages') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/identifiable_languages' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: - """ - Identify language. - - Identifies the language of the input text. - - :param str text: Input text in UTF-8 format. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `IdentifiedLanguages` object - """ - - if text is None: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='identify') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = text - headers['content-type'] = 'text/plain' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/identify' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Models - ######################### - - def list_models(self, - *, - source: str = None, - target: str = None, - default: bool = None, - **kwargs) -> DetailedResponse: - """ - List models. - - Lists available translation models. - - :param str source: (optional) Specify a language code to filter results by - source language. - :param str target: (optional) Specify a language code to filter results by - target language. - :param bool default: (optional) If the `default` parameter isn't specified, - the service returns all models (default and non-default) for each language - pair. To return only default models, set this parameter to `true`. To - return only non-default models, set this parameter to `false`. There is - exactly one default model, the IBM-provided base model, per language pair. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModels` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_models') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'source': source, - 'target': target, - 'default': default - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def create_model(self, - base_model_id: str, - *, - forced_glossary: BinaryIO = None, - parallel_corpus: BinaryIO = None, - name: str = None, - **kwargs) -> DetailedResponse: - """ - Create model. - - Uploads training files to customize a translation model. You can customize a model - with a forced glossary or with a parallel corpus: - * Use a *forced glossary* to force certain terms and phrases to be translated in a - specific way. You can upload only a single forced glossary file for a model. The - size of a forced glossary file for a custom model is limited to 10 MB. - * Use a *parallel corpus* when you want your custom model to learn from general - translation patterns in parallel sentences in your samples. What your model learns - from a parallel corpus can improve translation results for input text that the - model has not been trained on. You can upload multiple parallel corpora files with - a request. To successfully train with parallel corpora, the corpora files must - contain a cumulative total of at least 5000 parallel sentences. The cumulative - size of all uploaded corpus files for a custom model is limited to 250 MB. - Depending on the type of customization and the size of the uploaded files, - training time can range from minutes for a glossary to several hours for a large - parallel corpus. To create a model that is customized with a parallel corpus and a - forced glossary, customize the model with a parallel corpus first and then - customize the resulting model with a forced glossary. - You can create a maximum of 10 custom models per language pair. For more - information about customizing a translation model, including the formatting and - character restrictions for data files, see [Customizing your - model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing). - #### Supported file formats - You can provide your training data for customization in the following document - formats: - * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for - the exchange of translation memories. - * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an - XML specification for the exchange of translation memories. - * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for - aligned sentences and phrases. The first row must have two language codes. The - first column is for the source language code, and the second column is for the - target language code. - * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns - for aligned sentences and phrases. The first row must have two language codes. The - first column is for the source language code, and the second column is for the - target language code. - * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and - phrases. - * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns - for aligned sentences and phrases. The first row contains the language code. - You must encode all text data in UTF-8 format. For more information, see - [Supported document formats for training - data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data). - #### Specifying file formats - You can indicate the format of a file by including the file extension with the - file name. Use the file extensions shown in **Supported file formats**. - Alternatively, you can omit the file extension and specify one of the following - `content-type` specifications for the file: - * **TMX** - `application/x-tmx+xml` - * **XLIFF** - `application/xliff+xml` - * **CSV** - `text/csv` - * **TSV** - `text/tab-separated-values` - * **JSON** - `application/json` - * **Microsoft Excel** - - `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - For example, with `curl`, use the following `content-type` specification to - indicate the format of a CSV file named **glossary**: - `--form "forced_glossary=@glossary;type=text/csv"`. - - :param str base_model_id: The ID of the translation model to use as the - base for customization. To see available models and IDs, use the `List - models` method. Most models that are provided with the service are - customizable. In addition, all models that you create with parallel corpora - customization can be further customized with a forced glossary. - :param BinaryIO forced_glossary: (optional) A file with forced glossary - terms for the source and target languages. The customizations in the file - completely overwrite the domain translation data, including high frequency - or high confidence phrase translations. - You can upload only one glossary file for a custom model, and the glossary - can have a maximum size of 10 MB. A forced glossary must contain single - words or short phrases. For more information, see **Supported file - formats** in the method description. - *With `curl`, use `--form forced_glossary=@{filename}`.*. - :param BinaryIO parallel_corpus: (optional) A file with parallel sentences - for the source and target languages. You can upload multiple parallel - corpus files in one request by repeating the parameter. All uploaded - parallel corpus files combined must contain at least 5000 parallel - sentences to train successfully. You can provide a maximum of 500,000 - parallel sentences across all corpora. - A single entry in a corpus file can contain a maximum of 80 words. All - corpora files for a custom model can have a cumulative maximum size of 250 - MB. For more information, see **Supported file formats** in the method - description. - *With `curl`, use `--form parallel_corpus=@{filename}`.*. - :param str name: (optional) An optional model name that you can use to - identify the model. Valid characters are letters, numbers, dashes, - underscores, spaces, and apostrophes. The maximum length of the name is 32 - characters. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object - """ - - if base_model_id is None: - raise ValueError('base_model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='create_model') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'base_model_id': base_model_id, - 'name': name - } - - form_data = [] - if forced_glossary: - form_data.append(('forced_glossary', (None, forced_glossary, - 'application/octet-stream'))) - if parallel_corpus: - form_data.append(('parallel_corpus', (None, parallel_corpus, - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/models' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: - """ - Delete model. - - Deletes a custom translation model. - - :param str model_id: Model ID of the model to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_model(self, model_id: str, **kwargs) -> DetailedResponse: - """ - Get model details. - - Gets information about a translation model, including training status for custom - models. Use this API call to poll the status of your customization request. A - successfully completed training has a status of `available`. - - :param str model_id: Model ID of the model to get. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Document translation - ######################### - - def list_documents(self, **kwargs) -> DetailedResponse: - """ - List documents. - - Lists documents that have been submitted for translation. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentList` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_documents') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/documents' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def translate_document(self, - file: BinaryIO, - *, - filename: str = None, - file_content_type: str = None, - model_id: str = None, - source: str = None, - target: str = None, - document_id: str = None, - **kwargs) -> DetailedResponse: - """ - Translate document. - - Submit a document for translation. You can submit the document contents in the - `file` parameter, or you can reference a previously submitted document by document - ID. The maximum file size for document translation is - * 20 MB for service instances on the Standard, Advanced, and Premium plans - * 2 MB for service instances on the Lite plan. - - :param BinaryIO file: The contents of the source file to translate. The - maximum file size for document translation is 20 MB for service instances - on the Standard, Advanced, and Premium plans, and 2 MB for service - instances on the Lite plan. For more information, see [Supported file - formats - (Beta)](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and - is required if you use a custom model. If no model ID is specified, you - must specify at least a target language. - :param str source: (optional) Language code that specifies the language of - the source document. If omitted, the service derives the source language - from the input text. The input must contain sufficient text for the service - to identify the language reliably. - :param str target: (optional) Language code that specifies the target - language for translation. Required if model ID is not specified. - :param str document_id: (optional) To use a previously submitted document - as the source for a new translation, enter the `document_id` of the - document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if file is None: - raise ValueError('file must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate_document') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if model_id: - form_data.append(('model_id', (None, model_id, 'text/plain'))) - if source: - form_data.append(('source', (None, source, 'text/plain'))) - if target: - form_data.append(('target', (None, target, 'text/plain'))) - if document_id: - form_data.append(('document_id', (None, document_id, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/documents' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def get_document_status(self, document_id: str, - **kwargs) -> DetailedResponse: - """ - Get document status. - - Gets the translation status of a document. - - :param str document_id: The document ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if document_id is None: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_document_status') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: - """ - Delete document. - - Deletes a document. - - :param str document_id: Document ID of the document to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if document_id is None: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_document') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_translated_document(self, - document_id: str, - *, - accept: str = None, - **kwargs) -> DetailedResponse: - """ - Get translated document. - - Gets the translated document associated with the given document ID. - - :param str document_id: The document ID of the document that was submitted - for translation. - :param str accept: (optional) The type of the response: - application/powerpoint, application/mspowerpoint, application/x-rtf, - application/json, application/xml, application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `BinaryIO` result - """ - - if document_id is None: - raise ValueError('document_id must be provided') - headers = {'Accept': accept} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_translated_document') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}/translated_document'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - -class TranslateDocumentEnums: - """ - Enums for translate_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_POWERPOINT = 'application/powerpoint' - APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_JSON = 'application/json' - APPLICATION_XML = 'application/xml' - APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_PDF = 'application/pdf' - APPLICATION_RTF = 'application/rtf' - TEXT_HTML = 'text/html' - TEXT_JSON = 'text/json' - TEXT_PLAIN = 'text/plain' - TEXT_RICHTEXT = 'text/richtext' - TEXT_RTF = 'text/rtf' - TEXT_SBV = 'text/sbv' - TEXT_SRT = 'text/srt' - TEXT_VTT = 'text/vtt' - TEXT_XML = 'text/xml' - - -class GetTranslatedDocumentEnums: - """ - Enums for get_translated_document parameters. - """ - - class Accept(str, Enum): - """ - The type of the response: application/powerpoint, application/mspowerpoint, - application/x-rtf, application/json, application/xml, application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. - """ - APPLICATION_POWERPOINT = 'application/powerpoint' - APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_JSON = 'application/json' - APPLICATION_XML = 'application/xml' - APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_PDF = 'application/pdf' - APPLICATION_RTF = 'application/rtf' - TEXT_HTML = 'text/html' - TEXT_JSON = 'text/json' - TEXT_PLAIN = 'text/plain' - TEXT_RICHTEXT = 'text/richtext' - TEXT_RTF = 'text/rtf' - TEXT_XML = 'text/xml' - - -############################################################################## -# Models -############################################################################## - - -class DeleteModelResult(): - """ - DeleteModelResult. - - :attr str status: "OK" indicates that the model was successfully deleted. - """ - - def __init__(self, status: str) -> None: - """ - Initialize a DeleteModelResult object. - - :param str status: "OK" indicates that the model was successfully deleted. - """ - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': - """Initialize a DeleteModelResult object from a json dictionary.""" - args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - else: - raise ValueError( - 'Required property \'status\' not present in DeleteModelResult JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteModelResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteModelResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteModelResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DeleteModelResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentList(): - """ - DocumentList. - - :attr List[DocumentStatus] documents: An array of all previously submitted - documents. - """ - - def __init__(self, documents: List['DocumentStatus']) -> None: - """ - Initialize a DocumentList object. - - :param List[DocumentStatus] documents: An array of all previously submitted - documents. - """ - self.documents = documents - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentList': - """Initialize a DocumentList object from a json dictionary.""" - args = {} - if 'documents' in _dict: - args['documents'] = [ - DocumentStatus.from_dict(x) for x in _dict.get('documents') - ] - else: - raise ValueError( - 'Required property \'documents\' not present in DocumentList JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentList object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x.to_dict() for x in self.documents] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentList') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DocumentList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentStatus(): - """ - Document information, including translation status. - - :attr str document_id: System generated ID identifying a document being - translated using one specific translation model. - :attr str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :attr str status: The status of the translation job associated with a submitted - document. - :attr str model_id: A globally unique string that identifies the underlying - model that is used for translation. - :attr str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be absent or - an empty string. - :attr str source: Translation source language code. - :attr float detected_language_confidence: (optional) A score between 0 and 1 - indicating the confidence of source language detection. A higher value indicates - greater confidence. This is returned only when the service automatically detects - the source language. - :attr str target: Translation target language code. - :attr datetime created: The time when the document was submitted. - :attr datetime completed: (optional) The time when the translation completed. - :attr int word_count: (optional) An estimate of the number of words in the - source document. Returned only if `status` is `available`. - :attr int character_count: (optional) The number of characters in the source - document, present only if status=available. - """ - - def __init__(self, - document_id: str, - filename: str, - status: str, - model_id: str, - source: str, - target: str, - created: datetime, - *, - base_model_id: str = None, - detected_language_confidence: float = None, - completed: datetime = None, - word_count: int = None, - character_count: int = None) -> None: - """ - Initialize a DocumentStatus object. - - :param str document_id: System generated ID identifying a document being - translated using one specific translation model. - :param str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :param str status: The status of the translation job associated with a - submitted document. - :param str model_id: A globally unique string that identifies the - underlying model that is used for translation. - :param str source: Translation source language code. - :param str target: Translation target language code. - :param datetime created: The time when the document was submitted. - :param str base_model_id: (optional) Model ID of the base model that was - used to customize the model. If the model is not a custom model, this will - be absent or an empty string. - :param float detected_language_confidence: (optional) A score between 0 and - 1 indicating the confidence of source language detection. A higher value - indicates greater confidence. This is returned only when the service - automatically detects the source language. - :param datetime completed: (optional) The time when the translation - completed. - :param int word_count: (optional) An estimate of the number of words in the - source document. Returned only if `status` is `available`. - :param int character_count: (optional) The number of characters in the - source document, present only if status=available. - """ - self.document_id = document_id - self.filename = filename - self.status = status - self.model_id = model_id - self.base_model_id = base_model_id - self.source = source - self.detected_language_confidence = detected_language_confidence - self.target = target - self.created = created - self.completed = completed - self.word_count = word_count - self.character_count = character_count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentStatus': - """Initialize a DocumentStatus object from a json dictionary.""" - args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - else: - raise ValueError( - 'Required property \'document_id\' not present in DocumentStatus JSON' - ) - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - else: - raise ValueError( - 'Required property \'filename\' not present in DocumentStatus JSON' - ) - if 'status' in _dict: - args['status'] = _dict.get('status') - else: - raise ValueError( - 'Required property \'status\' not present in DocumentStatus JSON' - ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - else: - raise ValueError( - 'Required property \'model_id\' not present in DocumentStatus JSON' - ) - if 'base_model_id' in _dict: - args['base_model_id'] = _dict.get('base_model_id') - if 'source' in _dict: - args['source'] = _dict.get('source') - else: - raise ValueError( - 'Required property \'source\' not present in DocumentStatus JSON' - ) - if 'detected_language_confidence' in _dict: - args['detected_language_confidence'] = _dict.get( - 'detected_language_confidence') - if 'target' in _dict: - args['target'] = _dict.get('target') - else: - raise ValueError( - 'Required property \'target\' not present in DocumentStatus JSON' - ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - else: - raise ValueError( - 'Required property \'created\' not present in DocumentStatus JSON' - ) - if 'completed' in _dict: - args['completed'] = string_to_datetime(_dict.get('completed')) - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') - if 'character_count' in _dict: - args['character_count'] = _dict.get('character_count') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentStatus object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'base_model_id') and self.base_model_id is not None: - _dict['base_model_id'] = self.base_model_id - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'detected_language_confidence' - ) and self.detected_language_confidence is not None: - _dict[ - 'detected_language_confidence'] = self.detected_language_confidence - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'completed') and self.completed is not None: - _dict['completed'] = datetime_to_string(self.completed) - if hasattr(self, 'word_count') and self.word_count is not None: - _dict['word_count'] = self.word_count - if hasattr(self, - 'character_count') and self.character_count is not None: - _dict['character_count'] = self.character_count - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentStatus') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'DocumentStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the translation job associated with a submitted document. - """ - PROCESSING = 'processing' - AVAILABLE = 'available' - FAILED = 'failed' - - -class IdentifiableLanguage(): - """ - IdentifiableLanguage. - - :attr str language: The language code for an identifiable language. - :attr str name: The name of the identifiable language. - """ - - def __init__(self, language: str, name: str) -> None: - """ - Initialize a IdentifiableLanguage object. - - :param str language: The language code for an identifiable language. - :param str name: The name of the identifiable language. - """ - self.language = language - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': - """Initialize a IdentifiableLanguage object from a json dictionary.""" - args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - else: - raise ValueError( - 'Required property \'language\' not present in IdentifiableLanguage JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in IdentifiableLanguage JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiableLanguage object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IdentifiableLanguage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiableLanguage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'IdentifiableLanguage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiableLanguages(): - """ - IdentifiableLanguages. - - :attr List[IdentifiableLanguage] languages: A list of all languages that the - service can identify. - """ - - def __init__(self, languages: List['IdentifiableLanguage']) -> None: - """ - Initialize a IdentifiableLanguages object. - - :param List[IdentifiableLanguage] languages: A list of all languages that - the service can identify. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': - """Initialize a IdentifiableLanguages object from a json dictionary.""" - args = {} - if 'languages' in _dict: - args['languages'] = [ - IdentifiableLanguage.from_dict(x) - for x in _dict.get('languages') - ] - else: - raise ValueError( - 'Required property \'languages\' not present in IdentifiableLanguages JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiableLanguages object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IdentifiableLanguages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiableLanguages') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'IdentifiableLanguages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiedLanguage(): - """ - IdentifiedLanguage. - - :attr str language: The language code for an identified language. - :attr float confidence: The confidence score for the identified language. - """ - - def __init__(self, language: str, confidence: float) -> None: - """ - Initialize a IdentifiedLanguage object. - - :param str language: The language code for an identified language. - :param float confidence: The confidence score for the identified language. - """ - self.language = language - self.confidence = confidence - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': - """Initialize a IdentifiedLanguage object from a json dictionary.""" - args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - else: - raise ValueError( - 'Required property \'language\' not present in IdentifiedLanguage JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in IdentifiedLanguage JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiedLanguage object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IdentifiedLanguage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiedLanguage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'IdentifiedLanguage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiedLanguages(): - """ - IdentifiedLanguages. - - :attr List[IdentifiedLanguage] languages: A ranking of identified languages with - confidence scores. - """ - - def __init__(self, languages: List['IdentifiedLanguage']) -> None: - """ - Initialize a IdentifiedLanguages object. - - :param List[IdentifiedLanguage] languages: A ranking of identified - languages with confidence scores. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': - """Initialize a IdentifiedLanguages object from a json dictionary.""" - args = {} - if 'languages' in _dict: - args['languages'] = [ - IdentifiedLanguage.from_dict(x) for x in _dict.get('languages') - ] - else: - raise ValueError( - 'Required property \'languages\' not present in IdentifiedLanguages JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiedLanguages object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IdentifiedLanguages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiedLanguages') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'IdentifiedLanguages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Language(): - """ - Response payload for languages. - - :attr str language: (optional) The language code for the language (for example, - `af`). - :attr str language_name: (optional) The name of the language in English (for - example, `Afrikaans`). - :attr str native_language_name: (optional) The native name of the language (for - example, `Afrikaans`). - :attr str country_code: (optional) The country code for the language (for - example, `ZA` for South Africa). - :attr bool words_separated: (optional) Indicates whether words of the language - are separated by whitespace: `true` if the words are separated; `false` - otherwise. - :attr str direction: (optional) Indicates the direction of the language: - `right_to_left` or `left_to_right`. - :attr bool supported_as_source: (optional) Indicates whether the language can be - used as the source for translation: `true` if the language can be used as the - source; `false` otherwise. - :attr bool supported_as_target: (optional) Indicates whether the language can be - used as the target for translation: `true` if the language can be used as the - target; `false` otherwise. - :attr bool identifiable: (optional) Indicates whether the language supports - automatic detection: `true` if the language can be detected automatically; - `false` otherwise. - """ - - def __init__(self, - *, - language: str = None, - language_name: str = None, - native_language_name: str = None, - country_code: str = None, - words_separated: bool = None, - direction: str = None, - supported_as_source: bool = None, - supported_as_target: bool = None, - identifiable: bool = None) -> None: - """ - Initialize a Language object. - - :param str language: (optional) The language code for the language (for - example, `af`). - :param str language_name: (optional) The name of the language in English - (for example, `Afrikaans`). - :param str native_language_name: (optional) The native name of the language - (for example, `Afrikaans`). - :param str country_code: (optional) The country code for the language (for - example, `ZA` for South Africa). - :param bool words_separated: (optional) Indicates whether words of the - language are separated by whitespace: `true` if the words are separated; - `false` otherwise. - :param str direction: (optional) Indicates the direction of the language: - `right_to_left` or `left_to_right`. - :param bool supported_as_source: (optional) Indicates whether the language - can be used as the source for translation: `true` if the language can be - used as the source; `false` otherwise. - :param bool supported_as_target: (optional) Indicates whether the language - can be used as the target for translation: `true` if the language can be - used as the target; `false` otherwise. - :param bool identifiable: (optional) Indicates whether the language - supports automatic detection: `true` if the language can be detected - automatically; `false` otherwise. - """ - self.language = language - self.language_name = language_name - self.native_language_name = native_language_name - self.country_code = country_code - self.words_separated = words_separated - self.direction = direction - self.supported_as_source = supported_as_source - self.supported_as_target = supported_as_target - self.identifiable = identifiable - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Language': - """Initialize a Language object from a json dictionary.""" - args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'language_name' in _dict: - args['language_name'] = _dict.get('language_name') - if 'native_language_name' in _dict: - args['native_language_name'] = _dict.get('native_language_name') - if 'country_code' in _dict: - args['country_code'] = _dict.get('country_code') - if 'words_separated' in _dict: - args['words_separated'] = _dict.get('words_separated') - if 'direction' in _dict: - args['direction'] = _dict.get('direction') - if 'supported_as_source' in _dict: - args['supported_as_source'] = _dict.get('supported_as_source') - if 'supported_as_target' in _dict: - args['supported_as_target'] = _dict.get('supported_as_target') - if 'identifiable' in _dict: - args['identifiable'] = _dict.get('identifiable') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Language object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'language_name') and self.language_name is not None: - _dict['language_name'] = self.language_name - if hasattr(self, 'native_language_name' - ) and self.native_language_name is not None: - _dict['native_language_name'] = self.native_language_name - if hasattr(self, 'country_code') and self.country_code is not None: - _dict['country_code'] = self.country_code - if hasattr(self, - 'words_separated') and self.words_separated is not None: - _dict['words_separated'] = self.words_separated - if hasattr(self, 'direction') and self.direction is not None: - _dict['direction'] = self.direction - if hasattr( - self, - 'supported_as_source') and self.supported_as_source is not None: - _dict['supported_as_source'] = self.supported_as_source - if hasattr( - self, - 'supported_as_target') and self.supported_as_target is not None: - _dict['supported_as_target'] = self.supported_as_target - if hasattr(self, 'identifiable') and self.identifiable is not None: - _dict['identifiable'] = self.identifiable - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Language object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Language') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Language') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Languages(): - """ - The response type for listing supported languages. - - :attr List[Language] languages: An array of supported languages with information - about each language. - """ - - def __init__(self, languages: List['Language']) -> None: - """ - Initialize a Languages object. - - :param List[Language] languages: An array of supported languages with - information about each language. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Languages': - """Initialize a Languages object from a json dictionary.""" - args = {} - if 'languages' in _dict: - args['languages'] = [ - Language.from_dict(x) for x in _dict.get('languages') - ] - else: - raise ValueError( - 'Required property \'languages\' not present in Languages JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Languages object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Languages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Languages') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Languages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Translation(): - """ - Translation. - - :attr str translation: Translation output in UTF-8. - """ - - def __init__(self, translation: str) -> None: - """ - Initialize a Translation object. - - :param str translation: Translation output in UTF-8. - """ - self.translation = translation - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Translation': - """Initialize a Translation object from a json dictionary.""" - args = {} - if 'translation' in _dict: - args['translation'] = _dict.get('translation') - else: - raise ValueError( - 'Required property \'translation\' not present in Translation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Translation object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'translation') and self.translation is not None: - _dict['translation'] = self.translation - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Translation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Translation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Translation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TranslationModel(): - """ - Response payload for models. - - :attr str model_id: A globally unique string that identifies the underlying - model that is used for translation. - :attr str name: (optional) Optional name that can be specified when the model is - created. - :attr str source: (optional) Translation source language code. - :attr str target: (optional) Translation target language code. - :attr str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be an empty - string. - :attr str domain: (optional) The domain of the translation model. - :attr bool customizable: (optional) Whether this model can be used as a base for - customization. Customized models are not further customizable, and some base - models are not customizable. - :attr bool default_model: (optional) Whether or not the model is a default - model. A default model is the model for a given language pair that will be used - when that language pair is specified in the source and target parameters. - :attr str owner: (optional) Either an empty string, indicating the model is not - a custom model, or the ID of the service instance that created the model. - :attr str status: (optional) Availability of a model. - """ - - def __init__(self, - model_id: str, - *, - name: str = None, - source: str = None, - target: str = None, - base_model_id: str = None, - domain: str = None, - customizable: bool = None, - default_model: bool = None, - owner: str = None, - status: str = None) -> None: - """ - Initialize a TranslationModel object. - - :param str model_id: A globally unique string that identifies the - underlying model that is used for translation. - :param str name: (optional) Optional name that can be specified when the - model is created. - :param str source: (optional) Translation source language code. - :param str target: (optional) Translation target language code. - :param str base_model_id: (optional) Model ID of the base model that was - used to customize the model. If the model is not a custom model, this will - be an empty string. - :param str domain: (optional) The domain of the translation model. - :param bool customizable: (optional) Whether this model can be used as a - base for customization. Customized models are not further customizable, and - some base models are not customizable. - :param bool default_model: (optional) Whether or not the model is a default - model. A default model is the model for a given language pair that will be - used when that language pair is specified in the source and target - parameters. - :param str owner: (optional) Either an empty string, indicating the model - is not a custom model, or the ID of the service instance that created the - model. - :param str status: (optional) Availability of a model. - """ - self.model_id = model_id - self.name = name - self.source = source - self.target = target - self.base_model_id = base_model_id - self.domain = domain - self.customizable = customizable - self.default_model = default_model - self.owner = owner - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationModel': - """Initialize a TranslationModel object from a json dictionary.""" - args = {} - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - else: - raise ValueError( - 'Required property \'model_id\' not present in TranslationModel JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'target' in _dict: - args['target'] = _dict.get('target') - if 'base_model_id' in _dict: - args['base_model_id'] = _dict.get('base_model_id') - if 'domain' in _dict: - args['domain'] = _dict.get('domain') - if 'customizable' in _dict: - args['customizable'] = _dict.get('customizable') - if 'default_model' in _dict: - args['default_model'] = _dict.get('default_model') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'status' in _dict: - args['status'] = _dict.get('status') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TranslationModel object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target - if hasattr(self, 'base_model_id') and self.base_model_id is not None: - _dict['base_model_id'] = self.base_model_id - if hasattr(self, 'domain') and self.domain is not None: - _dict['domain'] = self.domain - if hasattr(self, 'customizable') and self.customizable is not None: - _dict['customizable'] = self.customizable - if hasattr(self, 'default_model') and self.default_model is not None: - _dict['default_model'] = self.default_model - if hasattr(self, 'owner') and self.owner is not None: - _dict['owner'] = self.owner - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TranslationModel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TranslationModel') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TranslationModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Availability of a model. - """ - UPLOADING = 'uploading' - UPLOADED = 'uploaded' - DISPATCHING = 'dispatching' - QUEUED = 'queued' - TRAINING = 'training' - TRAINED = 'trained' - PUBLISHING = 'publishing' - AVAILABLE = 'available' - DELETED = 'deleted' - ERROR = 'error' - - -class TranslationModels(): - """ - The response type for listing existing translation models. - - :attr List[TranslationModel] models: An array of available models. - """ - - def __init__(self, models: List['TranslationModel']) -> None: - """ - Initialize a TranslationModels object. - - :param List[TranslationModel] models: An array of available models. - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationModels': - """Initialize a TranslationModels object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [ - TranslationModel.from_dict(x) for x in _dict.get('models') - ] - else: - raise ValueError( - 'Required property \'models\' not present in TranslationModels JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TranslationModels object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TranslationModels object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TranslationModels') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TranslationModels') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TranslationResult(): - """ - TranslationResult. - - :attr int word_count: An estimate of the number of words in the input text. - :attr int character_count: Number of characters in the input text. - :attr str detected_language: (optional) The language code of the source text if - the source language was automatically detected. - :attr float detected_language_confidence: (optional) A score between 0 and 1 - indicating the confidence of source language detection. A higher value indicates - greater confidence. This is returned only when the service automatically detects - the source language. - :attr List[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. - """ - - def __init__(self, - word_count: int, - character_count: int, - translations: List['Translation'], - *, - detected_language: str = None, - detected_language_confidence: float = None) -> None: - """ - Initialize a TranslationResult object. - - :param int word_count: An estimate of the number of words in the input - text. - :param int character_count: Number of characters in the input text. - :param List[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. - :param str detected_language: (optional) The language code of the source - text if the source language was automatically detected. - :param float detected_language_confidence: (optional) A score between 0 and - 1 indicating the confidence of source language detection. A higher value - indicates greater confidence. This is returned only when the service - automatically detects the source language. - """ - self.word_count = word_count - self.character_count = character_count - self.detected_language = detected_language - self.detected_language_confidence = detected_language_confidence - self.translations = translations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationResult': - """Initialize a TranslationResult object from a json dictionary.""" - args = {} - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') - else: - raise ValueError( - 'Required property \'word_count\' not present in TranslationResult JSON' - ) - if 'character_count' in _dict: - args['character_count'] = _dict.get('character_count') - else: - raise ValueError( - 'Required property \'character_count\' not present in TranslationResult JSON' - ) - if 'detected_language' in _dict: - args['detected_language'] = _dict.get('detected_language') - if 'detected_language_confidence' in _dict: - args['detected_language_confidence'] = _dict.get( - 'detected_language_confidence') - if 'translations' in _dict: - args['translations'] = [ - Translation.from_dict(x) for x in _dict.get('translations') - ] - else: - raise ValueError( - 'Required property \'translations\' not present in TranslationResult JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TranslationResult object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'word_count') and self.word_count is not None: - _dict['word_count'] = self.word_count - if hasattr(self, - 'character_count') and self.character_count is not None: - _dict['character_count'] = self.character_count - if hasattr(self, - 'detected_language') and self.detected_language is not None: - _dict['detected_language'] = self.detected_language - if hasattr(self, 'detected_language_confidence' - ) and self.detected_language_confidence is not None: - _dict[ - 'detected_language_confidence'] = self.detected_language_confidence - if hasattr(self, 'translations') and self.translations is not None: - _dict['translations'] = [x.to_dict() for x in self.translations] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TranslationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TranslationResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'TranslationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 0ae9da787..c3561e275 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2017, 2022. +# (C) Copyright IBM Corp. 2017, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -31,7 +31,7 @@ from datetime import datetime from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -62,7 +62,7 @@ def __init__( Construct a new client for the Natural Language Understanding service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-08-01`. + Specify dates in YYYY-MM-DD format. The current version is `2022-04-07`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -83,19 +83,21 @@ def __init__( # Analyze ######################### - def analyze(self, - features: 'Features', - *, - text: str = None, - html: str = None, - url: str = None, - clean: bool = None, - xpath: str = None, - fallback_to_raw: bool = None, - return_analyzed_text: bool = None, - language: str = None, - limit_text_characters: int = None, - **kwargs) -> DetailedResponse: + def analyze( + self, + features: 'Features', + *, + text: Optional[str] = None, + html: Optional[str] = None, + url: Optional[str] = None, + clean: Optional[bool] = None, + xpath: Optional[str] = None, + fallback_to_raw: Optional[bool] = None, + return_analyzed_text: Optional[bool] = None, + language: Optional[str] = None, + limit_text_characters: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Analyze text. @@ -111,7 +113,6 @@ def analyze(self, - Semantic roles - Sentiment - Syntax - - Summarization (Experimental) If a language for the input text is not specified with the `language` parameter, the service [automatically detects the language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -151,12 +152,16 @@ def analyze(self, raise ValueError('features must be provided') features = convert_model(features) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='analyze') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='analyze', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'features': features, @@ -168,7 +173,7 @@ def analyze(self, 'fallback_to_raw': fallback_to_raw, 'return_analyzed_text': return_analyzed_text, 'language': language, - 'limit_text_characters': limit_text_characters + 'limit_text_characters': limit_text_characters, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -176,14 +181,17 @@ def analyze(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/analyze' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -192,7 +200,10 @@ def analyze(self, # Manage models ######################### - def list_models(self, **kwargs) -> DetailedResponse: + def list_models( + self, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -206,27 +217,38 @@ def list_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: + def delete_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete model. @@ -238,298 +260,35 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Manage sentiment models - ######################### - - def create_sentiment_model(self, - language: str, - training_data: BinaryIO, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: - """ - Create sentiment model. - - (Beta) Creates a custom sentiment model by uploading training data and associated - metadata. The model begins the training and deploying process and is ready to use - when the `status` is `available`. - - :param str language: The 2-letter language code of this model. - :param BinaryIO training_data: Training data in CSV format. For more - information, see [Sentiment training data - requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). - :param str name: (optional) An optional name for the model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if language is None: - raise ValueError('language must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - form_data.append(('language', (None, language, 'text/plain'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - if name: - form_data.append(('name', (None, name, 'text/plain'))) - if description: - form_data.append(('description', (None, description, 'text/plain'))) - if model_version: - form_data.append( - ('model_version', (None, model_version, 'text/plain'))) - if workspace_id: - form_data.append( - ('workspace_id', (None, workspace_id, 'text/plain'))) - if version_description: - form_data.append(('version_description', (None, version_description, - 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/models/sentiment' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_sentiment_models(self, **kwargs) -> DetailedResponse: - """ - List sentiment models. - - (Beta) Returns all custom sentiment models associated with this service instance. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListSentimentModelsResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_sentiment_models') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/models/sentiment' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: - """ - Get sentiment model details. - - (Beta) Returns the status of the sentiment model with the given model ID. - - :param str model_id: ID of the model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_sentiment_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: - """ - Update sentiment model. - - (Beta) Overwrites the training data associated with this custom sentiment model - and retrains the model. The new model replaces the current deployment. - - :param str model_id: ID of the model. - :param str language: The 2-letter language code of this model. - :param BinaryIO training_data: Training data in CSV format. For more - information, see [Sentiment training data - requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). - :param str name: (optional) An optional name for the model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - if language is None: - raise ValueError('language must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - form_data.append(('language', (None, language, 'text/plain'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - if name: - form_data.append(('name', (None, name, 'text/plain'))) - if description: - form_data.append(('description', (None, description, 'text/plain'))) - if model_version: - form_data.append( - ('model_version', (None, model_version, 'text/plain'))) - if workspace_id: - form_data.append( - ('workspace_id', (None, workspace_id, 'text/plain'))) - if version_description: - form_data.append(('version_description', (None, version_description, - 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_sentiment_model(self, model_id: str, - **kwargs) -> DetailedResponse: - """ - Delete sentiment model. - - (Beta) Un-deploys the custom sentiment model with the given model ID and deletes - all associated customer data, including any training data or binary artifacts. - - :param str model_id: ID of the model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -538,17 +297,20 @@ def delete_sentiment_model(self, model_id: str, # Manage categories models ######################### - def create_categories_model(self, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def create_categories_model( + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = None, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create categories model. @@ -563,6 +325,8 @@ def create_categories_model(self, :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -573,17 +337,21 @@ def create_categories_model(self, :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_categories_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -592,6 +360,9 @@ def create_categories_model(self, 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -606,19 +377,25 @@ def create_categories_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/categories' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def list_categories_models(self, **kwargs) -> DetailedResponse: + def list_categories_models( + self, + **kwargs, + ) -> DetailedResponse: """ List categories models. @@ -630,27 +407,38 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_categories_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_categories_models', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/categories' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_categories_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get categories model details. @@ -662,44 +450,54 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_categories_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_categories_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def update_categories_model( + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = None, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update categories model. @@ -714,6 +512,8 @@ def update_categories_model(self, :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -724,19 +524,23 @@ def update_categories_model(self, :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_categories_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -745,6 +549,9 @@ def update_categories_model(self, 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -759,23 +566,29 @@ def update_categories_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_categories_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def delete_categories_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete categories model. @@ -788,28 +601,35 @@ def delete_categories_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_categories_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -818,17 +638,22 @@ def delete_categories_model(self, model_id: str, # Manage classifications models ######################### - def create_classifications_model(self, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def create_classifications_model( + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = None, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + training_parameters: Optional[ + 'ClassificationsTrainingParameters'] = None, + **kwargs, + ) -> DetailedResponse: """ Create classifications model. @@ -843,17 +668,22 @@ def create_classifications_model(self, :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version_description: (optional) The description of the version. + :param ClassificationsTrainingParameters training_parameters: (optional) + Optional classifications training parameters along with model train + requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -861,10 +691,13 @@ def create_classifications_model(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='create_classifications_model') + operation_id='create_classifications_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -873,6 +706,9 @@ def create_classifications_model(self, 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -884,22 +720,32 @@ def create_classifications_model(self, if version_description: form_data.append(('version_description', (None, version_description, 'text/plain'))) + if training_parameters: + form_data.append( + ('training_parameters', (None, json.dumps(training_parameters), + 'application/json'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/classifications' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def list_classifications_models(self, **kwargs) -> DetailedResponse: + def list_classifications_models( + self, + **kwargs, + ) -> DetailedResponse: """ List classifications models. @@ -914,26 +760,35 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='list_classifications_models') + operation_id='list_classifications_models', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/classifications' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_classifications_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def get_classifications_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get classifications model details. @@ -945,44 +800,56 @@ def get_classifications_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_classifications_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_classifications_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_classifications_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def update_classifications_model( + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = None, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + training_parameters: Optional[ + 'ClassificationsTrainingParameters'] = None, + **kwargs, + ) -> DetailedResponse: """ Update classifications model. @@ -997,19 +864,24 @@ def update_classifications_model(self, :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version_description: (optional) The description of the version. + :param ClassificationsTrainingParameters training_parameters: (optional) + Optional classifications training parameters along with model train + requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -1017,10 +889,13 @@ def update_classifications_model(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='update_classifications_model') + operation_id='update_classifications_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -1029,6 +904,9 @@ def update_classifications_model(self, 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -1040,26 +918,36 @@ def update_classifications_model(self, if version_description: form_data.append(('version_description', (None, version_description, 'text/plain'))) + if training_parameters: + form_data.append( + ('training_parameters', (None, json.dumps(training_parameters), + 'application/json'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_classifications_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def delete_classifications_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete classifications model. @@ -1072,29 +960,35 @@ def delete_classifications_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='delete_classifications_model') + operation_id='delete_classifications_model', + ) headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1109,6 +1003,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -1122,6 +1017,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -1135,6 +1031,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -1148,6 +1045,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -1157,55 +1055,57 @@ class TrainingDataContentType(str, Enum): ############################################################################## -class AnalysisResults(): +class AnalysisResults: """ Results of the analysis, organized by feature. - :attr str language: (optional) Language used to analyze the text. - :attr str analyzed_text: (optional) Text that was used in the analysis. - :attr str retrieved_url: (optional) URL of the webpage that was analyzed. - :attr AnalysisResultsUsage usage: (optional) API usage information for the + :param str language: (optional) Language used to analyze the text. + :param str analyzed_text: (optional) Text that was used in the analysis. + :param str retrieved_url: (optional) URL of the webpage that was analyzed. + :param AnalysisResultsUsage usage: (optional) API usage information for the request. - :attr List[ConceptsResult] concepts: (optional) The general concepts referenced + :param List[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. - :attr List[EntitiesResult] entities: (optional) The entities detected in the + :param List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed + :param List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :attr List[CategoriesResult] categories: (optional) The categories that the + :param List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. - :attr List[ClassificationsResult] classifications: (optional) The + :param List[ClassificationsResult] classifications: (optional) The classifications assigned to the analyzed text. - :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. - :attr FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the - author and the title of the page. - :attr List[RelationsResult] relations: (optional) The relationships between + :param FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as + the author and the title of the page. + :param List[RelationsResult] relations: (optional) The relationships between entities in the content. - :attr List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into - `subject`, `action`, and `object` form. - :attr SentimentResult sentiment: (optional) The sentiment of the content. - :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax + :param List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed + into `subject`, `action`, and `object` form. + :param SentimentResult sentiment: (optional) The sentiment of the content. + :param SyntaxResult syntax: (optional) Tokens and sentences returned from syntax analysis. """ - def __init__(self, - *, - language: str = None, - analyzed_text: str = None, - retrieved_url: str = None, - usage: 'AnalysisResultsUsage' = None, - concepts: List['ConceptsResult'] = None, - entities: List['EntitiesResult'] = None, - keywords: List['KeywordsResult'] = None, - categories: List['CategoriesResult'] = None, - classifications: List['ClassificationsResult'] = None, - emotion: 'EmotionResult' = None, - metadata: 'FeaturesResultsMetadata' = None, - relations: List['RelationsResult'] = None, - semantic_roles: List['SemanticRolesResult'] = None, - sentiment: 'SentimentResult' = None, - syntax: 'SyntaxResult' = None) -> None: + def __init__( + self, + *, + language: Optional[str] = None, + analyzed_text: Optional[str] = None, + retrieved_url: Optional[str] = None, + usage: Optional['AnalysisResultsUsage'] = None, + concepts: Optional[List['ConceptsResult']] = None, + entities: Optional[List['EntitiesResult']] = None, + keywords: Optional[List['KeywordsResult']] = None, + categories: Optional[List['CategoriesResult']] = None, + classifications: Optional[List['ClassificationsResult']] = None, + emotion: Optional['EmotionResult'] = None, + metadata: Optional['FeaturesResultsMetadata'] = None, + relations: Optional[List['RelationsResult']] = None, + semantic_roles: Optional[List['SemanticRolesResult']] = None, + sentiment: Optional['SentimentResult'] = None, + syntax: Optional['SyntaxResult'] = None, + ) -> None: """ Initialize a AnalysisResults object. @@ -1256,54 +1156,44 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResults': """Initialize a AnalysisResults object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'analyzed_text' in _dict: - args['analyzed_text'] = _dict.get('analyzed_text') - if 'retrieved_url' in _dict: - args['retrieved_url'] = _dict.get('retrieved_url') - if 'usage' in _dict: - args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) - if 'concepts' in _dict: - args['concepts'] = [ - ConceptsResult.from_dict(x) for x in _dict.get('concepts') - ] - if 'entities' in _dict: - args['entities'] = [ - EntitiesResult.from_dict(x) for x in _dict.get('entities') - ] - if 'keywords' in _dict: - args['keywords'] = [ - KeywordsResult.from_dict(x) for x in _dict.get('keywords') - ] - if 'categories' in _dict: + if (language := _dict.get('language')) is not None: + args['language'] = language + if (analyzed_text := _dict.get('analyzed_text')) is not None: + args['analyzed_text'] = analyzed_text + if (retrieved_url := _dict.get('retrieved_url')) is not None: + args['retrieved_url'] = retrieved_url + if (usage := _dict.get('usage')) is not None: + args['usage'] = AnalysisResultsUsage.from_dict(usage) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = [ConceptsResult.from_dict(v) for v in concepts] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [EntitiesResult.from_dict(v) for v in entities] + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = [KeywordsResult.from_dict(v) for v in keywords] + if (categories := _dict.get('categories')) is not None: args['categories'] = [ - CategoriesResult.from_dict(x) for x in _dict.get('categories') + CategoriesResult.from_dict(v) for v in categories ] - if 'classifications' in _dict: + if (classifications := _dict.get('classifications')) is not None: args['classifications'] = [ - ClassificationsResult.from_dict(x) - for x in _dict.get('classifications') + ClassificationsResult.from_dict(v) for v in classifications ] - if 'emotion' in _dict: - args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) - if 'metadata' in _dict: - args['metadata'] = FeaturesResultsMetadata.from_dict( - _dict.get('metadata')) - if 'relations' in _dict: + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionResult.from_dict(emotion) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = FeaturesResultsMetadata.from_dict(metadata) + if (relations := _dict.get('relations')) is not None: args['relations'] = [ - RelationsResult.from_dict(x) for x in _dict.get('relations') + RelationsResult.from_dict(v) for v in relations ] - if 'semantic_roles' in _dict: + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = [ - SemanticRolesResult.from_dict(x) - for x in _dict.get('semantic_roles') + SemanticRolesResult.from_dict(v) for v in semantic_roles ] - if 'sentiment' in _dict: - args['sentiment'] = SentimentResult.from_dict( - _dict.get('sentiment')) - if 'syntax' in _dict: - args['syntax'] = SyntaxResult.from_dict(_dict.get('syntax')) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = SentimentResult.from_dict(sentiment) + if (syntax := _dict.get('syntax')) is not None: + args['syntax'] = SyntaxResult.from_dict(syntax) return cls(**args) @classmethod @@ -1321,32 +1211,87 @@ def to_dict(self) -> Dict: if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: _dict['retrieved_url'] = self.retrieved_url if hasattr(self, 'usage') and self.usage is not None: - _dict['usage'] = self.usage.to_dict() + if isinstance(self.usage, dict): + _dict['usage'] = self.usage + else: + _dict['usage'] = self.usage.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = [x.to_dict() for x in self.concepts] + concepts_list = [] + for v in self.concepts: + if isinstance(v, dict): + concepts_list.append(v) + else: + concepts_list.append(v.to_dict()) + _dict['concepts'] = concepts_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] + categories_list = [] + for v in self.categories: + if isinstance(v, dict): + categories_list.append(v) + else: + categories_list.append(v.to_dict()) + _dict['categories'] = categories_list if hasattr(self, 'classifications') and self.classifications is not None: - _dict['classifications'] = [ - x.to_dict() for x in self.classifications - ] + classifications_list = [] + for v in self.classifications: + if isinstance(v, dict): + classifications_list.append(v) + else: + classifications_list.append(v.to_dict()) + _dict['classifications'] = classifications_list if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() + if isinstance(self.metadata, dict): + _dict['metadata'] = self.metadata + else: + _dict['metadata'] = self.metadata.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = [x.to_dict() for x in self.relations] + relations_list = [] + for v in self.relations: + if isinstance(v, dict): + relations_list.append(v) + else: + relations_list.append(v.to_dict()) + _dict['relations'] = relations_list if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = [x.to_dict() for x in self.semantic_roles] + semantic_roles_list = [] + for v in self.semantic_roles: + if isinstance(v, dict): + semantic_roles_list.append(v) + else: + semantic_roles_list.append(v.to_dict()) + _dict['semantic_roles'] = semantic_roles_list if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if isinstance(self.syntax, dict): + _dict['syntax'] = self.syntax + else: + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -1368,20 +1313,22 @@ def __ne__(self, other: 'AnalysisResults') -> bool: return not self == other -class AnalysisResultsUsage(): +class AnalysisResultsUsage: """ API usage information for the request. - :attr int features: (optional) Number of features used in the API call. - :attr int text_characters: (optional) Number of text characters processed. - :attr int text_units: (optional) Number of 10,000-character units processed. + :param int features: (optional) Number of features used in the API call. + :param int text_characters: (optional) Number of text characters processed. + :param int text_units: (optional) Number of 10,000-character units processed. """ - def __init__(self, - *, - features: int = None, - text_characters: int = None, - text_units: int = None) -> None: + def __init__( + self, + *, + features: Optional[int] = None, + text_characters: Optional[int] = None, + text_units: Optional[int] = None, + ) -> None: """ Initialize a AnalysisResultsUsage object. @@ -1398,12 +1345,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'text_characters' in _dict: - args['text_characters'] = _dict.get('text_characters') - if 'text_units' in _dict: - args['text_units'] = _dict.get('text_units') + if (features := _dict.get('features')) is not None: + args['features'] = features + if (text_characters := _dict.get('text_characters')) is not None: + args['text_characters'] = text_characters + if (text_units := _dict.get('text_units')) is not None: + args['text_units'] = text_units return cls(**args) @classmethod @@ -1442,14 +1389,18 @@ def __ne__(self, other: 'AnalysisResultsUsage') -> bool: return not self == other -class Author(): +class Author: """ The author of the analyzed content. - :attr str name: (optional) Name of the author. + :param str name: (optional) Name of the author. """ - def __init__(self, *, name: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + ) -> None: """ Initialize a Author object. @@ -1461,8 +1412,8 @@ def __init__(self, *, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Author': """Initialize a Author object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -1496,47 +1447,49 @@ def __ne__(self, other: 'Author') -> bool: return not self == other -class CategoriesModel(): +class CategoriesModel: """ Categories model. - :attr str name: (optional) An optional name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - :attr List[str] features: (optional) The service features that are supported by + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are supported by the custom model. - :attr str status: When the status is `available`, the model is ready to use. - :attr str model_id: Unique model ID. - :attr datetime created: dateTime indicating when the model was created. - :attr List[Notice] notices: (optional) - :attr datetime last_trained: (optional) dateTime of last successful model + :param str status: When the status is `available`, the model is ready to use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model training. - :attr datetime last_deployed: (optional) dateTime of last successful model + :param datetime last_deployed: (optional) dateTime of last successful model deployment. """ - def __init__(self, - language: str, - status: str, - model_id: str, - created: datetime, - *, - name: str = None, - user_metadata: dict = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - features: List[str] = None, - notices: List['Notice'] = None, - last_trained: datetime = None, - last_deployed: datetime = None) -> None: + def __init__( + self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + features: Optional[List[str]] = None, + notices: Optional[List['Notice']] = None, + last_trained: Optional[datetime] = None, + last_deployed: Optional[datetime] = None, + ) -> None: """ Initialize a CategoriesModel object. @@ -1580,53 +1533,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesModel': """Initialize a CategoriesModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (user_metadata := _dict.get('user_metadata')) is not None: + args['user_metadata'] = user_metadata + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in CategoriesModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (features := _dict.get('features')) is not None: + args['features'] = features + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in CategoriesModel JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in CategoriesModel JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in CategoriesModel JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_datetime(last_trained) + if (last_deployed := _dict.get('last_deployed')) is not None: + args['last_deployed'] = string_to_datetime(last_deployed) return cls(**args) @classmethod @@ -1662,7 +1613,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = datetime_to_string(self.last_trained) if hasattr(self, 'last_deployed') and self.last_deployed is not None: @@ -1691,6 +1648,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -1699,14 +1657,18 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class CategoriesModelList(): +class CategoriesModelList: """ List of categories models. - :attr List[CategoriesModel] models: (optional) The categories models. + :param List[CategoriesModel] models: (optional) The categories models. """ - def __init__(self, *, models: List['CategoriesModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['CategoriesModel']] = None, + ) -> None: """ Initialize a CategoriesModelList object. @@ -1718,10 +1680,8 @@ def __init__(self, *, models: List['CategoriesModel'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesModelList': """Initialize a CategoriesModelList object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - CategoriesModel.from_dict(x) for x in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [CategoriesModel.from_dict(v) for v in models] return cls(**args) @classmethod @@ -1733,7 +1693,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -1755,27 +1721,29 @@ def __ne__(self, other: 'CategoriesModelList') -> bool: return not self == other -class CategoriesOptions(): +class CategoriesOptions: """ Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr bool explanation: (optional) Set this to `true` to return explanations for - each categorization. **This is available only for English categories.**. - :attr int limit: (optional) Maximum number of categories to return. - :attr str model: (optional) (Beta) Enter a [custom + :param bool explanation: (optional) Set this to `true` to return explanations + for each categorization. **This is available only for English categories.**. + :param int limit: (optional) Maximum number of categories to return. + :param str model: (optional) (Beta) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard categories model. **This is available only for English categories.**. """ - def __init__(self, - *, - explanation: bool = None, - limit: int = None, - model: str = None) -> None: + def __init__( + self, + *, + explanation: Optional[bool] = None, + limit: Optional[int] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a CategoriesOptions object. @@ -1796,12 +1764,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - if 'explanation' in _dict: - args['explanation'] = _dict.get('explanation') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (explanation := _dict.get('explanation')) is not None: + args['explanation'] = explanation + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -1839,15 +1807,19 @@ def __ne__(self, other: 'CategoriesOptions') -> bool: return not self == other -class CategoriesRelevantText(): +class CategoriesRelevantText: """ Relevant text that contributed to the categorization. - :attr str text: (optional) Text from the analyzed source that supports the + :param str text: (optional) Text from the analyzed source that supports the categorization. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a CategoriesRelevantText object. @@ -1860,8 +1832,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -1895,24 +1867,26 @@ def __ne__(self, other: 'CategoriesRelevantText') -> bool: return not self == other -class CategoriesResult(): +class CategoriesResult: """ A categorization of the analyzed text. - :attr str label: (optional) The path to the category through the multi-level + :param str label: (optional) The path to the category through the multi-level taxonomy hierarchy. For more information about the categories, see [Categories hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). - :attr float score: (optional) Confidence score for the category classification. + :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. - :attr CategoriesResultExplanation explanation: (optional) Information that helps - to explain what contributed to the categories result. + :param CategoriesResultExplanation explanation: (optional) Information that + helps to explain what contributed to the categories result. """ - def __init__(self, - *, - label: str = None, - score: float = None, - explanation: 'CategoriesResultExplanation' = None) -> None: + def __init__( + self, + *, + label: Optional[str] = None, + score: Optional[float] = None, + explanation: Optional['CategoriesResultExplanation'] = None, + ) -> None: """ Initialize a CategoriesResult object. @@ -1933,13 +1907,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResult': """Initialize a CategoriesResult object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'explanation' in _dict: + if (label := _dict.get('label')) is not None: + args['label'] = label + if (score := _dict.get('score')) is not None: + args['score'] = score + if (explanation := _dict.get('explanation')) is not None: args['explanation'] = CategoriesResultExplanation.from_dict( - _dict.get('explanation')) + explanation) return cls(**args) @classmethod @@ -1955,7 +1929,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'explanation') and self.explanation is not None: - _dict['explanation'] = self.explanation.to_dict() + if isinstance(self.explanation, dict): + _dict['explanation'] = self.explanation + else: + _dict['explanation'] = self.explanation.to_dict() return _dict def _to_dict(self): @@ -1977,19 +1954,21 @@ def __ne__(self, other: 'CategoriesResult') -> bool: return not self == other -class CategoriesResultExplanation(): +class CategoriesResultExplanation: """ Information that helps to explain what contributed to the categories result. - :attr List[CategoriesRelevantText] relevant_text: (optional) An array of + :param List[CategoriesRelevantText] relevant_text: (optional) An array of relevant text from the source that contributed to the categorization. The sorted array begins with the phrase that contributed most significantly to the result, followed by phrases that were less and less impactful. """ - def __init__(self, - *, - relevant_text: List['CategoriesRelevantText'] = None) -> None: + def __init__( + self, + *, + relevant_text: Optional[List['CategoriesRelevantText']] = None, + ) -> None: """ Initialize a CategoriesResultExplanation object. @@ -2004,10 +1983,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} - if 'relevant_text' in _dict: + if (relevant_text := _dict.get('relevant_text')) is not None: args['relevant_text'] = [ - CategoriesRelevantText.from_dict(x) - for x in _dict.get('relevant_text') + CategoriesRelevantText.from_dict(v) for v in relevant_text ] return cls(**args) @@ -2020,7 +1998,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'relevant_text') and self.relevant_text is not None: - _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] + relevant_text_list = [] + for v in self.relevant_text: + if isinstance(v, dict): + relevant_text_list.append(v) + else: + relevant_text_list.append(v.to_dict()) + _dict['relevant_text'] = relevant_text_list return _dict def _to_dict(self): @@ -2042,47 +2026,49 @@ def __ne__(self, other: 'CategoriesResultExplanation') -> bool: return not self == other -class ClassificationsModel(): +class ClassificationsModel: """ Classifications model. - :attr str name: (optional) An optional name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - :attr List[str] features: (optional) The service features that are supported by + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are supported by the custom model. - :attr str status: When the status is `available`, the model is ready to use. - :attr str model_id: Unique model ID. - :attr datetime created: dateTime indicating when the model was created. - :attr List[Notice] notices: (optional) - :attr datetime last_trained: (optional) dateTime of last successful model + :param str status: When the status is `available`, the model is ready to use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model training. - :attr datetime last_deployed: (optional) dateTime of last successful model + :param datetime last_deployed: (optional) dateTime of last successful model deployment. """ - def __init__(self, - language: str, - status: str, - model_id: str, - created: datetime, - *, - name: str = None, - user_metadata: dict = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - features: List[str] = None, - notices: List['Notice'] = None, - last_trained: datetime = None, - last_deployed: datetime = None) -> None: + def __init__( + self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + features: Optional[List[str]] = None, + notices: Optional[List['Notice']] = None, + last_trained: Optional[datetime] = None, + last_deployed: Optional[datetime] = None, + ) -> None: """ Initialize a ClassificationsModel object. @@ -2126,53 +2112,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationsModel': """Initialize a ClassificationsModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (user_metadata := _dict.get('user_metadata')) is not None: + args['user_metadata'] = user_metadata + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in ClassificationsModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (features := _dict.get('features')) is not None: + args['features'] = features + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in ClassificationsModel JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in ClassificationsModel JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in ClassificationsModel JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_datetime(last_trained) + if (last_deployed := _dict.get('last_deployed')) is not None: + args['last_deployed'] = string_to_datetime(last_deployed) return cls(**args) @classmethod @@ -2208,7 +2192,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = datetime_to_string(self.last_trained) if hasattr(self, 'last_deployed') and self.last_deployed is not None: @@ -2237,6 +2227,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -2245,14 +2236,18 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class ClassificationsModelList(): +class ClassificationsModelList: """ List of classifications models. - :attr List[ClassificationsModel] models: (optional) The classifications models. + :param List[ClassificationsModel] models: (optional) The classifications models. """ - def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['ClassificationsModel']] = None, + ) -> None: """ Initialize a ClassificationsModelList object. @@ -2265,10 +2260,8 @@ def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsModelList': """Initialize a ClassificationsModelList object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - ClassificationsModel.from_dict(x) for x in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [ClassificationsModel.from_dict(v) for v in models] return cls(**args) @classmethod @@ -2280,7 +2273,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -2302,11 +2301,11 @@ def __ne__(self, other: 'ClassificationsModelList') -> bool: return not self == other -class ClassificationsOptions(): +class ClassificationsOptions: """ Returns text classifications for the content. - :attr str model: (optional) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID of the classifications model to be used. You can analyze tone by using a language-specific model ID. See [Tone analytics @@ -2314,7 +2313,11 @@ class ClassificationsOptions(): for more information. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a ClassificationsOptions object. @@ -2332,8 +2335,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsOptions': """Initialize a ClassificationsOptions object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -2367,19 +2370,21 @@ def __ne__(self, other: 'ClassificationsOptions') -> bool: return not self == other -class ClassificationsResult(): +class ClassificationsResult: """ A classification of the analyzed text. - :attr str class_name: (optional) Classification assigned to the text. - :attr float confidence: (optional) Confidence score for the classification. + :param str class_name: (optional) Classification assigned to the text. + :param float confidence: (optional) Confidence score for the classification. Higher values indicate greater confidence. """ - def __init__(self, - *, - class_name: str = None, - confidence: float = None) -> None: + def __init__( + self, + *, + class_name: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a ClassificationsResult object. @@ -2394,10 +2399,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationsResult': """Initialize a ClassificationsResult object from a json dictionary.""" args = {} - if 'class_name' in _dict: - args['class_name'] = _dict.get('class_name') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (class_name := _dict.get('class_name')) is not None: + args['class_name'] = class_name + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -2433,7 +2438,75 @@ def __ne__(self, other: 'ClassificationsResult') -> bool: return not self == other -class ConceptsOptions(): +class ClassificationsTrainingParameters: + """ + Optional classifications training parameters along with model train requests. + + :param str model_type: (optional) Model type selector to train either a + single_label or a multi_label classifier. + """ + + def __init__( + self, + *, + model_type: Optional[str] = None, + ) -> None: + """ + Initialize a ClassificationsTrainingParameters object. + + :param str model_type: (optional) Model type selector to train either a + single_label or a multi_label classifier. + """ + self.model_type = model_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassificationsTrainingParameters': + """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" + args = {} + if (model_type := _dict.get('model_type')) is not None: + args['model_type'] = model_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'model_type') and self.model_type is not None: + _dict['model_type'] = self.model_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClassificationsTrainingParameters object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassificationsTrainingParameters') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClassificationsTrainingParameters') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelTypeEnum(str, Enum): + """ + Model type selector to train either a single_label or a multi_label classifier. + """ + + SINGLE_LABEL = 'single_label' + MULTI_LABEL = 'multi_label' + + +class ConceptsOptions: """ Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not @@ -2441,10 +2514,14 @@ class ConceptsOptions(): Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr int limit: (optional) Maximum number of concepts to return. + :param int limit: (optional) Maximum number of concepts to return. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a ConceptsOptions object. @@ -2456,8 +2533,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'ConceptsOptions': """Initialize a ConceptsOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -2491,22 +2568,24 @@ def __ne__(self, other: 'ConceptsOptions') -> bool: return not self == other -class ConceptsResult(): +class ConceptsResult: """ The general concepts referenced or alluded to in the analyzed text. - :attr str text: (optional) Name of the concept. - :attr float relevance: (optional) Relevance score between 0 and 1. Higher scores - indicate greater relevance. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + :param str text: (optional) Name of the concept. + :param float relevance: (optional) Relevance score between 0 and 1. Higher + scores indicate greater relevance. + :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. """ - def __init__(self, - *, - text: str = None, - relevance: float = None, - dbpedia_resource: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + relevance: Optional[float] = None, + dbpedia_resource: Optional[str] = None, + ) -> None: """ Initialize a ConceptsResult object. @@ -2524,12 +2603,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ConceptsResult': """Initialize a ConceptsResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'dbpedia_resource' in _dict: - args['dbpedia_resource'] = _dict.get('dbpedia_resource') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (dbpedia_resource := _dict.get('dbpedia_resource')) is not None: + args['dbpedia_resource'] = dbpedia_resource return cls(**args) @classmethod @@ -2568,14 +2647,18 @@ def __ne__(self, other: 'ConceptsResult') -> bool: return not self == other -class DeleteModelResults(): +class DeleteModelResults: """ Delete model results. - :attr str deleted: (optional) model_id of the deleted model. + :param str deleted: (optional) model_id of the deleted model. """ - def __init__(self, *, deleted: str = None) -> None: + def __init__( + self, + *, + deleted: Optional[str] = None, + ) -> None: """ Initialize a DeleteModelResults object. @@ -2587,8 +2670,8 @@ def __init__(self, *, deleted: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResults': """Initialize a DeleteModelResults object from a json dictionary.""" args = {} - if 'deleted' in _dict: - args['deleted'] = _dict.get('deleted') + if (deleted := _dict.get('deleted')) is not None: + args['deleted'] = deleted return cls(**args) @classmethod @@ -2622,21 +2705,23 @@ def __ne__(self, other: 'DeleteModelResults') -> bool: return not self == other -class DisambiguationResult(): +class DisambiguationResult: """ Disambiguation information for the entity. - :attr str name: (optional) Common entity name. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + :param str name: (optional) Common entity name. + :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :attr List[str] subtype: (optional) Entity subtype information. + :param List[str] subtype: (optional) Entity subtype information. """ - def __init__(self, - *, - name: str = None, - dbpedia_resource: str = None, - subtype: List[str] = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + dbpedia_resource: Optional[str] = None, + subtype: Optional[List[str]] = None, + ) -> None: """ Initialize a DisambiguationResult object. @@ -2653,12 +2738,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DisambiguationResult': """Initialize a DisambiguationResult object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'dbpedia_resource' in _dict: - args['dbpedia_resource'] = _dict.get('dbpedia_resource') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (dbpedia_resource := _dict.get('dbpedia_resource')) is not None: + args['dbpedia_resource'] = dbpedia_resource + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype return cls(**args) @classmethod @@ -2697,15 +2782,19 @@ def __ne__(self, other: 'DisambiguationResult') -> bool: return not self == other -class DocumentEmotionResults(): +class DocumentEmotionResults: """ Emotion results for the document as a whole. - :attr EmotionScores emotion: (optional) Emotion results for the document as a + :param EmotionScores emotion: (optional) Emotion results for the document as a whole. """ - def __init__(self, *, emotion: 'EmotionScores' = None) -> None: + def __init__( + self, + *, + emotion: Optional['EmotionScores'] = None, + ) -> None: """ Initialize a DocumentEmotionResults object. @@ -2718,8 +2807,8 @@ def __init__(self, *, emotion: 'EmotionScores' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults': """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) return cls(**args) @classmethod @@ -2731,7 +2820,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): @@ -2753,17 +2845,22 @@ def __ne__(self, other: 'DocumentEmotionResults') -> bool: return not self == other -class DocumentSentimentResults(): +class DocumentSentimentResults: """ DocumentSentimentResults. - :attr str label: (optional) Indicates whether the sentiment is positive, + :param str label: (optional) Indicates whether the sentiment is positive, neutral, or negative. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, label: str = None, score: float = None) -> None: + def __init__( + self, + *, + label: Optional[str] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a DocumentSentimentResults object. @@ -2779,10 +2876,10 @@ def __init__(self, *, label: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentSentimentResults': """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (label := _dict.get('label')) is not None: + args['label'] = label + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -2818,7 +2915,7 @@ def __ne__(self, other: 'DocumentSentimentResults') -> bool: return not self == other -class EmotionOptions(): +class EmotionOptions: """ Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze @@ -2826,16 +2923,18 @@ class EmotionOptions(): `keywords.emotion`. Supported languages: English. - :attr bool document: (optional) Set this to `false` to hide document-level + :param bool document: (optional) Set this to `false` to hide document-level emotion results. - :attr List[str] targets: (optional) Emotion results will be returned for each + :param List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a EmotionOptions object. @@ -2851,10 +2950,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionOptions': """Initialize a EmotionOptions object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -2890,22 +2989,24 @@ def __ne__(self, other: 'EmotionOptions') -> bool: return not self == other -class EmotionResult(): +class EmotionResult: """ The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. - :attr DocumentEmotionResults document: (optional) Emotion results for the + :param DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :attr List[TargetedEmotionResults] targets: (optional) Emotion results for + :param List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ - def __init__(self, - *, - document: 'DocumentEmotionResults' = None, - targets: List['TargetedEmotionResults'] = None) -> None: + def __init__( + self, + *, + document: Optional['DocumentEmotionResults'] = None, + targets: Optional[List['TargetedEmotionResults']] = None, + ) -> None: """ Initialize a EmotionResult object. @@ -2921,13 +3022,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionResult': """Initialize a EmotionResult object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = DocumentEmotionResults.from_dict( - _dict.get('document')) - if 'targets' in _dict: + if (document := _dict.get('document')) is not None: + args['document'] = DocumentEmotionResults.from_dict(document) + if (targets := _dict.get('targets')) is not None: args['targets'] = [ - TargetedEmotionResults.from_dict(x) - for x in _dict.get('targets') + TargetedEmotionResults.from_dict(v) for v in targets ] return cls(**args) @@ -2940,9 +3039,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() + if isinstance(self.document, dict): + _dict['document'] = self.document + else: + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x.to_dict() for x in self.targets] + targets_list = [] + for v in self.targets: + if isinstance(v, dict): + targets_list.append(v) + else: + targets_list.append(v.to_dict()) + _dict['targets'] = targets_list return _dict def _to_dict(self): @@ -2964,29 +3072,31 @@ def __ne__(self, other: 'EmotionResult') -> bool: return not self == other -class EmotionScores(): +class EmotionScores: """ EmotionScores. - :attr float anger: (optional) Anger score from 0 to 1. A higher score means that - the text is more likely to convey anger. - :attr float disgust: (optional) Disgust score from 0 to 1. A higher score means + :param float anger: (optional) Anger score from 0 to 1. A higher score means + that the text is more likely to convey anger. + :param float disgust: (optional) Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. - :attr float fear: (optional) Fear score from 0 to 1. A higher score means that + :param float fear: (optional) Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. - :attr float joy: (optional) Joy score from 0 to 1. A higher score means that the - text is more likely to convey joy. - :attr float sadness: (optional) Sadness score from 0 to 1. A higher score means + :param float joy: (optional) Joy score from 0 to 1. A higher score means that + the text is more likely to convey joy. + :param float sadness: (optional) Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. """ - def __init__(self, - *, - anger: float = None, - disgust: float = None, - fear: float = None, - joy: float = None, - sadness: float = None) -> None: + def __init__( + self, + *, + anger: Optional[float] = None, + disgust: Optional[float] = None, + fear: Optional[float] = None, + joy: Optional[float] = None, + sadness: Optional[float] = None, + ) -> None: """ Initialize a EmotionScores object. @@ -3011,16 +3121,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionScores': """Initialize a EmotionScores object from a json dictionary.""" args = {} - if 'anger' in _dict: - args['anger'] = _dict.get('anger') - if 'disgust' in _dict: - args['disgust'] = _dict.get('disgust') - if 'fear' in _dict: - args['fear'] = _dict.get('fear') - if 'joy' in _dict: - args['joy'] = _dict.get('joy') - if 'sadness' in _dict: - args['sadness'] = _dict.get('sadness') + if (anger := _dict.get('anger')) is not None: + args['anger'] = anger + if (disgust := _dict.get('disgust')) is not None: + args['disgust'] = disgust + if (fear := _dict.get('fear')) is not None: + args['fear'] = fear + if (joy := _dict.get('joy')) is not None: + args['joy'] = joy + if (sadness := _dict.get('sadness')) is not None: + args['sadness'] = sadness return cls(**args) @classmethod @@ -3062,34 +3172,36 @@ def __ne__(self, other: 'EmotionScores') -> bool: return not self == other -class EntitiesOptions(): +class EntitiesOptions: """ Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - :attr int limit: (optional) Maximum number of entities to return. - :attr bool mentions: (optional) Set this to `true` to return locations of entity - mentions. - :attr str model: (optional) Enter a [custom + :param int limit: (optional) Maximum number of entities to return. + :param bool mentions: (optional) Set this to `true` to return locations of + entity mentions. + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard entity detection model. - :attr bool sentiment: (optional) Set this to `true` to return sentiment + :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for + :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ - def __init__(self, - *, - limit: int = None, - mentions: bool = None, - model: str = None, - sentiment: bool = None, - emotion: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + mentions: Optional[bool] = None, + model: Optional[str] = None, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + ) -> None: """ Initialize a EntitiesOptions object. @@ -3114,16 +3226,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesOptions': """Initialize a EntitiesOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'mentions' in _dict: - args['mentions'] = _dict.get('mentions') - if 'model' in _dict: - args['model'] = _dict.get('model') - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = mentions + if (model := _dict.get('model')) is not None: + args['model'] = model + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion return cls(**args) @classmethod @@ -3165,40 +3277,43 @@ def __ne__(self, other: 'EntitiesOptions') -> bool: return not self == other -class EntitiesResult(): +class EntitiesResult: """ The important people, places, geopolitical entities and other types of entities in your content. - :attr str type: (optional) Entity type. - :attr str text: (optional) The name of the entity. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + :param str type: (optional) Entity type. + :param str text: (optional) The name of the entity. + :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. - :attr float confidence: (optional) Confidence in the entity identification from + :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. - :attr List[EntityMention] mentions: (optional) Entity mentions and locations. - :attr int count: (optional) How many times the entity was mentioned in the text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the entity, - enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + :param List[EntityMention] mentions: (optional) Entity mentions and locations. + :param int count: (optional) How many times the entity was mentioned in the + text. + :param EmotionScores emotion: (optional) Emotion analysis results for the + entity, enabled with the `emotion` option. + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the entity, enabled with the `sentiment` option. - :attr DisambiguationResult disambiguation: (optional) Disambiguation information - for the entity. + :param DisambiguationResult disambiguation: (optional) Disambiguation + information for the entity. """ - def __init__(self, - *, - type: str = None, - text: str = None, - relevance: float = None, - confidence: float = None, - mentions: List['EntityMention'] = None, - count: int = None, - emotion: 'EmotionScores' = None, - sentiment: 'FeatureSentimentResults' = None, - disambiguation: 'DisambiguationResult' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + relevance: Optional[float] = None, + confidence: Optional[float] = None, + mentions: Optional[List['EntityMention']] = None, + count: Optional[int] = None, + emotion: Optional['EmotionScores'] = None, + sentiment: Optional['FeatureSentimentResults'] = None, + disambiguation: Optional['DisambiguationResult'] = None, + ) -> None: """ Initialize a EntitiesResult object. @@ -3235,28 +3350,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesResult': """Initialize a EntitiesResult object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'mentions' in _dict: - args['mentions'] = [ - EntityMention.from_dict(x) for x in _dict.get('mentions') - ] - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) - if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults.from_dict( - _dict.get('sentiment')) - if 'disambiguation' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = [EntityMention.from_dict(v) for v in mentions] + if (count := _dict.get('count')) is not None: + args['count'] = count + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = FeatureSentimentResults.from_dict(sentiment) + if (disambiguation := _dict.get('disambiguation')) is not None: args['disambiguation'] = DisambiguationResult.from_dict( - _dict.get('disambiguation')) + disambiguation) return cls(**args) @classmethod @@ -3276,15 +3388,30 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] + mentions_list = [] + for v in self.mentions: + if isinstance(v, dict): + mentions_list.append(v) + else: + mentions_list.append(v.to_dict()) + _dict['mentions'] = mentions_list if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation.to_dict() + if isinstance(self.disambiguation, dict): + _dict['disambiguation'] = self.disambiguation + else: + _dict['disambiguation'] = self.disambiguation.to_dict() return _dict def _to_dict(self): @@ -3306,24 +3433,26 @@ def __ne__(self, other: 'EntitiesResult') -> bool: return not self == other -class EntityMention(): +class EntityMention: """ EntityMention. - :attr str text: (optional) Entity mention text. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param str text: (optional) Entity mention text. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. - :attr float confidence: (optional) Confidence in the entity identification from + :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. """ - def __init__(self, - *, - text: str = None, - location: List[int] = None, - confidence: float = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a EntityMention object. @@ -3343,12 +3472,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = location + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -3386,15 +3515,19 @@ def __ne__(self, other: 'EntityMention') -> bool: return not self == other -class FeatureSentimentResults(): +class FeatureSentimentResults: """ FeatureSentimentResults. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, score: float = None) -> None: + def __init__( + self, + *, + score: Optional[float] = None, + ) -> None: """ Initialize a FeatureSentimentResults object. @@ -3407,8 +3540,8 @@ def __init__(self, *, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'FeatureSentimentResults': """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -3442,37 +3575,37 @@ def __ne__(self, other: 'FeatureSentimentResults') -> bool: return not self == other -class Features(): +class Features: """ Analysis features and options. - :attr ClassificationsOptions classifications: (optional) Returns text + :param ClassificationsOptions classifications: (optional) Returns text classifications for the content. - :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the + :param ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or + :param EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. - :attr EntitiesOptions entities: (optional) Identifies people, cities, + :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - :attr KeywordsOptions keywords: (optional) Returns important keywords in the + :param KeywordsOptions keywords: (optional) Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr dict metadata: (optional) Returns information from the document, including - author name, title, RSS/ATOM feeds, prominent page image, and publication date. - Supports URL and HTML input types only. - :attr RelationsOptions relations: (optional) Recognizes when two entities are + :param dict metadata: (optional) Returns information from the document, + including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. + :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For more information, see [Relation @@ -3480,40 +3613,38 @@ class Features(): Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - :attr SemanticRolesOptions semantic_roles: (optional) Parses sentences into + :param SemanticRolesOptions semantic_roles: (optional) Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - :attr SentimentOptions sentiment: (optional) Analyzes the general sentiment of + :param SentimentOptions sentiment: (optional) Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr SummarizationOptions summarization: (optional) (Experimental) Returns a - summary of content. - Supported languages: English only. - :attr CategoriesOptions categories: (optional) Returns a hierarchical taxonomy + :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the + :param SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ - def __init__(self, - *, - classifications: 'ClassificationsOptions' = None, - concepts: 'ConceptsOptions' = None, - emotion: 'EmotionOptions' = None, - entities: 'EntitiesOptions' = None, - keywords: 'KeywordsOptions' = None, - metadata: dict = None, - relations: 'RelationsOptions' = None, - semantic_roles: 'SemanticRolesOptions' = None, - sentiment: 'SentimentOptions' = None, - summarization: 'SummarizationOptions' = None, - categories: 'CategoriesOptions' = None, - syntax: 'SyntaxOptions' = None) -> None: + def __init__( + self, + *, + classifications: Optional['ClassificationsOptions'] = None, + concepts: Optional['ConceptsOptions'] = None, + emotion: Optional['EmotionOptions'] = None, + entities: Optional['EntitiesOptions'] = None, + keywords: Optional['KeywordsOptions'] = None, + metadata: Optional[dict] = None, + relations: Optional['RelationsOptions'] = None, + semantic_roles: Optional['SemanticRolesOptions'] = None, + sentiment: Optional['SentimentOptions'] = None, + categories: Optional['CategoriesOptions'] = None, + syntax: Optional['SyntaxOptions'] = None, + ) -> None: """ Initialize a Features object. @@ -3533,7 +3664,7 @@ def __init__(self, :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -3561,9 +3692,6 @@ def __init__(self, and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :param SummarizationOptions summarization: (optional) (Experimental) - Returns a summary of content. - Supported languages: English only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, @@ -3580,7 +3708,6 @@ def __init__(self, self.relations = relations self.semantic_roles = semantic_roles self.sentiment = sentiment - self.summarization = summarization self.categories = categories self.syntax = syntax @@ -3588,36 +3715,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} - if 'classifications' in _dict: + if (classifications := _dict.get('classifications')) is not None: args['classifications'] = ClassificationsOptions.from_dict( - _dict.get('classifications')) - if 'concepts' in _dict: - args['concepts'] = ConceptsOptions.from_dict(_dict.get('concepts')) - if 'emotion' in _dict: - args['emotion'] = EmotionOptions.from_dict(_dict.get('emotion')) - if 'entities' in _dict: - args['entities'] = EntitiesOptions.from_dict(_dict.get('entities')) - if 'keywords' in _dict: - args['keywords'] = KeywordsOptions.from_dict(_dict.get('keywords')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'relations' in _dict: - args['relations'] = RelationsOptions.from_dict( - _dict.get('relations')) - if 'semantic_roles' in _dict: + classifications) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = ConceptsOptions.from_dict(concepts) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionOptions.from_dict(emotion) + if (entities := _dict.get('entities')) is not None: + args['entities'] = EntitiesOptions.from_dict(entities) + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = KeywordsOptions.from_dict(keywords) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (relations := _dict.get('relations')) is not None: + args['relations'] = RelationsOptions.from_dict(relations) + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = SemanticRolesOptions.from_dict( - _dict.get('semantic_roles')) - if 'sentiment' in _dict: - args['sentiment'] = SentimentOptions.from_dict( - _dict.get('sentiment')) - if 'summarization' in _dict: - args['summarization'] = SummarizationOptions.from_dict( - _dict.get('summarization')) - if 'categories' in _dict: - args['categories'] = CategoriesOptions.from_dict( - _dict.get('categories')) - if 'syntax' in _dict: - args['syntax'] = SyntaxOptions.from_dict(_dict.get('syntax')) + semantic_roles) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = SentimentOptions.from_dict(sentiment) + if (categories := _dict.get('categories')) is not None: + args['categories'] = CategoriesOptions.from_dict(categories) + if (syntax := _dict.get('syntax')) is not None: + args['syntax'] = SyntaxOptions.from_dict(syntax) return cls(**args) @classmethod @@ -3630,29 +3751,57 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'classifications') and self.classifications is not None: - _dict['classifications'] = self.classifications.to_dict() + if isinstance(self.classifications, dict): + _dict['classifications'] = self.classifications + else: + _dict['classifications'] = self.classifications.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts.to_dict() + if isinstance(self.concepts, dict): + _dict['concepts'] = self.concepts + else: + _dict['concepts'] = self.concepts.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities.to_dict() + if isinstance(self.entities, dict): + _dict['entities'] = self.entities + else: + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords.to_dict() + if isinstance(self.keywords, dict): + _dict['keywords'] = self.keywords + else: + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations.to_dict() + if isinstance(self.relations, dict): + _dict['relations'] = self.relations + else: + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles.to_dict() + if isinstance(self.semantic_roles, dict): + _dict['semantic_roles'] = self.semantic_roles + else: + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'summarization') and self.summarization is not None: - _dict['summarization'] = self.summarization.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories.to_dict() + if isinstance(self.categories, dict): + _dict['categories'] = self.categories + else: + _dict['categories'] = self.categories.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if isinstance(self.syntax, dict): + _dict['syntax'] = self.syntax + else: + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -3674,25 +3823,27 @@ def __ne__(self, other: 'Features') -> bool: return not self == other -class FeaturesResultsMetadata(): +class FeaturesResultsMetadata: """ Webpage metadata, such as the author and the title of the page. - :attr List[Author] authors: (optional) The authors of the document. - :attr str publication_date: (optional) The publication date in the format ISO + :param List[Author] authors: (optional) The authors of the document. + :param str publication_date: (optional) The publication date in the format ISO 8601. - :attr str title: (optional) The title of the document. - :attr str image: (optional) URL of a prominent image on the webpage. - :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + :param str title: (optional) The title of the document. + :param str image: (optional) URL of a prominent image on the webpage. + :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ - def __init__(self, - *, - authors: List['Author'] = None, - publication_date: str = None, - title: str = None, - image: str = None, - feeds: List['Feed'] = None) -> None: + def __init__( + self, + *, + authors: Optional[List['Author']] = None, + publication_date: Optional[str] = None, + title: Optional[str] = None, + image: Optional[str] = None, + feeds: Optional[List['Feed']] = None, + ) -> None: """ Initialize a FeaturesResultsMetadata object. @@ -3713,18 +3864,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': """Initialize a FeaturesResultsMetadata object from a json dictionary.""" args = {} - if 'authors' in _dict: - args['authors'] = [ - Author.from_dict(x) for x in _dict.get('authors') - ] - if 'publication_date' in _dict: - args['publication_date'] = _dict.get('publication_date') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'image' in _dict: - args['image'] = _dict.get('image') - if 'feeds' in _dict: - args['feeds'] = [Feed.from_dict(x) for x in _dict.get('feeds')] + if (authors := _dict.get('authors')) is not None: + args['authors'] = [Author.from_dict(v) for v in authors] + if (publication_date := _dict.get('publication_date')) is not None: + args['publication_date'] = publication_date + if (title := _dict.get('title')) is not None: + args['title'] = title + if (image := _dict.get('image')) is not None: + args['image'] = image + if (feeds := _dict.get('feeds')) is not None: + args['feeds'] = [Feed.from_dict(v) for v in feeds] return cls(**args) @classmethod @@ -3736,7 +3885,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'authors') and self.authors is not None: - _dict['authors'] = [x.to_dict() for x in self.authors] + authors_list = [] + for v in self.authors: + if isinstance(v, dict): + authors_list.append(v) + else: + authors_list.append(v.to_dict()) + _dict['authors'] = authors_list if hasattr(self, 'publication_date') and self.publication_date is not None: _dict['publication_date'] = self.publication_date @@ -3745,7 +3900,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'feeds') and self.feeds is not None: - _dict['feeds'] = [x.to_dict() for x in self.feeds] + feeds_list = [] + for v in self.feeds: + if isinstance(v, dict): + feeds_list.append(v) + else: + feeds_list.append(v.to_dict()) + _dict['feeds'] = feeds_list return _dict def _to_dict(self): @@ -3767,14 +3928,18 @@ def __ne__(self, other: 'FeaturesResultsMetadata') -> bool: return not self == other -class Feed(): +class Feed: """ RSS or ATOM feed found on the webpage. - :attr str link: (optional) URL of the RSS or ATOM feed. + :param str link: (optional) URL of the RSS or ATOM feed. """ - def __init__(self, *, link: str = None) -> None: + def __init__( + self, + *, + link: Optional[str] = None, + ) -> None: """ Initialize a Feed object. @@ -3786,8 +3951,8 @@ def __init__(self, *, link: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Feed': """Initialize a Feed object from a json dictionary.""" args = {} - if 'link' in _dict: - args['link'] = _dict.get('link') + if (link := _dict.get('link')) is not None: + args['link'] = link return cls(**args) @classmethod @@ -3821,24 +3986,26 @@ def __ne__(self, other: 'Feed') -> bool: return not self == other -class KeywordsOptions(): +class KeywordsOptions: """ Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr int limit: (optional) Maximum number of keywords to return. - :attr bool sentiment: (optional) Set this to `true` to return sentiment + :param int limit: (optional) Maximum number of keywords to return. + :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected keywords. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for + :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ - def __init__(self, - *, - limit: int = None, - sentiment: bool = None, - emotion: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + ) -> None: """ Initialize a KeywordsOptions object. @@ -3856,12 +4023,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsOptions': """Initialize a KeywordsOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion return cls(**args) @classmethod @@ -3899,28 +4066,30 @@ def __ne__(self, other: 'KeywordsOptions') -> bool: return not self == other -class KeywordsResult(): +class KeywordsResult: """ The important keywords in the content, organized by relevance. - :attr int count: (optional) Number of times the keyword appears in the analyzed + :param int count: (optional) Number of times the keyword appears in the analyzed text. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. - :attr str text: (optional) The keyword text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the + :param str text: (optional) The keyword text. + :param EmotionScores emotion: (optional) Emotion analysis results for the keyword, enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the keyword, enabled with the `sentiment` option. """ - def __init__(self, - *, - count: int = None, - relevance: float = None, - text: str = None, - emotion: 'EmotionScores' = None, - sentiment: 'FeatureSentimentResults' = None) -> None: + def __init__( + self, + *, + count: Optional[int] = None, + relevance: Optional[float] = None, + text: Optional[str] = None, + emotion: Optional['EmotionScores'] = None, + sentiment: Optional['FeatureSentimentResults'] = None, + ) -> None: """ Initialize a KeywordsResult object. @@ -3944,17 +4113,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsResult': """Initialize a KeywordsResult object from a json dictionary.""" args = {} - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) - if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults.from_dict( - _dict.get('sentiment')) + if (count := _dict.get('count')) is not None: + args['count'] = count + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (text := _dict.get('text')) is not None: + args['text'] = text + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = FeatureSentimentResults.from_dict(sentiment) return cls(**args) @classmethod @@ -3972,9 +4140,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() return _dict def _to_dict(self): @@ -3985,106 +4159,60 @@ def __str__(self) -> str: """Return a `str` version of this KeywordsResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'KeywordsResult') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'KeywordsResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListModelsResults(): - """ - Custom models that are available for entities and relations. - - :attr List[Model] models: (optional) An array of available models. - """ - - def __init__(self, *, models: List['Model'] = None) -> None: - """ - Initialize a ListModelsResults object. - - :param List[Model] models: (optional) An array of available models. - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListModelsResults': - """Initialize a ListModelsResults object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [Model.from_dict(x) for x in _dict.get('models')] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListModelsResults object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListModelsResults object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListModelsResults') -> bool: + def __eq__(self, other: 'KeywordsResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListModelsResults') -> bool: + def __ne__(self, other: 'KeywordsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ListSentimentModelsResponse(): +class ListModelsResults: """ - ListSentimentModelsResponse. + Custom models that are available for entities and relations. - :attr List[SentimentModel] models: (optional) + :param List[Model] models: (optional) An array of available models. """ - def __init__(self, *, models: List['SentimentModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['Model']] = None, + ) -> None: """ - Initialize a ListSentimentModelsResponse object. + Initialize a ListModelsResults object. - :param List[SentimentModel] models: (optional) + :param List[Model] models: (optional) An array of available models. """ self.models = models @classmethod - def from_dict(cls, _dict: Dict) -> 'ListSentimentModelsResponse': - """Initialize a ListSentimentModelsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListModelsResults': + """Initialize a ListModelsResults object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - SentimentModel.from_dict(x) for x in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [Model.from_dict(v) for v in models] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListSentimentModelsResponse object from a json dictionary.""" + """Initialize a ListModelsResults object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -4092,52 +4220,54 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListSentimentModelsResponse object.""" + """Return a `str` version of this ListModelsResults object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListSentimentModelsResponse') -> bool: + def __eq__(self, other: 'ListModelsResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListSentimentModelsResponse') -> bool: + def __ne__(self, other: 'ListModelsResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Model(): +class Model: """ Model. - :attr str status: (optional) When the status is `available`, the model is ready + :param str status: (optional) When the status is `available`, the model is ready to use. - :attr str model_id: (optional) Unique model ID. - :attr str language: (optional) ISO 639-1 code that indicates the language of the - model. - :attr str description: (optional) Model description. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str model_id: (optional) Unique model ID. + :param str language: (optional) ISO 639-1 code that indicates the language of + the model. + :param str description: (optional) Model description. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str model_version: (optional) The model version, if it was manually + :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :attr str version: (optional) Deprecated — use `model_version`. - :attr str version_description: (optional) The description of the version, if it + :param str version: (optional) Deprecated: Deprecated — use `model_version`. + :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. - :attr datetime created: (optional) A dateTime indicating when the model was + :param datetime created: (optional) A dateTime indicating when the model was created. """ - def __init__(self, - *, - status: str = None, - model_id: str = None, - language: str = None, - description: str = None, - workspace_id: str = None, - model_version: str = None, - version: str = None, - version_description: str = None, - created: datetime = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + model_id: Optional[str] = None, + language: Optional[str] = None, + description: Optional[str] = None, + workspace_id: Optional[str] = None, + model_version: Optional[str] = None, + version: Optional[str] = None, + version_description: Optional[str] = None, + created: Optional[datetime] = None, + ) -> None: """ Initialize a Model object. @@ -4151,7 +4281,8 @@ def __init__(self, workspace that deployed this model to Natural Language Understanding. :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :param str version: (optional) Deprecated — use `model_version`. + :param str version: (optional) Deprecated: Deprecated — use + `model_version`. :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :param datetime created: (optional) A dateTime indicating when the model @@ -4171,24 +4302,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Model': """Initialize a Model object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'version' in _dict: - args['version'] = _dict.get('version') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (language := _dict.get('language')) is not None: + args['language'] = language + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (version := _dict.get('version')) is not None: + args['version'] = version + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) return cls(**args) @classmethod @@ -4243,6 +4375,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -4251,15 +4384,19 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class Notice(): +class Notice: """ A list of messages describing model training issues when model status is `error`. - :attr str message: (optional) Describes deficiencies or inconsistencies in + :param str message: (optional) Describes deficiencies or inconsistencies in training data. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -4270,8 +4407,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -4305,21 +4442,23 @@ def __ne__(self, other: 'Notice') -> bool: return not self == other -class RelationArgument(): +class RelationArgument: """ RelationArgument. - :attr List[RelationEntity] entities: (optional) An array of extracted entities. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param List[RelationEntity] entities: (optional) An array of extracted entities. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. - :attr str text: (optional) Text that corresponds to the argument. + :param str text: (optional) Text that corresponds to the argument. """ - def __init__(self, - *, - entities: List['RelationEntity'] = None, - location: List[int] = None, - text: str = None) -> None: + def __init__( + self, + *, + entities: Optional[List['RelationEntity']] = None, + location: Optional[List[int]] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a RelationArgument object. @@ -4337,14 +4476,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationArgument': """Initialize a RelationArgument object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = [ - RelationEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RelationEntity.from_dict(v) for v in entities] + if (location := _dict.get('location')) is not None: + args['location'] = location + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4356,7 +4493,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: @@ -4382,15 +4525,20 @@ def __ne__(self, other: 'RelationArgument') -> bool: return not self == other -class RelationEntity(): +class RelationEntity: """ An entity that corresponds with an argument in a relation. - :attr str text: (optional) Text that corresponds to the entity. - :attr str type: (optional) Entity type. + :param str text: (optional) Text that corresponds to the entity. + :param str type: (optional) Entity type. """ - def __init__(self, *, text: str = None, type: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a RelationEntity object. @@ -4404,10 +4552,10 @@ def __init__(self, *, text: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationEntity': """Initialize a RelationEntity object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -4443,7 +4591,7 @@ def __ne__(self, other: 'RelationEntity') -> bool: return not self == other -class RelationsOptions(): +class RelationsOptions: """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -4452,12 +4600,16 @@ class RelationsOptions(): Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - :attr str model: (optional) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the default model. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a RelationsOptions object. @@ -4471,8 +4623,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationsOptions': """Initialize a RelationsOptions object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -4506,24 +4658,26 @@ def __ne__(self, other: 'RelationsOptions') -> bool: return not self == other -class RelationsResult(): +class RelationsResult: """ The relations between entities found in the content. - :attr float score: (optional) Confidence score for the relation. Higher values + :param float score: (optional) Confidence score for the relation. Higher values indicate greater confidence. - :attr str sentence: (optional) The sentence that contains the relation. - :attr str type: (optional) The type of the relation. - :attr List[RelationArgument] arguments: (optional) Entity mentions that are + :param str sentence: (optional) The sentence that contains the relation. + :param str type: (optional) The type of the relation. + :param List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ - def __init__(self, - *, - score: float = None, - sentence: str = None, - type: str = None, - arguments: List['RelationArgument'] = None) -> None: + def __init__( + self, + *, + score: Optional[float] = None, + sentence: Optional[str] = None, + type: Optional[str] = None, + arguments: Optional[List['RelationArgument']] = None, + ) -> None: """ Initialize a RelationsResult object. @@ -4543,15 +4697,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationsResult': """Initialize a RelationsResult object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'sentence' in _dict: - args['sentence'] = _dict.get('sentence') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'arguments' in _dict: + if (score := _dict.get('score')) is not None: + args['score'] = score + if (sentence := _dict.get('sentence')) is not None: + args['sentence'] = sentence + if (type := _dict.get('type')) is not None: + args['type'] = type + if (arguments := _dict.get('arguments')) is not None: args['arguments'] = [ - RelationArgument.from_dict(x) for x in _dict.get('arguments') + RelationArgument.from_dict(v) for v in arguments ] return cls(**args) @@ -4570,7 +4724,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'arguments') and self.arguments is not None: - _dict['arguments'] = [x.to_dict() for x in self.arguments] + arguments_list = [] + for v in self.arguments: + if isinstance(v, dict): + arguments_list.append(v) + else: + arguments_list.append(v.to_dict()) + _dict['arguments'] = arguments_list return _dict def _to_dict(self): @@ -4592,15 +4752,20 @@ def __ne__(self, other: 'RelationsResult') -> bool: return not self == other -class SemanticRolesEntity(): +class SemanticRolesEntity: """ SemanticRolesEntity. - :attr str type: (optional) Entity type. - :attr str text: (optional) The entity text. + :param str type: (optional) Entity type. + :param str text: (optional) The entity text. """ - def __init__(self, *, type: str = None, text: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesEntity object. @@ -4614,10 +4779,10 @@ def __init__(self, *, type: str = None, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesEntity': """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4653,14 +4818,18 @@ def __ne__(self, other: 'SemanticRolesEntity') -> bool: return not self == other -class SemanticRolesKeyword(): +class SemanticRolesKeyword: """ SemanticRolesKeyword. - :attr str text: (optional) The keyword text. + :param str text: (optional) The keyword text. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesKeyword object. @@ -4672,8 +4841,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesKeyword': """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4707,23 +4876,25 @@ def __ne__(self, other: 'SemanticRolesKeyword') -> bool: return not self == other -class SemanticRolesOptions(): +class SemanticRolesOptions: """ Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - :attr int limit: (optional) Maximum number of semantic_roles results to return. - :attr bool keywords: (optional) Set this to `true` to return keyword information - for subjects and objects. - :attr bool entities: (optional) Set this to `true` to return entity information + :param int limit: (optional) Maximum number of semantic_roles results to return. + :param bool keywords: (optional) Set this to `true` to return keyword + information for subjects and objects. + :param bool entities: (optional) Set this to `true` to return entity information for subjects and objects. """ - def __init__(self, - *, - limit: int = None, - keywords: bool = None, - entities: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + keywords: Optional[bool] = None, + entities: Optional[bool] = None, + ) -> None: """ Initialize a SemanticRolesOptions object. @@ -4742,12 +4913,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesOptions': """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'keywords' in _dict: - args['keywords'] = _dict.get('keywords') - if 'entities' in _dict: - args['entities'] = _dict.get('entities') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = keywords + if (entities := _dict.get('entities')) is not None: + args['entities'] = entities return cls(**args) @classmethod @@ -4785,26 +4956,28 @@ def __ne__(self, other: 'SemanticRolesOptions') -> bool: return not self == other -class SemanticRolesResult(): +class SemanticRolesResult: """ The object containing the actions and the objects the actions act upon. - :attr str sentence: (optional) Sentence from the source that contains the + :param str sentence: (optional) Sentence from the source that contains the subject, action, and object. - :attr SemanticRolesResultSubject subject: (optional) The extracted subject from + :param SemanticRolesResultSubject subject: (optional) The extracted subject from + the sentence. + :param SemanticRolesResultAction action: (optional) The extracted action from + the sentence. + :param SemanticRolesResultObject object: (optional) The extracted object from the sentence. - :attr SemanticRolesResultAction action: (optional) The extracted action from the - sentence. - :attr SemanticRolesResultObject object: (optional) The extracted object from the - sentence. """ - def __init__(self, - *, - sentence: str = None, - subject: 'SemanticRolesResultSubject' = None, - action: 'SemanticRolesResultAction' = None, - object: 'SemanticRolesResultObject' = None) -> None: + def __init__( + self, + *, + sentence: Optional[str] = None, + subject: Optional['SemanticRolesResultSubject'] = None, + action: Optional['SemanticRolesResultAction'] = None, + object: Optional['SemanticRolesResultObject'] = None, + ) -> None: """ Initialize a SemanticRolesResult object. @@ -4826,17 +4999,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult': """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} - if 'sentence' in _dict: - args['sentence'] = _dict.get('sentence') - if 'subject' in _dict: - args['subject'] = SemanticRolesResultSubject.from_dict( - _dict.get('subject')) - if 'action' in _dict: - args['action'] = SemanticRolesResultAction.from_dict( - _dict.get('action')) - if 'object' in _dict: - args['object'] = SemanticRolesResultObject.from_dict( - _dict.get('object')) + if (sentence := _dict.get('sentence')) is not None: + args['sentence'] = sentence + if (subject := _dict.get('subject')) is not None: + args['subject'] = SemanticRolesResultSubject.from_dict(subject) + if (action := _dict.get('action')) is not None: + args['action'] = SemanticRolesResultAction.from_dict(action) + if (object := _dict.get('object')) is not None: + args['object'] = SemanticRolesResultObject.from_dict(object) return cls(**args) @classmethod @@ -4850,11 +5020,20 @@ def to_dict(self) -> Dict: if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: - _dict['subject'] = self.subject.to_dict() + if isinstance(self.subject, dict): + _dict['subject'] = self.subject + else: + _dict['subject'] = self.subject.to_dict() if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action.to_dict() + if isinstance(self.action, dict): + _dict['action'] = self.action + else: + _dict['action'] = self.action.to_dict() if hasattr(self, 'object') and self.object is not None: - _dict['object'] = self.object.to_dict() + if isinstance(self.object, dict): + _dict['object'] = self.object + else: + _dict['object'] = self.object.to_dict() return _dict def _to_dict(self): @@ -4876,20 +5055,22 @@ def __ne__(self, other: 'SemanticRolesResult') -> bool: return not self == other -class SemanticRolesResultAction(): +class SemanticRolesResultAction: """ The extracted action from the sentence. - :attr str text: (optional) Analyzed text that corresponds to the action. - :attr str normalized: (optional) normalized version of the action. - :attr SemanticRolesVerb verb: (optional) + :param str text: (optional) Analyzed text that corresponds to the action. + :param str normalized: (optional) normalized version of the action. + :param SemanticRolesVerb verb: (optional) """ - def __init__(self, - *, - text: str = None, - normalized: str = None, - verb: 'SemanticRolesVerb' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + normalized: Optional[str] = None, + verb: Optional['SemanticRolesVerb'] = None, + ) -> None: """ Initialize a SemanticRolesResultAction object. @@ -4905,12 +5086,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultAction': """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'normalized' in _dict: - args['normalized'] = _dict.get('normalized') - if 'verb' in _dict: - args['verb'] = SemanticRolesVerb.from_dict(_dict.get('verb')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (normalized := _dict.get('normalized')) is not None: + args['normalized'] = normalized + if (verb := _dict.get('verb')) is not None: + args['verb'] = SemanticRolesVerb.from_dict(verb) return cls(**args) @classmethod @@ -4926,7 +5107,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'normalized') and self.normalized is not None: _dict['normalized'] = self.normalized if hasattr(self, 'verb') and self.verb is not None: - _dict['verb'] = self.verb.to_dict() + if isinstance(self.verb, dict): + _dict['verb'] = self.verb + else: + _dict['verb'] = self.verb.to_dict() return _dict def _to_dict(self): @@ -4948,19 +5132,21 @@ def __ne__(self, other: 'SemanticRolesResultAction') -> bool: return not self == other -class SemanticRolesResultObject(): +class SemanticRolesResultObject: """ The extracted object from the sentence. - :attr str text: (optional) Object text. - :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted + :param str text: (optional) Object text. + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, - *, - text: str = None, - keywords: List['SemanticRolesKeyword'] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + keywords: Optional[List['SemanticRolesKeyword']] = None, + ) -> None: """ Initialize a SemanticRolesResultObject object. @@ -4975,11 +5161,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'keywords' in _dict: + if (text := _dict.get('text')) is not None: + args['text'] = text + if (keywords := _dict.get('keywords')) is not None: args['keywords'] = [ - SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in keywords ] return cls(**args) @@ -4994,7 +5180,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list return _dict def _to_dict(self): @@ -5016,22 +5208,24 @@ def __ne__(self, other: 'SemanticRolesResultObject') -> bool: return not self == other -class SemanticRolesResultSubject(): +class SemanticRolesResultSubject: """ The extracted subject from the sentence. - :attr str text: (optional) Text that corresponds to the subject role. - :attr List[SemanticRolesEntity] entities: (optional) An array of extracted + :param str text: (optional) Text that corresponds to the subject role. + :param List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, - *, - text: str = None, - entities: List['SemanticRolesEntity'] = None, - keywords: List['SemanticRolesKeyword'] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + entities: Optional[List['SemanticRolesEntity']] = None, + keywords: Optional[List['SemanticRolesKeyword']] = None, + ) -> None: """ Initialize a SemanticRolesResultSubject object. @@ -5049,15 +5243,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'entities' in _dict: + if (text := _dict.get('text')) is not None: + args['text'] = text + if (entities := _dict.get('entities')) is not None: args['entities'] = [ - SemanticRolesEntity.from_dict(x) for x in _dict.get('entities') + SemanticRolesEntity.from_dict(v) for v in entities ] - if 'keywords' in _dict: + if (keywords := _dict.get('keywords')) is not None: args['keywords'] = [ - SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in keywords ] return cls(**args) @@ -5072,9 +5266,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list return _dict def _to_dict(self): @@ -5096,15 +5302,20 @@ def __ne__(self, other: 'SemanticRolesResultSubject') -> bool: return not self == other -class SemanticRolesVerb(): +class SemanticRolesVerb: """ SemanticRolesVerb. - :attr str text: (optional) The keyword text. - :attr str tense: (optional) Verb tense. + :param str text: (optional) The keyword text. + :param str tense: (optional) Verb tense. """ - def __init__(self, *, text: str = None, tense: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + tense: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesVerb object. @@ -5118,10 +5329,10 @@ def __init__(self, *, text: str = None, tense: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesVerb': """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'tense' in _dict: - args['tense'] = _dict.get('tense') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (tense := _dict.get('tense')) is not None: + args['tense'] = tense return cls(**args) @classmethod @@ -5157,16 +5368,21 @@ def __ne__(self, other: 'SemanticRolesVerb') -> bool: return not self == other -class SentenceResult(): +class SentenceResult: """ SentenceResult. - :attr str text: (optional) The sentence. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param str text: (optional) The sentence. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ - def __init__(self, *, text: str = None, location: List[int] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a SentenceResult object. @@ -5181,10 +5397,10 @@ def __init__(self, *, text: str = None, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'SentenceResult': """Initialize a SentenceResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -5220,197 +5436,7 @@ def __ne__(self, other: 'SentenceResult') -> bool: return not self == other -class SentimentModel(): - """ - SentimentModel. - - :attr List[str] features: (optional) The service features that are supported by - the custom model. - :attr str status: (optional) When the status is `available`, the model is ready - to use. - :attr str model_id: (optional) Unique model ID. - :attr datetime created: (optional) dateTime indicating when the model was - created. - :attr datetime last_trained: (optional) dateTime of last successful model - training. - :attr datetime last_deployed: (optional) dateTime of last successful model - deployment. - :attr str name: (optional) A name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: (optional) The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr List[Notice] notices: (optional) - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace - that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - """ - - def __init__(self, - *, - features: List[str] = None, - status: str = None, - model_id: str = None, - created: datetime = None, - last_trained: datetime = None, - last_deployed: datetime = None, - name: str = None, - user_metadata: dict = None, - language: str = None, - description: str = None, - model_version: str = None, - notices: List['Notice'] = None, - workspace_id: str = None, - version_description: str = None) -> None: - """ - Initialize a SentimentModel object. - - :param List[str] features: (optional) The service features that are - supported by the custom model. - :param str status: (optional) When the status is `available`, the model is - ready to use. - :param str model_id: (optional) Unique model ID. - :param datetime created: (optional) dateTime indicating when the model was - created. - :param datetime last_trained: (optional) dateTime of last successful model - training. - :param datetime last_deployed: (optional) dateTime of last successful model - deployment. - :param str name: (optional) A name for the model. - :param dict user_metadata: (optional) An optional map of metadata key-value - pairs to store with this model. - :param str language: (optional) The 2-letter language code of this model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param List[Notice] notices: (optional) - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - """ - self.features = features - self.status = status - self.model_id = model_id - self.created = created - self.last_trained = last_trained - self.last_deployed = last_deployed - self.name = name - self.user_metadata = user_metadata - self.language = language - self.description = description - self.model_version = model_version - self.notices = notices - self.workspace_id = workspace_id - self.version_description = version_description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SentimentModel': - """Initialize a SentimentModel object from a json dictionary.""" - args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SentimentModel object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'features') and self.features is not None: - _dict['features'] = self.features - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = datetime_to_string(self.last_trained) - if hasattr(self, 'last_deployed') and self.last_deployed is not None: - _dict['last_deployed'] = datetime_to_string(self.last_deployed) - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'user_metadata') and self.user_metadata is not None: - _dict['user_metadata'] = self.user_metadata - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - if hasattr(self, 'workspace_id') and self.workspace_id is not None: - _dict['workspace_id'] = self.workspace_id - if hasattr( - self, - 'version_description') and self.version_description is not None: - _dict['version_description'] = self.version_description - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SentimentModel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SentimentModel') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SentimentModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - When the status is `available`, the model is ready to use. - """ - STARTING = 'starting' - TRAINING = 'training' - DEPLOYING = 'deploying' - AVAILABLE = 'available' - ERROR = 'error' - DELETED = 'deleted' - - -class SentimentOptions(): +class SentimentOptions: """ Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and @@ -5418,22 +5444,18 @@ class SentimentOptions(): Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr bool document: (optional) Set this to `false` to hide document-level + :param bool document: (optional) Set this to `false` to hide document-level sentiment results. - :attr List[str] targets: (optional) Sentiment results will be returned for each + :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. - :attr str model: (optional) (Beta) Enter a [custom - model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard sentiment model for all sentiment analysis - operations in the request, including targeted sentiment for entities and - keywords. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None, - model: str = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a SentimentOptions object. @@ -5441,26 +5463,18 @@ def __init__(self, sentiment results. :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. - :param str model: (optional) (Beta) Enter a [custom - model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard sentiment model for all sentiment analysis - operations in the request, including targeted sentiment for entities and - keywords. """ self.document = document self.targets = targets - self.model = model @classmethod def from_dict(cls, _dict: Dict) -> 'SentimentOptions': """Initialize a SentimentOptions object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -5475,8 +5489,6 @@ def to_dict(self) -> Dict: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model return _dict def _to_dict(self): @@ -5498,20 +5510,22 @@ def __ne__(self, other: 'SentimentOptions') -> bool: return not self == other -class SentimentResult(): +class SentimentResult: """ The sentiment of the content. - :attr DocumentSentimentResults document: (optional) The document level + :param DocumentSentimentResults document: (optional) The document level sentiment. - :attr List[TargetedSentimentResults] targets: (optional) The targeted sentiment + :param List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ - def __init__(self, - *, - document: 'DocumentSentimentResults' = None, - targets: List['TargetedSentimentResults'] = None) -> None: + def __init__( + self, + *, + document: Optional['DocumentSentimentResults'] = None, + targets: Optional[List['TargetedSentimentResults']] = None, + ) -> None: """ Initialize a SentimentResult object. @@ -5527,13 +5541,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentResult': """Initialize a SentimentResult object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = DocumentSentimentResults.from_dict( - _dict.get('document')) - if 'targets' in _dict: + if (document := _dict.get('document')) is not None: + args['document'] = DocumentSentimentResults.from_dict(document) + if (targets := _dict.get('targets')) is not None: args['targets'] = [ - TargetedSentimentResults.from_dict(x) - for x in _dict.get('targets') + TargetedSentimentResults.from_dict(v) for v in targets ] return cls(**args) @@ -5546,9 +5558,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() + if isinstance(self.document, dict): + _dict['document'] = self.document + else: + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x.to_dict() for x in self.targets] + targets_list = [] + for v in self.targets: + if isinstance(v, dict): + targets_list.append(v) + else: + targets_list.append(v.to_dict()) + _dict['targets'] = targets_list return _dict def _to_dict(self): @@ -5570,74 +5591,21 @@ def __ne__(self, other: 'SentimentResult') -> bool: return not self == other -class SummarizationOptions(): - """ - (Experimental) Returns a summary of content. - Supported languages: English only. - - :attr int limit: (optional) Maximum number of summary sentences to return. - """ - - def __init__(self, *, limit: int = None) -> None: - """ - Initialize a SummarizationOptions object. - - :param int limit: (optional) Maximum number of summary sentences to return. - """ - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SummarizationOptions': - """Initialize a SummarizationOptions object from a json dictionary.""" - args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SummarizationOptions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SummarizationOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SummarizationOptions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SummarizationOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SyntaxOptions(): +class SyntaxOptions: """ Returns tokens and sentences from the input text. - :attr SyntaxOptionsTokens tokens: (optional) Tokenization options. - :attr bool sentences: (optional) Set this to `true` to return sentence + :param SyntaxOptionsTokens tokens: (optional) Tokenization options. + :param bool sentences: (optional) Set this to `true` to return sentence information. """ - def __init__(self, - *, - tokens: 'SyntaxOptionsTokens' = None, - sentences: bool = None) -> None: + def __init__( + self, + *, + tokens: Optional['SyntaxOptionsTokens'] = None, + sentences: Optional[bool] = None, + ) -> None: """ Initialize a SyntaxOptions object. @@ -5652,10 +5620,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptions': """Initialize a SyntaxOptions object from a json dictionary.""" args = {} - if 'tokens' in _dict: - args['tokens'] = SyntaxOptionsTokens.from_dict(_dict.get('tokens')) - if 'sentences' in _dict: - args['sentences'] = _dict.get('sentences') + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = SyntaxOptionsTokens.from_dict(tokens) + if (sentences := _dict.get('sentences')) is not None: + args['sentences'] = sentences return cls(**args) @classmethod @@ -5667,7 +5635,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens.to_dict() + if isinstance(self.tokens, dict): + _dict['tokens'] = self.tokens + else: + _dict['tokens'] = self.tokens.to_dict() if hasattr(self, 'sentences') and self.sentences is not None: _dict['sentences'] = self.sentences return _dict @@ -5691,20 +5662,22 @@ def __ne__(self, other: 'SyntaxOptions') -> bool: return not self == other -class SyntaxOptionsTokens(): +class SyntaxOptionsTokens: """ Tokenization options. - :attr bool lemma: (optional) Set this to `true` to return the lemma for each + :param bool lemma: (optional) Set this to `true` to return the lemma for each token. - :attr bool part_of_speech: (optional) Set this to `true` to return the part of + :param bool part_of_speech: (optional) Set this to `true` to return the part of speech for each token. """ - def __init__(self, - *, - lemma: bool = None, - part_of_speech: bool = None) -> None: + def __init__( + self, + *, + lemma: Optional[bool] = None, + part_of_speech: Optional[bool] = None, + ) -> None: """ Initialize a SyntaxOptionsTokens object. @@ -5720,10 +5693,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptionsTokens': """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} - if 'lemma' in _dict: - args['lemma'] = _dict.get('lemma') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (lemma := _dict.get('lemma')) is not None: + args['lemma'] = lemma + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -5759,18 +5732,20 @@ def __ne__(self, other: 'SyntaxOptionsTokens') -> bool: return not self == other -class SyntaxResult(): +class SyntaxResult: """ Tokens and sentences returned from syntax analysis. - :attr List[TokenResult] tokens: (optional) - :attr List[SentenceResult] sentences: (optional) + :param List[TokenResult] tokens: (optional) + :param List[SentenceResult] sentences: (optional) """ - def __init__(self, - *, - tokens: List['TokenResult'] = None, - sentences: List['SentenceResult'] = None) -> None: + def __init__( + self, + *, + tokens: Optional[List['TokenResult']] = None, + sentences: Optional[List['SentenceResult']] = None, + ) -> None: """ Initialize a SyntaxResult object. @@ -5784,14 +5759,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxResult': """Initialize a SyntaxResult object from a json dictionary.""" args = {} - if 'tokens' in _dict: - args['tokens'] = [ - TokenResult.from_dict(x) for x in _dict.get('tokens') - ] - if 'sentences' in _dict: - args['sentences'] = [ - SentenceResult.from_dict(x) for x in _dict.get('sentences') - ] + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = [TokenResult.from_dict(v) for v in tokens] + if (sentences := _dict.get('sentences')) is not None: + args['sentences'] = [SentenceResult.from_dict(v) for v in sentences] return cls(**args) @classmethod @@ -5803,9 +5774,21 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = [x.to_dict() for x in self.tokens] + tokens_list = [] + for v in self.tokens: + if isinstance(v, dict): + tokens_list.append(v) + else: + tokens_list.append(v.to_dict()) + _dict['tokens'] = tokens_list if hasattr(self, 'sentences') and self.sentences is not None: - _dict['sentences'] = [x.to_dict() for x in self.sentences] + sentences_list = [] + for v in self.sentences: + if isinstance(v, dict): + sentences_list.append(v) + else: + sentences_list.append(v.to_dict()) + _dict['sentences'] = sentences_list return _dict def _to_dict(self): @@ -5827,18 +5810,20 @@ def __ne__(self, other: 'SyntaxResult') -> bool: return not self == other -class TargetedEmotionResults(): +class TargetedEmotionResults: """ Emotion results for a specified target. - :attr str text: (optional) Targeted text. - :attr EmotionScores emotion: (optional) The emotion results for the target. + :param str text: (optional) Targeted text. + :param EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, - *, - text: str = None, - emotion: 'EmotionScores' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + emotion: Optional['EmotionScores'] = None, + ) -> None: """ Initialize a TargetedEmotionResults object. @@ -5853,10 +5838,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TargetedEmotionResults': """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) return cls(**args) @classmethod @@ -5870,7 +5855,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): @@ -5892,16 +5880,21 @@ def __ne__(self, other: 'TargetedEmotionResults') -> bool: return not self == other -class TargetedSentimentResults(): +class TargetedSentimentResults: """ TargetedSentimentResults. - :attr str text: (optional) Targeted text. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param str text: (optional) Targeted text. + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, text: str = None, score: float = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a TargetedSentimentResults object. @@ -5916,10 +5909,10 @@ def __init__(self, *, text: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'TargetedSentimentResults': """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -5955,26 +5948,28 @@ def __ne__(self, other: 'TargetedSentimentResults') -> bool: return not self == other -class TokenResult(): +class TokenResult: """ TokenResult. - :attr str text: (optional) The token as it appears in the analyzed text. - :attr str part_of_speech: (optional) The part of speech of the token. For more + :param str text: (optional) The token as it appears in the analyzed text. + :param str part_of_speech: (optional) The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :attr List[int] location: (optional) Character offsets indicating the beginning + :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. - :attr str lemma: (optional) The + :param str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. """ - def __init__(self, - *, - text: str = None, - part_of_speech: str = None, - location: List[int] = None, - lemma: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + part_of_speech: Optional[str] = None, + location: Optional[List[int]] = None, + lemma: Optional[str] = None, + ) -> None: """ Initialize a TokenResult object. @@ -5996,14 +5991,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenResult': """Initialize a TokenResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'lemma' in _dict: - args['lemma'] = _dict.get('lemma') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech + if (location := _dict.get('location')) is not None: + args['location'] = location + if (lemma := _dict.get('lemma')) is not None: + args['lemma'] = lemma return cls(**args) @classmethod @@ -6047,6 +6042,7 @@ class PartOfSpeechEnum(str, Enum): The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). """ + ADJ = 'ADJ' ADP = 'ADP' ADV = 'ADV' diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index c769fb495..1b1b47bc6 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,10 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's -speech-recognition capabilities to produce transcripts of spoken audio. The service can +speech-recognition capabilities to produce transcripts of spoken audio. The service can transcribe speech from various languages and audio formats. In addition to basic transcription, the service can produce detailed information about many different aspects of the audio. It returns all JSON response content in the UTF-8 character set. @@ -27,11 +27,10 @@ have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum sampling rates of 8 kHz. The next-generation models offer high throughput and greater transcription accuracy. -Effective 15 March 2022, previous-generation models for all languages other than Arabic -and Japanese are deprecated. The deprecated models remain available until 15 September -2022, when they will be removed from the service and the documentation. You must migrate -to the equivalent next-generation model by the end of service date. For more information, -see [Migrating to next-generation +Effective **31 July 2023**, all previous-generation models will be removed from the +service and the documentation. Most previous-generation models were deprecated on 15 March +2022. You must migrate to the equivalent large speech model or next-generation model by 31 +July 2023. For more information, see [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: deprecated} For speech recognition, the service supports synchronous and asynchronous HTTP @@ -52,7 +51,7 @@ """ from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -96,7 +95,10 @@ def __init__( # Models ######################### - def list_models(self, **kwargs) -> DetailedResponse: + def list_models( + self, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -113,22 +115,33 @@ def list_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def get_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a model. @@ -139,31 +152,36 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-specific). :param str model_id: The identifier of the model in the form of its name - from the output of the [List models](#listmodels) method. (**Note:** The - model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` - instead.). + from the output of the [List models](#listmodels) method. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -172,35 +190,41 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: # Synchronous ######################### - def recognize(self, - audio: BinaryIO, - *, - content_type: str = None, - model: str = None, - language_customization_id: str = None, - acoustic_customization_id: str = None, - base_model_version: str = None, - customization_weight: float = None, - inactivity_timeout: int = None, - keywords: List[str] = None, - keywords_threshold: float = None, - max_alternatives: int = None, - word_alternatives_threshold: float = None, - word_confidence: bool = None, - timestamps: bool = None, - profanity_filter: bool = None, - smart_formatting: bool = None, - speaker_labels: bool = None, - customization_id: str = None, - grammar_name: str = None, - redaction: bool = None, - audio_metrics: bool = None, - end_of_phrase_silence_time: float = None, - split_transcript_at_phrase_end: bool = None, - speech_detector_sensitivity: float = None, - background_audio_suppression: float = None, - low_latency: bool = None, - **kwargs) -> DetailedResponse: + def recognize( + self, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + model: Optional[str] = None, + speech_begin_event: Optional[bool] = None, + enrichments: Optional[str] = None, + language_customization_id: Optional[str] = None, + acoustic_customization_id: Optional[str] = None, + base_model_version: Optional[str] = None, + customization_weight: Optional[float] = None, + inactivity_timeout: Optional[int] = None, + keywords: Optional[List[str]] = None, + keywords_threshold: Optional[float] = None, + max_alternatives: Optional[int] = None, + word_alternatives_threshold: Optional[float] = None, + word_confidence: Optional[bool] = None, + timestamps: Optional[bool] = None, + profanity_filter: Optional[bool] = None, + smart_formatting: Optional[bool] = None, + smart_formatting_version: Optional[int] = None, + speaker_labels: Optional[bool] = None, + grammar_name: Optional[str] = None, + redaction: Optional[bool] = None, + audio_metrics: Optional[bool] = None, + end_of_phrase_silence_time: Optional[float] = None, + split_transcript_at_phrase_end: Optional[bool] = None, + speech_detector_sensitivity: Optional[float] = None, + sad_module: Optional[int] = None, + background_audio_suppression: Optional[float] = None, + low_latency: Optional[bool] = None, + character_insertion_bias: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Recognize audio. @@ -260,25 +284,36 @@ def recognize(self, fails. **See also:** [Supported audio formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). - ### Next-generation models - The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 - kHz) models for many languages. Next-generation models have higher throughput than - the service's previous generation of `Broadband` and `Narrowband` models. When you - use next-generation models, the service can return transcriptions more quickly and - also provide noticeably better transcription accuracy. - You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Many next-generation models also support the - `low_latency` parameter, which is not available with previous-generation models. - Next-generation models do not support all of the parameters that are available for - use with previous-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to - next-generation + ### Large speech models and Next-generation models + The service supports large speech models and next-generation `Multimedia` (16 + kHz) and `Telephony` (8 kHz) models for many languages. Large speech models and + next-generation models have higher throughput than the service's previous + generation of `Broadband` and `Narrowband` models. When you use large speech + models and next-generation models, the service can return transcriptions more + quickly and also provide noticeably better transcription accuracy. + You specify a large speech model or next-generation model by using the `model` + query parameter, as you do a previous-generation model. Only the next-generation + models support the `low_latency` parameter, and all large speech models and + next-generation models support the `character_insertion_bias` parameter. These + parameters are not available with previous-generation models. + Large speech models and next-generation models do not support all of the speech + recognition parameters that are available for use with previous-generation models. + Next-generation models do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** + * [Large speech languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages) + * [Supported features for large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages#models-lsm-supported-features) * [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) * [Supported features for next-generation @@ -302,11 +337,36 @@ def recognize(self, :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. - :param str model: (optional) The identifier of the model that is to be used - for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for - speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + :param str model: (optional) The model to use for speech recognition. If + you omit the `model` parameter, the service uses the US English + `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_BroadbandModel`, you must either specify a model with the request or + specify a new default model for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). + :param bool speech_begin_event: (optional) If `true`, the service returns a + response object `SpeechActivity` which contains the time when a speech + activity is detected in the stream. This can be used both in standard and + low latency mode. This feature enables client applications to know that + some words/speech has been detected and the service is in the process of + decoding. This can be used in lieu of interim results in standard mode. Use + `sad_module: 2` to increase accuracy and performance in detecting speech + boundaries within the audio stream. See [Using speech recognition + parameters](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-service-features#features-parameters). + :param str enrichments: (optional) Speech transcript enrichment improves + readability of raw ASR transcripts by adding punctuation (periods, commas, + question marks, exclamation points) and intelligent capitalization + (sentence beginnings, proper nouns, acronyms, brand names). To enable + enrichment, add the `enrichments=punctuation` parameter to your recognition + request. Supported languages include English (US, UK, Australia, India), + French (France, Canada), German, Italian, Portuguese (Brazil, Portugal), + Spanish (Spain, Latin America, Argentina, Chile, Colombia, Mexico, Peru), + and Japanese. See [Speech transcript + enrichment](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speech-transcript-enrichment). :param str language_customization_id: (optional) The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match @@ -339,14 +399,19 @@ def recognize(self, to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization - weight was specified for the custom model when it was trained, the default - value is 0.3. A customization weight that you specify overrides a weight - that was specified when the custom model was trained. - The default value yields the best performance in general. Assign a higher - value if your audio makes frequent use of OOV words from the custom model. - Use caution when setting the weight: a higher value can improve the - accuracy of phrases from the custom model's domain, but it can negatively - affect performance on non-domain phrases. + weight was specified for the custom model when the model was trained, the + default value is: + * 0.5 for large speech models + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models + A customization weight that you specify overrides a weight that was + specified when the custom model was trained. The default value yields the + best performance in general. Assign a higher value if your audio makes + frequent use of OOV words from the custom model. Use caution when setting + the weight: a higher value can improve the accuracy of phrases from the + custom model's domain, but it can negatively affect performance on + non-domain phrases. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param int inactivity_timeout: (optional) The time in seconds after which, @@ -410,6 +475,10 @@ def recognize(self, (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param int smart_formatting_version: (optional) Smart formatting version + for large speech models and next-generation models is supported in US + English, Brazilian Portuguese, French, German, Spanish and French Canadian + languages. :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -419,15 +488,10 @@ def recognize(self, Australian English, US English, German, Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model) transcription only. - * _For next-generation models,_ the parameter can be used with Czech, - English (Australian, Indian, UK, and US), German, Japanese, Korean, and - Spanish transcription only. + * _For large speech models and next-generation models,_ the parameter can + be used with all available languages. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). - :param str customization_id: (optional) **Deprecated.** Use the - `language_customization_id` parameter to specify the customization ID - (GUID) of a custom language model that is to be used with the recognition - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -457,12 +521,12 @@ def recognize(self, default, the service returns no audio metrics. See [Audio metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio-metrics). - :param float end_of_phrase_silence_time: (optional) If `true`, specifies - the duration of the pause interval at which the service splits a transcript - into multiple final results. If the service detects pauses or extended - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. + :param float end_of_phrase_silence_time: (optional) Specifies the duration + of the pause interval at which the service splits a transcript into + multiple final results. If the service detects pauses or extended silence + before it reaches the end of the audio stream, its response can include + multiple final results. Silence indicates a point at which the speaker + pauses between spoken words or phrases. Specify a value for the pause interval in the range of 0.0 to 120.0. * A value greater than 0 specifies the interval that the service is to use for speech recognition. @@ -496,12 +560,20 @@ def recognize(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Speech detector + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). + :param int sad_module: (optional) Detects speech boundaries within the + audio stream with better performance, improved noise suppression, faster + responsiveness, and increased accuracy. + Specify `sad_module: 2` + See [Speech Activity Detection + (SAD)](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#sad). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -511,9 +583,11 @@ def recognize(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Background audio + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). @@ -524,13 +598,33 @@ def recognize(self, previous-generation models. The `low_latency` parameter causes the models to produce results even more quickly, though the results might be less accurate when the parameter is used. - The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available only for some next-generation models. - For a list of next-generation models that support low latency, see + The parameter is not available for large speech models and + previous-generation `Broadband` and `Narrowband` models. It is available + for most next-generation models. + * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For large speech models + and next-generation models, an indication of whether the service is biased + to recognize shorter or longer strings of characters when developing + transcription hypotheses. By default, the service is optimized to produce + the best balance of strings of different lengths. + The default bias is 0.0. The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechRecognitionResults` object @@ -538,14 +632,20 @@ def recognize(self, if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='recognize') + headers = { + 'Content-Type': content_type, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='recognize', + ) headers.update(sdk_headers) params = { 'model': model, + 'speech_begin_event': speech_begin_event, + 'enrichments': enrichments, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, @@ -559,30 +659,35 @@ def recognize(self, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, - 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, 'audio_metrics': audio_metrics, 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, + 'sad_module': sad_module, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias, } data = audio if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognize' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -591,11 +696,13 @@ def recognize(self, # Asynchronous ######################### - def register_callback(self, - callback_url: str, - *, - user_secret: str = None, - **kwargs) -> DetailedResponse: + def register_callback( + self, + callback_url: str, + *, + user_secret: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Register a callback. @@ -645,31 +752,42 @@ def register_callback(self, :rtype: DetailedResponse with `dict` result representing a `RegisterStatus` object """ - if callback_url is None: + if not callback_url: raise ValueError('callback_url must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='register_callback') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='register_callback', + ) headers.update(sdk_headers) - params = {'callback_url': callback_url, 'user_secret': user_secret} + params = { + 'callback_url': callback_url, + 'user_secret': user_secret, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/register_callback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def unregister_callback(self, callback_url: str, - **kwargs) -> DetailedResponse: + def unregister_callback( + self, + callback_url: str, + **kwargs, + ) -> DetailedResponse: """ Unregister a callback. @@ -686,63 +804,76 @@ def unregister_callback(self, callback_url: str, :rtype: DetailedResponse """ - if callback_url is None: + if not callback_url: raise ValueError('callback_url must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='unregister_callback') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='unregister_callback', + ) headers.update(sdk_headers) - params = {'callback_url': callback_url} + params = { + 'callback_url': callback_url, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/unregister_callback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_job(self, - audio: BinaryIO, - *, - content_type: str = None, - model: str = None, - callback_url: str = None, - events: str = None, - user_token: str = None, - results_ttl: int = None, - language_customization_id: str = None, - acoustic_customization_id: str = None, - base_model_version: str = None, - customization_weight: float = None, - inactivity_timeout: int = None, - keywords: List[str] = None, - keywords_threshold: float = None, - max_alternatives: int = None, - word_alternatives_threshold: float = None, - word_confidence: bool = None, - timestamps: bool = None, - profanity_filter: bool = None, - smart_formatting: bool = None, - speaker_labels: bool = None, - customization_id: str = None, - grammar_name: str = None, - redaction: bool = None, - processing_metrics: bool = None, - processing_metrics_interval: float = None, - audio_metrics: bool = None, - end_of_phrase_silence_time: float = None, - split_transcript_at_phrase_end: bool = None, - speech_detector_sensitivity: float = None, - background_audio_suppression: float = None, - low_latency: bool = None, - **kwargs) -> DetailedResponse: + def create_job( + self, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + model: Optional[str] = None, + callback_url: Optional[str] = None, + events: Optional[str] = None, + user_token: Optional[str] = None, + results_ttl: Optional[int] = None, + speech_begin_event: Optional[bool] = None, + enrichments: Optional[str] = None, + language_customization_id: Optional[str] = None, + acoustic_customization_id: Optional[str] = None, + base_model_version: Optional[str] = None, + customization_weight: Optional[float] = None, + inactivity_timeout: Optional[int] = None, + keywords: Optional[List[str]] = None, + keywords_threshold: Optional[float] = None, + max_alternatives: Optional[int] = None, + word_alternatives_threshold: Optional[float] = None, + word_confidence: Optional[bool] = None, + timestamps: Optional[bool] = None, + profanity_filter: Optional[bool] = None, + smart_formatting: Optional[bool] = None, + smart_formatting_version: Optional[int] = None, + speaker_labels: Optional[bool] = None, + grammar_name: Optional[str] = None, + redaction: Optional[bool] = None, + processing_metrics: Optional[bool] = None, + processing_metrics_interval: Optional[float] = None, + audio_metrics: Optional[bool] = None, + end_of_phrase_silence_time: Optional[float] = None, + split_transcript_at_phrase_end: Optional[bool] = None, + speech_detector_sensitivity: Optional[float] = None, + sad_module: Optional[int] = None, + background_audio_suppression: Optional[float] = None, + low_latency: Optional[bool] = None, + character_insertion_bias: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Create a job. @@ -828,25 +959,36 @@ def create_job(self, fails. **See also:** [Supported audio formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). - ### Next-generation models - The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 - kHz) models for many languages. Next-generation models have higher throughput than - the service's previous generation of `Broadband` and `Narrowband` models. When you - use next-generation models, the service can return transcriptions more quickly and - also provide noticeably better transcription accuracy. - You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Many next-generation models also support the - `low_latency` parameter, which is not available with previous-generation models. - Next-generation models do not support all of the parameters that are available for - use with previous-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to - next-generation + ### Large speech models and Next-generation models + The service supports large speech models and next-generation `Multimedia` (16 + kHz) and `Telephony` (8 kHz) models for many languages. Large speech models and + next-generation models have higher throughput than the service's previous + generation of `Broadband` and `Narrowband` models. When you use large speech + models and next-generation models, the service can return transcriptions more + quickly and also provide noticeably better transcription accuracy. + You specify a large speech model or next-generation model by using the `model` + query parameter, as you do a previous-generation model. Only the next-generation + models support the `low_latency` parameter, and all large speech models and + next-generation models support the `character_insertion_bias` parameter. These + parameters are not available with previous-generation models. + Large speech models and next-generation models do not support all of the speech + recognition parameters that are available for use with previous-generation models. + Next-generation models do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** + * [Large speech languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages) + * [Supported features for large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages#models-lsm-supported-features) * [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) * [Supported features for next-generation @@ -856,11 +998,17 @@ def create_job(self, :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. - :param str model: (optional) The identifier of the model that is to be used - for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for - speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + :param str model: (optional) The model to use for speech recognition. If + you omit the `model` parameter, the service uses the US English + `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_BroadbandModel`, you must either specify a model with the request or + specify a new default model for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using the [Register a callback](#registercallback) method. You can include the @@ -897,6 +1045,25 @@ def create_job(self, via a callback, the results must be retrieved within this time. Omit the parameter to use a time to live of one week. The parameter is valid with or without a callback URL. + :param bool speech_begin_event: (optional) If `true`, the service returns a + response object `SpeechActivity` which contains the time when a speech + activity is detected in the stream. This can be used both in standard and + low latency mode. This feature enables client applications to know that + some words/speech has been detected and the service is in the process of + decoding. This can be used in lieu of interim results in standard mode. Use + `sad_module: 2` to increase accuracy and performance in detecting speech + boundaries within the audio stream. See [Using speech recognition + parameters](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-service-features#features-parameters). + :param str enrichments: (optional) Speech transcript enrichment improves + readability of raw ASR transcripts by adding punctuation (periods, commas, + question marks, exclamation points) and intelligent capitalization + (sentence beginnings, proper nouns, acronyms, brand names). To enable + enrichment, add the `enrichments=punctuation` parameter to your recognition + request. Supported languages include English (US, UK, Australia, India), + French (France, Canada), German, Italian, Portuguese (Brazil, Portugal), + Spanish (Spain, Latin America, Argentina, Chile, Colombia, Mexico, Peru), + and Japanese. See [Speech transcript + enrichment](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speech-transcript-enrichment). :param str language_customization_id: (optional) The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match @@ -929,14 +1096,19 @@ def create_job(self, to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization - weight was specified for the custom model when it was trained, the default - value is 0.3. A customization weight that you specify overrides a weight - that was specified when the custom model was trained. - The default value yields the best performance in general. Assign a higher - value if your audio makes frequent use of OOV words from the custom model. - Use caution when setting the weight: a higher value can improve the - accuracy of phrases from the custom model's domain, but it can negatively - affect performance on non-domain phrases. + weight was specified for the custom model when the model was trained, the + default value is: + * 0.5 for large speech models + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models + A customization weight that you specify overrides a weight that was + specified when the custom model was trained. The default value yields the + best performance in general. Assign a higher value if your audio makes + frequent use of OOV words from the custom model. Use caution when setting + the weight: a higher value can improve the accuracy of phrases from the + custom model's domain, but it can negatively affect performance on + non-domain phrases. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param int inactivity_timeout: (optional) The time in seconds after which, @@ -1000,6 +1172,10 @@ def create_job(self, (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param int smart_formatting_version: (optional) Smart formatting version + for large speech models and next-generation models is supported in US + English, Brazilian Portuguese, French, German, Spanish and French Canadian + languages. :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -1009,15 +1185,10 @@ def create_job(self, Australian English, US English, German, Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model) transcription only. - * _For next-generation models,_ the parameter can be used with Czech, - English (Australian, Indian, UK, and US), German, Japanese, Korean, and - Spanish transcription only. + * _For large speech models and next-generation models,_ the parameter can + be used with all available languages. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). - :param str customization_id: (optional) **Deprecated.** Use the - `language_customization_id` parameter to specify the customization ID - (GUID) of a custom language model that is to be used with the recognition - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -1069,12 +1240,12 @@ def create_job(self, default, the service returns no audio metrics. See [Audio metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio-metrics). - :param float end_of_phrase_silence_time: (optional) If `true`, specifies - the duration of the pause interval at which the service splits a transcript - into multiple final results. If the service detects pauses or extended - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. + :param float end_of_phrase_silence_time: (optional) Specifies the duration + of the pause interval at which the service splits a transcript into + multiple final results. If the service detects pauses or extended silence + before it reaches the end of the audio stream, its response can include + multiple final results. Silence indicates a point at which the speaker + pauses between spoken words or phrases. Specify a value for the pause interval in the range of 0.0 to 120.0. * A value greater than 0 specifies the interval that the service is to use for speech recognition. @@ -1108,12 +1279,20 @@ def create_job(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Speech detector + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). + :param int sad_module: (optional) Detects speech boundaries within the + audio stream with better performance, improved noise suppression, faster + responsiveness, and increased accuracy. + Specify `sad_module: 2` + See [Speech Activity Detection + (SAD)](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#sad). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -1123,9 +1302,11 @@ def create_job(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Background audio + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). @@ -1136,13 +1317,33 @@ def create_job(self, previous-generation models. The `low_latency` parameter causes the models to produce results even more quickly, though the results might be less accurate when the parameter is used. - The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available only for some next-generation models. - For a list of next-generation models that support low latency, see + The parameter is not available for large speech models and + previous-generation `Broadband` and `Narrowband` models. It is available + for most next-generation models. + * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For large speech models + and next-generation models, an indication of whether the service is biased + to recognize shorter or longer strings of characters when developing + transcription hypotheses. By default, the service is optimized to produce + the best balance of strings of different lengths. + The default bias is 0.0. The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object @@ -1150,10 +1351,14 @@ def create_job(self, if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_job') + headers = { + 'Content-Type': content_type, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_job', + ) headers.update(sdk_headers) params = { @@ -1162,6 +1367,8 @@ def create_job(self, 'events': events, 'user_token': user_token, 'results_ttl': results_ttl, + 'speech_begin_event': speech_begin_event, + 'enrichments': enrichments, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, @@ -1175,8 +1382,8 @@ def create_job(self, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, - 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, 'processing_metrics': processing_metrics, @@ -1185,27 +1392,35 @@ def create_job(self, 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, + 'sad_module': sad_module, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias, } data = audio if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognitions' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def check_jobs(self, **kwargs) -> DetailedResponse: + def check_jobs( + self, + **kwargs, + ) -> DetailedResponse: """ Check jobs. @@ -1226,22 +1441,33 @@ def check_jobs(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='check_jobs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_jobs', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognitions' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def check_job(self, id: str, **kwargs) -> DetailedResponse: + def check_job( + self, + id: str, + **kwargs, + ) -> DetailedResponse: """ Check a job. @@ -1266,28 +1492,39 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object """ - if id is None: + if not id: raise ValueError('id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='check_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_job', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['id'] path_param_values = self.encode_path_vars(id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/recognitions/{id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_job(self, id: str, **kwargs) -> DetailedResponse: + def delete_job( + self, + id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a job. @@ -1307,24 +1544,29 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if id is None: + if not id: raise ValueError('id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_job', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['id'] path_param_values = self.encode_path_vars(id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/recognitions/{id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1333,13 +1575,15 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: # Custom language models ######################### - def create_language_model(self, - name: str, - base_model_name: str, - *, - dialect: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_language_model( + self, + name: str, + base_model_name: str, + *, + dialect: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom language model. @@ -1351,24 +1595,59 @@ def create_language_model(self, The service returns an error if you attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your model count is below the limit. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to - next-generation + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** * [Create a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#createModel-language) * [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) + ### Large speech models and Next-generation models + The service supports large speech models and next-generation `Multimedia` (16 + kHz) and `Telephony` (8 kHz) models for many languages. Large speech models and + next-generation models have higher throughput than the service's previous + generation of `Broadband` and `Narrowband` models. When you use large speech + models and next-generation models, the service can return transcriptions more + quickly and also provide noticeably better transcription accuracy. + You specify a large speech model or next-generation model by using the `model` + query parameter, as you do a previous-generation model. Only the next-generation + models support the `low_latency` parameter, and all large speech models and + next-generation models support the `character_insertion_bias` parameter. These + parameters are not available with previous-generation models. + Large speech models and next-generation models do not support all of the speech + recognition parameters that are available for use with previous-generation models. + Next-generation models do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). + **See also:** + * [Large speech languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages) + * [Supported features for large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages#models-lsm-supported-features) + * [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) + * [Supported features for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features). :param str name: A user-defined name for the new custom language model. Use - a name that is unique among all custom language models that you own. Use a - localized name that matches the language of the custom model. Use a name + a localized name that matches the language of the custom model. Use a name that describes the domain of the custom model, such as `Medical custom - model` or `Legal custom model`. + model` or `Legal custom model`. Use a name that is unique among all custom + language models that you own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str base_model_name: The name of the base language model that is to be customized by the new custom language model. The new custom model can be used only with the base model that it customizes. @@ -1393,9 +1672,10 @@ def create_language_model(self, `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) All values that you pass for the `dialect` field are case-insensitive. - :param str description: (optional) A description of the new custom language - model. Use a localized description that matches the language of the custom - model. + :param str description: (optional) A recommended description of the new + custom language model. Use a localized description that matches the + language of the custom model. Include a maximum of 128 characters in the + description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object @@ -1406,16 +1686,18 @@ def create_language_model(self, if base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_language_model', + ) headers.update(sdk_headers) data = { 'name': name, 'base_model_name': base_model_name, 'dialect': dialect, - 'description': description + 'description': description, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1423,21 +1705,26 @@ def create_language_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_language_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_language_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom language models. @@ -1457,8 +1744,7 @@ def list_language_models(self, five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). @@ -1468,28 +1754,38 @@ def list_language_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_language_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_language_models', + ) headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom language model. @@ -1510,29 +1806,39 @@ def get_language_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom language model. @@ -1555,35 +1861,44 @@ def delete_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def train_language_model(self, - customization_id: str, - *, - word_type_to_add: str = None, - customization_weight: float = None, - **kwargs) -> DetailedResponse: + def train_language_model( + self, + customization_id: str, + *, + word_type_to_add: Optional[str] = None, + customization_weight: Optional[float] = None, + strict: Optional[bool] = None, + force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Train a custom language model. @@ -1600,16 +1915,24 @@ def train_language_model(self, indicate that the training process has begun. You can monitor the status of the training by using the [Get a custom language model](#getlanguagemodel) method to poll the model's status. Use a loop to check - the status every 10 seconds. The method returns a `LanguageModel` object that - includes `status` and `progress` fields. A status of `available` means that the - custom model is trained and ready to use. The service cannot accept subsequent - training requests or requests to add new resources until the existing request - completes. + the status every 10 seconds. If you added custom words directly to a custom model + that is based on a next-generation model, allow for some minutes of extra training + time for the model. + The method returns a `LanguageModel` object that includes `status` and `progress` + fields. A status of `available` means that the custom model is trained and ready + to use. The service cannot accept subsequent training requests or requests to add + new resources until the existing request completes. + For custom models that are based on improved base language models, training also + performs an automatic upgrade to a newer version of the base model. You do not + need to use the [Upgrade a custom language model](#upgradelanguagemodel) method to + perform the upgrade. **See also:** - * [Train the custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) * [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) + * [Train the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) + * [Upgrading custom language models that are based on improved next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng) ### Training failures Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as @@ -1634,14 +1957,19 @@ def train_language_model(self, * `user` trains the model only on custom words that were added or modified by the user directly. The model is not trained on new words extracted from corpora or grammars. - _For custom models that are based on next-generation models_, the service - ignores the parameter. The words resource contains only custom words that - the user adds or modifies directly, so the parameter is unnecessary. + _For custom models that are based on large speech models and + next-generation models_, the service ignores the `word_type_to_add` + parameter. The words resource contains only custom words that the user adds + or modifies directly, so the parameter is unnecessary. :param float customization_weight: (optional) Specifies a customization weight for the custom language model. The customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for speech recognition. Specify a - value between 0.0 and 1.0; the default is 0.3. + value between 0.0 and 1.0. The default value is: + * 0.5 for large speech models + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the @@ -1652,26 +1980,46 @@ def train_language_model(self, customization weight for that request. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). + :param bool strict: (optional) If `false`, allows training of the custom + language model to proceed as long as the model contains at least one valid + resource. The method returns an array of `TrainingWarning` objects that + lists any invalid resources. By default (`true`), training of a custom + language model fails (status code 400) if the model contains one or more + invalid resources (corpus files, grammar files, or custom words). + :param bool force: (optional) If `true`, forces the training of the custom + language model regardless of whether it contains any changes (is in the + `ready` or `available` state). By default (`false`), the model must be in + the `ready` state to be trained. You can use the parameter to train and + thus upgrade a custom model that is based on an improved next-generation + model. *The parameter is available only for IBM Cloud, not for IBM Cloud + Pak for Data.* + See [Upgrading a custom language model based on an improved next-generation + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='train_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_language_model', + ) headers.update(sdk_headers) params = { 'word_type_to_add': word_type_to_add, - 'customization_weight': customization_weight + 'customization_weight': customization_weight, + 'strict': strict, + 'force': force, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1679,16 +2027,21 @@ def train_language_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/train'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def reset_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def reset_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Reset a custom language model. @@ -1713,16 +2066,19 @@ def reset_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='reset_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1730,13 +2086,20 @@ def reset_language_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/reset'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def upgrade_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def upgrade_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Upgrade a custom language model. @@ -1755,11 +2118,17 @@ def upgrade_language_model(self, customization_id: str, upgrade is complete, the model resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until the upgrade completes. + For custom models that are based on improved base language models, the [Train a + custom language model](#trainlanguagemodel) method also performs an automatic + upgrade to a newer version of the base model. You do not need to use the upgrade + method. **See also:** + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) * [Upgrading a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language) - * [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). + * [Upgrading custom language models that are based on improved next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1770,16 +2139,19 @@ def upgrade_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='upgrade_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1787,7 +2159,11 @@ def upgrade_language_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/upgrade_model'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1796,7 +2172,11 @@ def upgrade_language_model(self, customization_id: str, # Custom corpora ######################### - def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_corpora( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List corpora. @@ -1817,16 +2197,19 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Corpora` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_corpora') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_corpora', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1834,18 +2217,24 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_corpus(self, - customization_id: str, - corpus_name: str, - corpus_file: BinaryIO, - *, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_corpus( + self, + customization_id: str, + corpus_name: str, + corpus_file: BinaryIO, + *, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a corpus. @@ -1868,13 +2257,17 @@ def add_corpus(self, additional resources to the custom model or to train the model until the service's analysis of the corpus for the current request completes. Use the [Get a corpus](#getcorpus) method to check the status of the analysis. + _For custom models that are based on large speech models_, the service parses and + extracts word sequences from one or multiple corpora files. The characters help + the service learn and predict character sequences from audio. _For custom models that are based on previous-generation models_, the service auto-populates the model's words resource with words from the corpus that are not found in its base vocabulary. These words are referred to as out-of-vocabulary (OOV) words. After adding a corpus, you must validate the words resource to ensure that each OOV word's definition is complete and valid. You can use the [List custom words](#listwords) method to examine the words resource. You can use other - words method to eliminate typos and modify how words are pronounced as needed. + words method to eliminate typos and modify how words are pronounced and displayed + as needed. To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and extract @@ -1893,11 +2286,11 @@ def add_corpus(self, model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addCorpus) * [Working with corpora for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora) - * [Working with corpora for next-generation + * [Working with corpora for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingCorpora-ng) * [Validating a words resource for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) - * [Validating a words resource for next-generation + * [Validating a words resource for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :param str customization_id: The customization ID (GUID) of the custom @@ -1938,25 +2331,30 @@ def add_corpus(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') if corpus_file is None: raise ValueError('corpus_file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_corpus', + ) headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } form_data = [] form_data.append(('corpus_file', (None, corpus_file, 'text/plain'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -1964,17 +2362,23 @@ def add_corpus(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> DetailedResponse: + def get_corpus( + self, + customization_id: str, + corpus_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a corpus. @@ -1997,18 +2401,21 @@ def get_corpus(self, customization_id: str, corpus_name: str, :rtype: DetailedResponse with `dict` result representing a `Corpus` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_corpus', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2016,13 +2423,21 @@ def get_corpus(self, customization_id: str, corpus_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> DetailedResponse: + def delete_corpus( + self, + customization_id: str, + corpus_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a corpus. @@ -2049,18 +2464,21 @@ def delete_corpus(self, customization_id: str, corpus_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_corpus', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2068,9 +2486,11 @@ def delete_corpus(self, customization_id: str, corpus_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2079,12 +2499,14 @@ def delete_corpus(self, customization_id: str, corpus_name: str, # Custom words ######################### - def list_words(self, - customization_id: str, - *, - word_type: str = None, - sort: str = None, - **kwargs) -> DetailedResponse: + def list_words( + self, + customization_id: str, + *, + word_type: Optional[str] = None, + sort: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom words. @@ -2092,10 +2514,13 @@ def list_words(self, all words from the custom model's words resource, only custom words that were added or modified by the user, or, _for a custom model that is based on a previous-generation model_, only out-of-vocabulary (OOV) words that were extracted - from corpora or are recognized by grammars. You can also indicate the order in - which the service is to return words; by default, the service lists words in - ascending alphabetical order. You must use credentials for the instance of the - service that owns a model to list information about its words. + from corpora or are recognized by grammars. _For a custom model that is based on a + next-generation model_, you can list all words or only those words that were added + directly by a user, which return the same results. + You can also indicate the order in which the service is to return words; by + default, the service lists words in ascending alphabetical order. You must use + credentials for the instance of the service that owns a model to list information + about its words. **See also:** [Listing words from a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#listWords). @@ -2127,18 +2552,24 @@ def list_words(self, :rtype: DetailedResponse with `dict` result representing a `Words` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words', + ) headers.update(sdk_headers) - params = {'word_type': word_type, 'sort': sort} + params = { + 'word_type': word_type, + 'sort': sort, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2146,16 +2577,22 @@ def list_words(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_words(self, customization_id: str, words: List['CustomWord'], - **kwargs) -> DetailedResponse: + def add_words( + self, + customization_id: str, + words: List['CustomWord'], + **kwargs, + ) -> DetailedResponse: """ Add custom words. @@ -2181,16 +2618,22 @@ def add_words(self, customization_id: str, words: List['CustomWord'], transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM` is to be displayed as `IBM™`. - * The `sounds_like` field, _which can be used only with a custom model that is - based on a previous-generation model_, provides an array of one or more - pronunciations for the word. Use the parameter to specify how the word can be - pronounced by users. Use the parameter for words that are difficult to pronounce, - foreign words, acronyms, and so on. For example, you might specify that the word - `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like - pronunciations for a word. If you omit the `sounds_like` field, the service - attempts to set the field to its pronunciation of the word. It cannot generate a - pronunciation for all words, so you must review the word's definition to ensure - that it is complete and valid. + * The `sounds_like` field provides an array of one or more pronunciations for the + word. Use the parameter to specify how the word can be pronounced by users. Use + the parameter for words that are difficult to pronounce, foreign words, acronyms, + and so on. For example, you might specify that the word `IEEE` can sound like `I + triple E`. You can specify a maximum of five sounds-like pronunciations for a + word. _For a custom model that is based on a previous-generation model_, if you + omit the `sounds_like` field, the service attempts to set the field to its + pronunciation of the word. It cannot generate a pronunciation for all words, so + you must review the word's definition to ensure that it is complete and valid. + * The `mapping_only` field provides parameter for custom words. You can use the + 'mapping_only' key in custom words as a form of post processing. This key + parameter has a boolean value to determine whether 'sounds_like' (for non-Japanese + models) or word (for Japanese) is not used for the model fine-tuning, but for the + replacement for 'display_as'. This feature helps you when you use custom words + exclusively to map 'sounds_like' (or word) to 'display_as' value. When you use + custom words solely for post-processing purposes that does not need fine-tuning. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and @@ -2215,11 +2658,11 @@ def add_words(self, customization_id: str, words: List['CustomWord'], model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) * [Working with custom words for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) - * [Working with custom words for next-generation + * [Working with custom words for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng) * [Validating a words resource for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) - * [Validating a words resource for next-generation + * [Validating a words resource for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :param str customization_id: The customization ID (GUID) of the custom @@ -2234,24 +2677,29 @@ def add_words(self, customization_id: str, words: List['CustomWord'], :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words', + ) headers.update(sdk_headers) - data = {'words': words} + data = { + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2259,22 +2707,27 @@ def add_words(self, customization_id: str, words: List['CustomWord'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def add_word(self, - customization_id: str, - word_name: str, - *, - word: str = None, - sounds_like: List[str] = None, - display_as: str = None, - **kwargs) -> DetailedResponse: + def add_word( + self, + customization_id: str, + word_name: str, + *, + word: Optional[str] = None, + mapping_only: Optional[List[str]] = None, + sounds_like: Optional[List[str]] = None, + display_as: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a custom word. @@ -2299,16 +2752,15 @@ def add_word(self, transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM` is to be displayed as `IBM™`. - * The `sounds_like` field, _which can be used only with a custom model that is - based on a previous-generation model_, provides an array of one or more - pronunciations for the word. Use the parameter to specify how the word can be - pronounced by users. Use the parameter for words that are difficult to pronounce, - foreign words, acronyms, and so on. For example, you might specify that the word - `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like - pronunciations for a word. If you omit the `sounds_like` field, the service - attempts to set the field to its pronunciation of the word. It cannot generate a - pronunciation for all words, so you must review the word's definition to ensure - that it is complete and valid. + * The `sounds_like` field provides an array of one or more pronunciations for the + word. Use the parameter to specify how the word can be pronounced by users. Use + the parameter for words that are difficult to pronounce, foreign words, acronyms, + and so on. For example, you might specify that the word `IEEE` can sound like `i + triple e`. You can specify a maximum of five sounds-like pronunciations for a + word. _For custom models that are based on previous-generation models_, if you + omit the `sounds_like` field, the service attempts to set the field to its + pronunciation of the word. It cannot generate a pronunciation for all words, so + you must review the word's definition to ensure that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error, it does not add the word to the words resource. Use @@ -2318,11 +2770,11 @@ def add_word(self, model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) * [Working with custom words for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) - * [Working with custom words for next-generation + * [Working with custom words for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng) * [Validating a words resource for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) - * [Validating a words resource for next-generation + * [Validating a words resource for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :param str customization_id: The customization ID (GUID) of the custom @@ -2330,55 +2782,74 @@ def add_word(self, request with credentials for the instance of the service that owns the custom model. :param str word_name: The custom word that is to be added to or updated in - the custom language model. Do not include spaces in the word. Use a `-` + the custom language model. Do not use characters that need to be + URL-encoded, for example, spaces, slashes, backslashes, colons, ampersands, + double quotes, plus signs, equals signs, or question marks. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. URL-encode the word if it includes non-ASCII characters. For more information, see [Character encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). :param str word: (optional) For the [Add custom words](#addwords) method, you must specify the custom word that is to be added to or updated in the - custom model. Do not include spaces in the word. Use a `-` (dash) or `_` - (underscore) to connect the tokens of compound words. + custom model. Do not use characters that need to be URL-encoded, for + example, spaces, slashes, backslashes, colons, ampersands, double quotes, + plus signs, equals signs, or question marks. Use a `-` (dash) or `_` + (underscore) to connect the tokens of compound words. A Japanese custom + word can include at most 25 characters, not including leading or trailing + spaces. Omit this parameter for the [Add a custom word](#addword) method. - :param List[str] sounds_like: (optional) _For a custom model that is based - on a previous-generation model_, an array of sounds-like pronunciations for - the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the - parameter to have the service automatically generate a sounds-like - pronunciation for the word. + :param List[str] mapping_only: (optional) Parameter for custom words. You + can use the 'mapping_only' key in custom words as a form of post + processing. This key parameter has a boolean value to determine whether + 'sounds_like' (for non-Japanese models) or word (for Japanese) is not used + for the model fine-tuning, but for the replacement for 'display_as'. This + feature helps you when you use custom words exclusively to map + 'sounds_like' (or word) to 'display_as' value. When you use custom words + solely for post-processing purposes that does not need fine-tuning. + :param List[str] sounds_like: (optional) As array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a + word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation - can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this - field. Custom models based on next-generation models do not support the - `sounds_like` field. The service ignores the field. + can include at most 40 characters, not including leading or trailing + spaces. A Japanese pronunciation can include at most 25 characters, not + including leading or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service + uses the spelling of the word as the display-as value if you omit the + field. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word', + ) headers.update(sdk_headers) data = { 'word': word, + 'mapping_only': mapping_only, 'sounds_like': sounds_like, - 'display_as': display_as + 'display_as': display_as, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2386,6 +2857,7 @@ def add_word(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2393,16 +2865,22 @@ def add_word(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_word(self, customization_id: str, word_name: str, - **kwargs) -> DetailedResponse: + def get_word( + self, + customization_id: str, + word_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom word. @@ -2425,18 +2903,21 @@ def get_word(self, customization_id: str, word_name: str, :rtype: DetailedResponse with `dict` result representing a `Word` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2444,13 +2925,21 @@ def get_word(self, customization_id: str, word_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_word(self, customization_id: str, word_name: str, - **kwargs) -> DetailedResponse: + def delete_word( + self, + customization_id: str, + word_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom word. @@ -2477,18 +2966,21 @@ def delete_word(self, customization_id: str, word_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2496,9 +2988,11 @@ def delete_word(self, customization_id: str, word_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2507,8 +3001,11 @@ def delete_word(self, customization_id: str, word_name: str, # Custom grammars ######################### - def list_grammars(self, customization_id: str, - **kwargs) -> DetailedResponse: + def list_grammars( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List grammars. @@ -2532,16 +3029,19 @@ def list_grammars(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `Grammars` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_grammars') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_grammars', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2549,19 +3049,25 @@ def list_grammars(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_grammar(self, - customization_id: str, - grammar_name: str, - grammar_file: BinaryIO, - content_type: str, - *, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_grammar( + self, + customization_id: str, + grammar_name: str, + grammar_file: BinaryIO, + content_type: str, + *, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a grammar. @@ -2647,26 +3153,33 @@ def add_grammar(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') if grammar_file is None: raise ValueError('grammar_file must be provided') - if content_type is None: + if not content_type: raise ValueError('content_type must be provided') - headers = {'Content-Type': content_type} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_grammar') + headers = { + 'Content-Type': content_type, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_grammar', + ) headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } data = grammar_file if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2675,17 +3188,23 @@ def add_grammar(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> DetailedResponse: + def get_grammar( + self, + customization_id: str, + grammar_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a grammar. @@ -2711,18 +3230,21 @@ def get_grammar(self, customization_id: str, grammar_name: str, :rtype: DetailedResponse with `dict` result representing a `Grammar` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_grammar', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2731,13 +3253,21 @@ def get_grammar(self, customization_id: str, grammar_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> DetailedResponse: + def delete_grammar( + self, + customization_id: str, + grammar_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a grammar. @@ -2767,18 +3297,21 @@ def delete_grammar(self, customization_id: str, grammar_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_grammar', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2787,9 +3320,11 @@ def delete_grammar(self, customization_id: str, grammar_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2798,12 +3333,14 @@ def delete_grammar(self, customization_id: str, grammar_name: str, # Custom acoustic models ######################### - def create_acoustic_model(self, - name: str, - base_model_name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def create_acoustic_model( + self, + name: str, + base_model_name: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom acoustic model. @@ -2816,32 +3353,34 @@ def create_acoustic_model(self, do not lose any models, but you cannot create any more until your model count is below the limit. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to - next-generation + previous-generation models. It is not supported for large speech models and + next-generation models. + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). :param str name: A user-defined name for the new custom acoustic model. Use - a name that is unique among all custom acoustic models that you own. Use a - localized name that matches the language of the custom model. Use a name + a localized name that matches the language of the custom model. Use a name that describes the acoustic environment of the custom model, such as - `Mobile custom model` or `Noisy car custom model`. + `Mobile custom model` or `Noisy car custom model`. Use a name that is + unique among all custom acoustic models that you own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str base_model_name: The name of the base language model that is to be customized by the new custom acoustic model. The new custom model can be - used only with the base model that it customizes. (**Note:** The model - `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + used only with the base model that it customizes. To determine whether a base model supports acoustic model customization, refer to [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). - :param str description: (optional) A description of the new custom acoustic - model. Use a localized description that matches the language of the custom - model. + :param str description: (optional) A recommended description of the new + custom acoustic model. Use a localized description that matches the + language of the custom model. Include a maximum of 128 characters in the + description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object @@ -2852,15 +3391,17 @@ def create_acoustic_model(self, if base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_acoustic_model', + ) headers.update(sdk_headers) data = { 'name': name, 'base_model_name': base_model_name, - 'description': description + 'description': description, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2868,21 +3409,26 @@ def create_acoustic_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_acoustic_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_acoustic_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom acoustic models. @@ -2892,7 +3438,8 @@ def list_acoustic_models(self, all languages. You must use credentials for the instance of the service that owns a model to list information about it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). @@ -2901,8 +3448,7 @@ def list_acoustic_models(self, five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). @@ -2912,35 +3458,46 @@ def list_acoustic_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_acoustic_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_acoustic_models', + ) headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom acoustic model. Gets information about a specified custom acoustic model. You must use credentials for the instance of the service that owns a model to list information about it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). @@ -2953,16 +3510,19 @@ def get_acoustic_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2970,13 +3530,20 @@ def get_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom acoustic model. @@ -2985,7 +3552,8 @@ def delete_acoustic_model(self, customization_id: str, processed. You must use credentials for the instance of the service that owns a model to delete it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Deleting a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#deleteModel-acoustic). @@ -2998,16 +3566,19 @@ def delete_acoustic_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3015,18 +3586,23 @@ def delete_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def train_acoustic_model(self, - customization_id: str, - *, - custom_language_model_id: str = None, - **kwargs) -> DetailedResponse: + def train_acoustic_model( + self, + customization_id: str, + *, + custom_language_model_id: Optional[str] = None, + strict: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Train a custom acoustic model. @@ -3061,7 +3637,8 @@ def train_acoustic_model(self, same version of the same base model, and the custom language model must be fully trained and available. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** * [Train the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic) @@ -3071,8 +3648,13 @@ def train_acoustic_model(self, Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as another training request or a request to add audio resources to the model. - * The custom model contains less than 10 minutes or more than 200 hours of audio - data. + * The custom model contains less than 10 minutes of audio that includes speech, + not silence. + * The custom model contains more than 50 hours of audio (for IBM Cloud) or more + that 200 hours of audio (for IBM Cloud Pak for Data). **Note:** For IBM Cloud, the + maximum hours of audio for a custom acoustic model was reduced from 200 to 50 + hours in August and September 2022. For more information, see [Maximum hours of + audio](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audioResources#audioMaximum). * You passed a custom language model with the `custom_language_model_id` query parameter that is not in the available state. A custom language model must be fully trained and available to be used to train a custom acoustic model. @@ -3097,23 +3679,35 @@ def train_acoustic_model(self, custom acoustic model, and the custom language model must be fully trained and available. The credentials specified with the request must own both custom models. + :param bool strict: (optional) If `false`, allows training of the custom + acoustic model to proceed as long as the model contains at least one valid + audio resource. The method returns an array of `TrainingWarning` objects + that lists any invalid resources. By default (`true`), training of a custom + acoustic model fails (status code 400) if the model contains one or more + invalid audio resources. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='train_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_acoustic_model', + ) headers.update(sdk_headers) - params = {'custom_language_model_id': custom_language_model_id} + params = { + 'custom_language_model_id': custom_language_model_id, + 'strict': strict, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3121,16 +3715,21 @@ def train_acoustic_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/train'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def reset_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def reset_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Reset a custom acoustic model. @@ -3143,7 +3742,8 @@ def reset_acoustic_model(self, customization_id: str, request completes. You must use credentials for the instance of the service that owns a model to reset it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Resetting a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#resetModel-acoustic). @@ -3156,16 +3756,19 @@ def reset_acoustic_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='reset_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3173,17 +3776,23 @@ def reset_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/reset'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def upgrade_acoustic_model(self, - customization_id: str, - *, - custom_language_model_id: str = None, - force: bool = None, - **kwargs) -> DetailedResponse: + def upgrade_acoustic_model( + self, + customization_id: str, + *, + custom_language_model_id: Optional[str] = None, + force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Upgrade a custom acoustic model. @@ -3210,7 +3819,8 @@ def upgrade_acoustic_model(self, the custom acoustic model can be upgraded. Omit the parameter if the custom acoustic model was not trained with a custom language model. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Upgrading a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-acoustic). @@ -3236,21 +3846,24 @@ def upgrade_acoustic_model(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='upgrade_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_acoustic_model', + ) headers.update(sdk_headers) params = { 'custom_language_model_id': custom_language_model_id, - 'force': force + 'force': force, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3258,10 +3871,12 @@ def upgrade_acoustic_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/upgrade_model'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3270,7 +3885,11 @@ def upgrade_acoustic_model(self, # Custom audio resources ######################### - def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_audio( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List audio resources. @@ -3281,7 +3900,8 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: to a request to add it to the custom acoustic model. You must use credentials for the instance of the service that owns a model to list its audio resources. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). @@ -3294,16 +3914,19 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `AudioResources` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3311,20 +3934,26 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_audio(self, - customization_id: str, - audio_name: str, - audio_resource: BinaryIO, - *, - content_type: str = None, - contained_content_type: str = None, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_audio( + self, + customization_id: str, + audio_name: str, + audio_resource: BinaryIO, + *, + content_type: Optional[str] = None, + contained_content_type: Optional[str] = None, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add an audio resource. @@ -3341,11 +3970,15 @@ def add_audio(self, You can use this method to add any number of audio resources to a custom model by calling the method once for each audio or archive file. You can add multiple different audio resources at the same time. You must add a minimum of 10 minutes - and a maximum of 200 hours of audio that includes speech, not just silence, to a - custom acoustic model before you can train it. No audio resource, audio- or - archive-type, can be larger than 100 MB. To add an audio resource that has the - same name as an existing audio resource, set the `allow_overwrite` parameter to - `true`; otherwise, the request fails. + of audio that includes speech, not just silence, to a custom acoustic model before + you can train it. No audio resource, audio- or archive-type, can be larger than + 100 MB. To add an audio resource that has the same name as an existing audio + resource, set the `allow_overwrite` parameter to `true`; otherwise, the request + fails. A custom model can contain no more than 50 hours of audio (for IBM Cloud) + or 200 hours of audio (for IBM Cloud Pak for Data). **Note:** For IBM Cloud, the + maximum hours of audio for a custom acoustic model was reduced from 200 to 50 + hours in August and September 2022. For more information, see [Maximum hours of + audio](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audioResources#audioMaximum). The method is asynchronous. It can take several seconds or minutes to complete depending on the duration of the audio and, in the case of an archive file, the total number of audio files being processed. The service returns a 201 response @@ -3360,7 +3993,8 @@ def add_audio(self, resource, and it returns the status of the resource. Use a loop to check the status of the audio every few seconds until it becomes `ok`. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Add audio to the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#addAudio). ### Content types for audio-type resources @@ -3464,27 +4098,32 @@ def add_audio(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') if audio_resource is None: raise ValueError('audio_resource must be provided') headers = { 'Content-Type': content_type, - 'Contained-Content-Type': contained_content_type + 'Contained-Content-Type': contained_content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_audio', + ) headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } data = audio_resource if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3492,17 +4131,23 @@ def add_audio(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_audio(self, customization_id: str, audio_name: str, - **kwargs) -> DetailedResponse: + def get_audio( + self, + customization_id: str, + audio_name: str, + **kwargs, + ) -> DetailedResponse: """ Get an audio resource. @@ -3525,7 +4170,8 @@ def get_audio(self, customization_id: str, audio_name: str, You must use credentials for the instance of the service that owns a model to list its audio resources. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). @@ -3540,18 +4186,21 @@ def get_audio(self, customization_id: str, audio_name: str, :rtype: DetailedResponse with `dict` result representing a `AudioListing` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3559,13 +4208,21 @@ def get_audio(self, customization_id: str, audio_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_audio(self, customization_id: str, audio_name: str, - **kwargs) -> DetailedResponse: + def delete_audio( + self, + customization_id: str, + audio_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete an audio resource. @@ -3579,7 +4236,8 @@ def delete_audio(self, customization_id: str, audio_name: str, credentials for the instance of the service that owns a model to delete its audio resources. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Deleting an audio resource from a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#deleteAudio). @@ -3594,18 +4252,21 @@ def delete_audio(self, customization_id: str, audio_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3613,9 +4274,11 @@ def delete_audio(self, customization_id: str, audio_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -3624,7 +4287,11 @@ def delete_audio(self, customization_id: str, audio_name: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3650,24 +4317,100 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) - params = {'customer_id': customer_id} + params = { + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Language identification + ######################### + + def detect_language( + self, + lid_confidence: float, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Spoken language identification. + + Detects the spoken language in audio streams. The endpoint is + `/v1/detect_language` and user can optionally include `lid_confidence` parameter + to set a custom confidence threshold for detection. The model continuously + processes incoming audio and returns the identified language when it reaches a + confidence level higher than the specified threshold (0.99 by default). See + [Spoken language + identification](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speech-language-identification). + + :param float lid_confidence: Set a custom confidence threshold for + detection. + :param BinaryIO audio: The audio to transcribe. + :param str content_type: (optional) The type of the input. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `LanguageDetectionResults` object + """ + + if lid_confidence is None: + raise ValueError('lid_confidence must be provided') + if audio is None: + raise ValueError('audio must be provided') + headers = { + 'Content-Type': content_type, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='detect_language', + ) + headers.update(sdk_headers) + + params = { + 'lid_confidence': lid_confidence, + } + + data = audio + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v1/detect_language' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -3681,50 +4424,63 @@ class GetModelEnums: class ModelId(str, Enum): """ The identifier of the model in the form of its name from the output of the [List - models](#listmodels) method. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.). + models](#listmodels) method. """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' + DE_DE = 'de-DE' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' + EN_AU = 'en-AU' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_GB = 'en-GB' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_IN = 'en-IN' EN_IN_TELEPHONY = 'en-IN_Telephony' + EN_US = 'en-US' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA = 'fr-CA' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' + FR_FR = 'fr-FR' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' @@ -3732,21 +4488,28 @@ class ModelId(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' + JA_JP = 'ja-JP' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3762,6 +4525,7 @@ class ContentType(str, Enum): The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -3781,52 +4545,72 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. - (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Using a model for speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + The model to use for speech recognition. If you omit the `model` parameter, the + service uses the US English `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, + you must either specify a model with the request or specify a new default model + for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' + DE_DE = 'de-DE' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' + EN_AU = 'en-AU' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_IN = 'en-IN' EN_IN_TELEPHONY = 'en-IN_Telephony' + EN_GB = 'en-GB' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_US = 'en-US' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA = 'fr-CA' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' + FR_FR = 'fr-FR' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' @@ -3834,21 +4618,28 @@ class Model(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' + JA_JP = 'ja-JP' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3864,6 +4655,7 @@ class ContentType(str, Enum): The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -3883,52 +4675,72 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. - (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Using a model for speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + The model to use for speech recognition. If you omit the `model` parameter, the + service uses the US English `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, + you must either specify a model with the request or specify a new default model + for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' + DE_DE = 'de-DE' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' + EN_AU = 'en-AU' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_IN = 'en-IN' EN_IN_TELEPHONY = 'en-IN_Telephony' + EN_GB = 'en-GB' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_US = 'en-US' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA = 'fr-CA' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' + FR_FR = 'fr-FR' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' @@ -3936,21 +4748,28 @@ class Model(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' + JA_JP = 'ja-JP' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3975,6 +4794,7 @@ class Events(str, Enum): `recognitions.failed`. If the job does not include a callback URL, omit the parameter. """ + RECOGNITIONS_STARTED = 'recognitions.started' RECOGNITIONS_COMPLETED = 'recognitions.completed' RECOGNITIONS_COMPLETED_WITH_RESULTS = 'recognitions.completed_with_results' @@ -3992,13 +4812,12 @@ class Language(str, Enum): are to be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or - custom acoustic models that are owned by the requesting credentials. (**Note:** - The identifier `ar-AR` is deprecated; use `ar-MS` instead.) + custom acoustic models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ - AR_AR = 'ar-AR' + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4023,6 +4842,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' @@ -4041,10 +4861,12 @@ class WordTypeToAdd(str, Enum): * `user` trains the model only on custom words that were added or modified by the user directly. The model is not trained on new words extracted from corpora or grammars. - _For custom models that are based on next-generation models_, the service ignores - the parameter. The words resource contains only custom words that the user adds or - modifies directly, so the parameter is unnecessary. + _For custom models that are based on large speech models and next-generation + models_, the service ignores the `word_type_to_add` parameter. The words resource + contains only custom words that the user adds or modifies directly, so the + parameter is unnecessary. """ + ALL = 'all' USER = 'user' @@ -4065,6 +4887,7 @@ class WordType(str, Enum): `user` apply. Both options return the same results. Words from other sources are not added to custom models that are based on next-generation models. """ + ALL = 'all' USER = 'user' CORPORA = 'corpora' @@ -4080,6 +4903,7 @@ class Sort(str, Enum): letters. For count ordering, values with the same count are ordered alphabetically. With the `curl` command, URL-encode the `+` symbol as `%2B`. """ + ALPHABETICAL = 'alphabetical' COUNT = 'count' @@ -4097,6 +4921,7 @@ class ContentType(str, Enum): * `application/srgs+xml` for XML Form, which uses XML elements to represent the grammar. """ + APPLICATION_SRGS = 'application/srgs' APPLICATION_SRGS_XML = 'application/srgs+xml' @@ -4112,13 +4937,12 @@ class Language(str, Enum): are to be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or - custom acoustic models that are owned by the requesting credentials. (**Note:** - The identifier `ar-AR` is deprecated; use `ar-MS` instead.) + custom acoustic models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ - AR_AR = 'ar-AR' + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4143,6 +4967,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' @@ -4160,6 +4985,7 @@ class ContentType(str, Enum): information, see **Content types for archive-type resources** in the method description. """ + APPLICATION_ZIP = 'application/zip' APPLICATION_GZIP = 'application/gzip' AUDIO_ALAW = 'audio/alaw' @@ -4193,6 +5019,35 @@ class ContainedContentType(str, Enum): resources** in the method description. _For an audio-type resource_, omit the header. """ + + AUDIO_ALAW = 'audio/alaw' + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_G729 = 'audio/g729' + AUDIO_L16 = 'audio/l16' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + +class DetectLanguageEnums: + """ + Enums for detect_language parameters. + """ + + class ContentType(str, Enum): + """ + The type of the input. + """ + + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' @@ -4215,35 +5070,35 @@ class ContainedContentType(str, Enum): ############################################################################## -class AcousticModel(): +class AcousticModel: """ Information about an existing custom acoustic model. - :attr str customization_id: The customization ID (GUID) of the custom acoustic + :param str customization_id: The customization ID (GUID) of the custom acoustic model. The [Create a custom acoustic model](#createacousticmodel) method returns only this field of the object; it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was last modified. The `created` and `updated` fields are equal when an acoustic model is first added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom acoustic + :param str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). - :attr List[str] versions: (optional) A list of the available versions of the + :param List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded to a new version of its base model. Otherwise, only a single version is shown. - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. - :attr str name: (optional) The name of the custom acoustic model. - :attr str description: (optional) The description of the custom acoustic model. - :attr str base_model_name: (optional) The name of the language model for which + :param str name: (optional) The name of the custom acoustic model. + :param str description: (optional) The description of the custom acoustic model. + :param str base_model_name: (optional) The name of the language model for which the custom acoustic model was created. - :attr str status: (optional) The current status of the custom acoustic model: + :param str status: (optional) The current status of the custom acoustic model: * `pending`: The model was created but is waiting either for valid training data to be added or for the service to finish analyzing added data. * `ready`: The model contains valid data and is ready to be trained. If the @@ -4253,31 +5108,33 @@ class AcousticModel(): * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the + :param int progress: (optional) A percentage that indicates the progress of the custom acoustic model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. - :attr str warnings: (optional) If the request included unknown parameters, the + :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ - def __init__(self, - customization_id: str, - *, - created: str = None, - updated: str = None, - language: str = None, - versions: List[str] = None, - owner: str = None, - name: str = None, - description: str = None, - base_model_name: str = None, - status: str = None, - progress: int = None, - warnings: str = None) -> None: + def __init__( + self, + customization_id: str, + *, + created: Optional[str] = None, + updated: Optional[str] = None, + language: Optional[str] = None, + versions: Optional[List[str]] = None, + owner: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + base_model_name: Optional[str] = None, + status: Optional[str] = None, + progress: Optional[int] = None, + warnings: Optional[str] = None, + ) -> None: """ Initialize a AcousticModel object. @@ -4345,34 +5202,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AcousticModel': """Initialize a AcousticModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in AcousticModel JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'versions' in _dict: - args['versions'] = _dict.get('versions') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'base_model_name' in _dict: - args['base_model_name'] = _dict.get('base_model_name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'progress' in _dict: - args['progress'] = _dict.get('progress') - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (created := _dict.get('created')) is not None: + args['created'] = created + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (language := _dict.get('language')) is not None: + args['language'] = language + if (versions := _dict.get('versions')) is not None: + args['versions'] = versions + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (base_model_name := _dict.get('base_model_name')) is not None: + args['base_model_name'] = base_model_name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (progress := _dict.get('progress')) is not None: + args['progress'] = progress + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -4442,6 +5299,7 @@ class StatusEnum(str, Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ + PENDING = 'pending' READY = 'ready' TRAINING = 'training' @@ -4450,18 +5308,21 @@ class StatusEnum(str, Enum): FAILED = 'failed' -class AcousticModels(): +class AcousticModels: """ Information about existing custom acoustic models. - :attr List[AcousticModel] customizations: An array of `AcousticModel` objects + :param List[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic models for the specified language. """ - def __init__(self, customizations: List['AcousticModel']) -> None: + def __init__( + self, + customizations: List['AcousticModel'], + ) -> None: """ Initialize a AcousticModels object. @@ -4477,9 +5338,9 @@ def __init__(self, customizations: List['AcousticModel']) -> None: def from_dict(cls, _dict: Dict) -> 'AcousticModels': """Initialize a AcousticModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - AcousticModel.from_dict(x) for x in _dict.get('customizations') + AcousticModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -4496,7 +5357,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -4518,35 +5385,37 @@ def __ne__(self, other: 'AcousticModels') -> bool: return not self == other -class AudioDetails(): +class AudioDetails: """ Information about an audio resource from a custom acoustic model. - :attr str type: (optional) The type of the audio resource: + :param str type: (optional) The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). - :attr str codec: (optional) _For an audio-type resource_, the codec in which the - audio is encoded. Omitted for an archive-type resource. - :attr int frequency: (optional) _For an audio-type resource_, the sampling rate + :param str codec: (optional) _For an audio-type resource_, the codec in which + the audio is encoded. Omitted for an archive-type resource. + :param int frequency: (optional) _For an audio-type resource_, the sampling rate of the audio in Hertz (samples per second). Omitted for an archive-type resource. - :attr str compression: (optional) _For an archive-type resource_, the format of + :param str compression: (optional) _For an archive-type resource_, the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ - def __init__(self, - *, - type: str = None, - codec: str = None, - frequency: int = None, - compression: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + codec: Optional[str] = None, + frequency: Optional[int] = None, + compression: Optional[str] = None, + ) -> None: """ Initialize a AudioDetails object. @@ -4577,14 +5446,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioDetails': """Initialize a AudioDetails object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'codec' in _dict: - args['codec'] = _dict.get('codec') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') - if 'compression' in _dict: - args['compression'] = _dict.get('compression') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (codec := _dict.get('codec')) is not None: + args['codec'] = codec + if (frequency := _dict.get('frequency')) is not None: + args['frequency'] = frequency + if (compression := _dict.get('compression')) is not None: + args['compression'] = compression return cls(**args) @classmethod @@ -4633,6 +5502,7 @@ class TypeEnum(str, Enum): the user mistakenly passes a file that does not contain audio, such as a JPEG file). """ + AUDIO = 'audio' ARCHIVE = 'archive' UNDETERMINED = 'undetermined' @@ -4644,23 +5514,24 @@ class CompressionEnum(str, Enum): * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ + ZIP = 'zip' GZIP = 'gzip' -class AudioListing(): +class AudioListing: """ Information about an audio resource from a custom acoustic model. - :attr int duration: (optional) _For an audio-type resource_, the total seconds + :param int duration: (optional) _For an audio-type resource_, the total seconds of audio in the resource. Omitted for an archive-type resource. - :attr str name: (optional) _For an audio-type resource_, the user-specified name - of the resource. Omitted for an archive-type resource. - :attr AudioDetails details: (optional) _For an audio-type resource_, an + :param str name: (optional) _For an audio-type resource_, the user-specified + name of the resource. Omitted for an archive-type resource. + :param AudioDetails details: (optional) _For an audio-type resource_, an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. - :attr str status: (optional) _For an audio-type resource_, the status of the + :param str status: (optional) _For an audio-type resource_, the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. @@ -4670,23 +5541,25 @@ class AudioListing(): * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. - :attr AudioResource container: (optional) _For an archive-type resource_, an + :param AudioResource container: (optional) _For an archive-type resource_, an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. - :attr List[AudioResource] audio: (optional) _For an archive-type resource_, an + :param List[AudioResource] audio: (optional) _For an archive-type resource_, an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. """ - def __init__(self, - *, - duration: int = None, - name: str = None, - details: 'AudioDetails' = None, - status: str = None, - container: 'AudioResource' = None, - audio: List['AudioResource'] = None) -> None: + def __init__( + self, + *, + duration: Optional[int] = None, + name: Optional[str] = None, + details: Optional['AudioDetails'] = None, + status: Optional[str] = None, + container: Optional['AudioResource'] = None, + audio: Optional[List['AudioResource']] = None, + ) -> None: """ Initialize a AudioListing object. @@ -4728,20 +5601,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioListing': """Initialize a AudioListing object from a json dictionary.""" args = {} - if 'duration' in _dict: - args['duration'] = _dict.get('duration') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'details' in _dict: - args['details'] = AudioDetails.from_dict(_dict.get('details')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'container' in _dict: - args['container'] = AudioResource.from_dict(_dict.get('container')) - if 'audio' in _dict: - args['audio'] = [ - AudioResource.from_dict(x) for x in _dict.get('audio') - ] + if (duration := _dict.get('duration')) is not None: + args['duration'] = duration + if (name := _dict.get('name')) is not None: + args['name'] = name + if (details := _dict.get('details')) is not None: + args['details'] = AudioDetails.from_dict(details) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (container := _dict.get('container')) is not None: + args['container'] = AudioResource.from_dict(container) + if (audio := _dict.get('audio')) is not None: + args['audio'] = [AudioResource.from_dict(v) for v in audio] return cls(**args) @classmethod @@ -4757,13 +5628,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details.to_dict() + if isinstance(self.details, dict): + _dict['details'] = self.details + else: + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'container') and self.container is not None: - _dict['container'] = self.container.to_dict() + if isinstance(self.container, dict): + _dict['container'] = self.container + else: + _dict['container'] = self.container.to_dict() if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x.to_dict() for x in self.audio] + audio_list = [] + for v in self.audio: + if isinstance(v, dict): + audio_list.append(v) + else: + audio_list.append(v.to_dict()) + _dict['audio'] = audio_list return _dict def _to_dict(self): @@ -4796,27 +5679,31 @@ class StatusEnum(str, Enum): because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. """ + OK = 'ok' BEING_PROCESSED = 'being_processed' INVALID = 'invalid' -class AudioMetrics(): +class AudioMetrics: """ If audio metrics are requested, information about the signal characteristics of the input audio. - :attr float sampling_interval: The interval in seconds (typically 0.1 seconds) + :param float sampling_interval: The interval in seconds (typically 0.1 seconds) at which the service calculated the audio metrics. In other words, how often the service calculated the metrics. A single unit in each histogram (see the `AudioMetricsHistogramBin` object) is calculated based on a `sampling_interval` length of audio. - :attr AudioMetricsDetails accumulated: Detailed information about the signal + :param AudioMetricsDetails accumulated: Detailed information about the signal characteristics of the input audio. """ - def __init__(self, sampling_interval: float, - accumulated: 'AudioMetricsDetails') -> None: + def __init__( + self, + sampling_interval: float, + accumulated: 'AudioMetricsDetails', + ) -> None: """ Initialize a AudioMetrics object. @@ -4835,15 +5722,14 @@ def __init__(self, sampling_interval: float, def from_dict(cls, _dict: Dict) -> 'AudioMetrics': """Initialize a AudioMetrics object from a json dictionary.""" args = {} - if 'sampling_interval' in _dict: - args['sampling_interval'] = _dict.get('sampling_interval') + if (sampling_interval := _dict.get('sampling_interval')) is not None: + args['sampling_interval'] = sampling_interval else: raise ValueError( 'Required property \'sampling_interval\' not present in AudioMetrics JSON' ) - if 'accumulated' in _dict: - args['accumulated'] = AudioMetricsDetails.from_dict( - _dict.get('accumulated')) + if (accumulated := _dict.get('accumulated')) is not None: + args['accumulated'] = AudioMetricsDetails.from_dict(accumulated) else: raise ValueError( 'Required property \'accumulated\' not present in AudioMetrics JSON' @@ -4862,7 +5748,10 @@ def to_dict(self) -> Dict: 'sampling_interval') and self.sampling_interval is not None: _dict['sampling_interval'] = self.sampling_interval if hasattr(self, 'accumulated') and self.accumulated is not None: - _dict['accumulated'] = self.accumulated.to_dict() + if isinstance(self.accumulated, dict): + _dict['accumulated'] = self.accumulated + else: + _dict['accumulated'] = self.accumulated.to_dict() return _dict def _to_dict(self): @@ -4884,23 +5773,23 @@ def __ne__(self, other: 'AudioMetrics') -> bool: return not self == other -class AudioMetricsDetails(): +class AudioMetricsDetails: """ Detailed information about the signal characteristics of the input audio. - :attr bool final: If `true`, indicates the end of the audio stream, meaning that - transcription is complete. Currently, the field is always `true`. The service - returns metrics just once per audio stream. The results provide aggregated audio - metrics that pertain to the complete audio stream. - :attr float end_time: The end time in seconds of the block of audio to which the - metrics apply. - :attr float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) + :param bool final: If `true`, indicates the end of the audio stream, meaning + that transcription is complete. Currently, the field is always `true`. The + service returns metrics just once per audio stream. The results provide + aggregated audio metrics that pertain to the complete audio stream. + :param float end_time: The end time in seconds of the block of audio to which + the metrics apply. + :param float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) for the audio signal. The value indicates the ratio of speech to noise in the audio. A valid value lies in the range of 0 to 100 decibels (dB). The service omits the field if it cannot compute the SNR for the audio. - :attr float speech_ratio: The ratio of speech to non-speech segments in the + :param float speech_ratio: The ratio of speech to non-speech segments in the audio signal. The value lies in the range of 0.0 to 1.0. - :attr float high_frequency_loss: The probability that the audio signal is + :param float high_frequency_loss: The probability that the audio signal is missing the upper half of its frequency content. * A value close to 1.0 typically indicates artificially up-sampled audio, which negatively impacts the accuracy of the transcription results. @@ -4908,10 +5797,10 @@ class AudioMetricsDetails(): spectrum. * A value around 0.5 means that detection of the frequency content is unreliable or not available. - :attr List[AudioMetricsHistogramBin] direct_current_offset: An array of + :param List[AudioMetricsHistogramBin] direct_current_offset: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative direct current (DC) component of the audio signal. - :attr List[AudioMetricsHistogramBin] clipping_rate: An array of + :param List[AudioMetricsHistogramBin] clipping_rate: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate for the audio segments. The clipping rate is defined as the fraction of samples in the segment that reach the maximum or minimum value that is offered by the @@ -4919,29 +5808,31 @@ class AudioMetricsDetails(): Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The clipping rate is between 0.0 and 1.0, with higher values indicating possible degradation of speech recognition. - :attr List[AudioMetricsHistogramBin] speech_level: An array of + :param List[AudioMetricsHistogramBin] speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). - :attr List[AudioMetricsHistogramBin] non_speech_level: An array of + :param List[AudioMetricsHistogramBin] non_speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that do not contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). """ - def __init__(self, - final: bool, - end_time: float, - speech_ratio: float, - high_frequency_loss: float, - direct_current_offset: List['AudioMetricsHistogramBin'], - clipping_rate: List['AudioMetricsHistogramBin'], - speech_level: List['AudioMetricsHistogramBin'], - non_speech_level: List['AudioMetricsHistogramBin'], - *, - signal_to_noise_ratio: float = None) -> None: + def __init__( + self, + final: bool, + end_time: float, + speech_ratio: float, + high_frequency_loss: float, + direct_current_offset: List['AudioMetricsHistogramBin'], + clipping_rate: List['AudioMetricsHistogramBin'], + speech_level: List['AudioMetricsHistogramBin'], + non_speech_level: List['AudioMetricsHistogramBin'], + *, + signal_to_noise_ratio: Optional[float] = None, + ) -> None: """ Initialize a AudioMetricsDetails object. @@ -5002,63 +5893,63 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in AudioMetricsDetails JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in AudioMetricsDetails JSON' ) - if 'signal_to_noise_ratio' in _dict: - args['signal_to_noise_ratio'] = _dict.get('signal_to_noise_ratio') - if 'speech_ratio' in _dict: - args['speech_ratio'] = _dict.get('speech_ratio') + if (signal_to_noise_ratio := + _dict.get('signal_to_noise_ratio')) is not None: + args['signal_to_noise_ratio'] = signal_to_noise_ratio + if (speech_ratio := _dict.get('speech_ratio')) is not None: + args['speech_ratio'] = speech_ratio else: raise ValueError( 'Required property \'speech_ratio\' not present in AudioMetricsDetails JSON' ) - if 'high_frequency_loss' in _dict: - args['high_frequency_loss'] = _dict.get('high_frequency_loss') + if (high_frequency_loss := + _dict.get('high_frequency_loss')) is not None: + args['high_frequency_loss'] = high_frequency_loss else: raise ValueError( 'Required property \'high_frequency_loss\' not present in AudioMetricsDetails JSON' ) - if 'direct_current_offset' in _dict: + if (direct_current_offset := + _dict.get('direct_current_offset')) is not None: args['direct_current_offset'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('direct_current_offset') + AudioMetricsHistogramBin.from_dict(v) + for v in direct_current_offset ] else: raise ValueError( 'Required property \'direct_current_offset\' not present in AudioMetricsDetails JSON' ) - if 'clipping_rate' in _dict: + if (clipping_rate := _dict.get('clipping_rate')) is not None: args['clipping_rate'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('clipping_rate') + AudioMetricsHistogramBin.from_dict(v) for v in clipping_rate ] else: raise ValueError( 'Required property \'clipping_rate\' not present in AudioMetricsDetails JSON' ) - if 'speech_level' in _dict: + if (speech_level := _dict.get('speech_level')) is not None: args['speech_level'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('speech_level') + AudioMetricsHistogramBin.from_dict(v) for v in speech_level ] else: raise ValueError( 'Required property \'speech_level\' not present in AudioMetricsDetails JSON' ) - if 'non_speech_level' in _dict: + if (non_speech_level := _dict.get('non_speech_level')) is not None: args['non_speech_level'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('non_speech_level') + AudioMetricsHistogramBin.from_dict(v) for v in non_speech_level ] else: raise ValueError( @@ -5089,18 +5980,38 @@ def to_dict(self) -> Dict: _dict['high_frequency_loss'] = self.high_frequency_loss if hasattr(self, 'direct_current_offset' ) and self.direct_current_offset is not None: - _dict['direct_current_offset'] = [ - x.to_dict() for x in self.direct_current_offset - ] + direct_current_offset_list = [] + for v in self.direct_current_offset: + if isinstance(v, dict): + direct_current_offset_list.append(v) + else: + direct_current_offset_list.append(v.to_dict()) + _dict['direct_current_offset'] = direct_current_offset_list if hasattr(self, 'clipping_rate') and self.clipping_rate is not None: - _dict['clipping_rate'] = [x.to_dict() for x in self.clipping_rate] + clipping_rate_list = [] + for v in self.clipping_rate: + if isinstance(v, dict): + clipping_rate_list.append(v) + else: + clipping_rate_list.append(v.to_dict()) + _dict['clipping_rate'] = clipping_rate_list if hasattr(self, 'speech_level') and self.speech_level is not None: - _dict['speech_level'] = [x.to_dict() for x in self.speech_level] + speech_level_list = [] + for v in self.speech_level: + if isinstance(v, dict): + speech_level_list.append(v) + else: + speech_level_list.append(v.to_dict()) + _dict['speech_level'] = speech_level_list if hasattr(self, 'non_speech_level') and self.non_speech_level is not None: - _dict['non_speech_level'] = [ - x.to_dict() for x in self.non_speech_level - ] + non_speech_level_list = [] + for v in self.non_speech_level: + if isinstance(v, dict): + non_speech_level_list.append(v) + else: + non_speech_level_list.append(v.to_dict()) + _dict['non_speech_level'] = non_speech_level_list return _dict def _to_dict(self): @@ -5122,19 +6033,24 @@ def __ne__(self, other: 'AudioMetricsDetails') -> bool: return not self == other -class AudioMetricsHistogramBin(): +class AudioMetricsHistogramBin: """ A bin with defined boundaries that indicates the number of values in a range of signal characteristics for a histogram. The first and last bins of a histogram are the boundary bins. They cover the intervals between negative infinity and the first boundary, and between the last boundary and positive infinity, respectively. - :attr float begin: The lower boundary of the bin in the histogram. - :attr float end: The upper boundary of the bin in the histogram. - :attr int count: The number of values in the bin of the histogram. + :param float begin: The lower boundary of the bin in the histogram. + :param float end: The upper boundary of the bin in the histogram. + :param int count: The number of values in the bin of the histogram. """ - def __init__(self, begin: float, end: float, count: int) -> None: + def __init__( + self, + begin: float, + end: float, + count: int, + ) -> None: """ Initialize a AudioMetricsHistogramBin object. @@ -5150,20 +6066,20 @@ def __init__(self, begin: float, end: float, count: int) -> None: def from_dict(cls, _dict: Dict) -> 'AudioMetricsHistogramBin': """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') + if (begin := _dict.get('begin')) is not None: + args['begin'] = begin else: raise ValueError( 'Required property \'begin\' not present in AudioMetricsHistogramBin JSON' ) - if 'end' in _dict: - args['end'] = _dict.get('end') + if (end := _dict.get('end')) is not None: + args['end'] = end else: raise ValueError( 'Required property \'end\' not present in AudioMetricsHistogramBin JSON' ) - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count else: raise ValueError( 'Required property \'count\' not present in AudioMetricsHistogramBin JSON' @@ -5205,20 +6121,20 @@ def __ne__(self, other: 'AudioMetricsHistogramBin') -> bool: return not self == other -class AudioResource(): +class AudioResource: """ Information about an audio resource from a custom acoustic model. - :attr int duration: The total seconds of audio in the audio resource. - :attr str name: _For an archive-type resource_, the user-specified name of the + :param int duration: The total seconds of audio in the audio resource. + :param str name: _For an archive-type resource_, the user-specified name of the resource. _For an audio-type resource_, the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. - :attr AudioDetails details: An `AudioDetails` object that provides detailed + :param AudioDetails details: An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the service finishes processing the audio. - :attr str status: The status of the audio resource: + :param str status: The status of the audio resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service @@ -5230,8 +6146,13 @@ class AudioResource(): invalid. """ - def __init__(self, duration: int, name: str, details: 'AudioDetails', - status: str) -> None: + def __init__( + self, + duration: int, + name: str, + details: 'AudioDetails', + status: str, + ) -> None: """ Initialize a AudioResource object. @@ -5264,25 +6185,25 @@ def __init__(self, duration: int, name: str, details: 'AudioDetails', def from_dict(cls, _dict: Dict) -> 'AudioResource': """Initialize a AudioResource object from a json dictionary.""" args = {} - if 'duration' in _dict: - args['duration'] = _dict.get('duration') + if (duration := _dict.get('duration')) is not None: + args['duration'] = duration else: raise ValueError( 'Required property \'duration\' not present in AudioResource JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in AudioResource JSON') - if 'details' in _dict: - args['details'] = AudioDetails.from_dict(_dict.get('details')) + if (details := _dict.get('details')) is not None: + args['details'] = AudioDetails.from_dict(details) else: raise ValueError( 'Required property \'details\' not present in AudioResource JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in AudioResource JSON' @@ -5302,7 +6223,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details.to_dict() + if isinstance(self.details, dict): + _dict['details'] = self.details + else: + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict @@ -5338,26 +6262,30 @@ class StatusEnum(str, Enum): an archive file, the entire archive is invalid if any of its audio files are invalid. """ + OK = 'ok' BEING_PROCESSED = 'being_processed' INVALID = 'invalid' -class AudioResources(): +class AudioResources: """ Information about the audio resources from a custom acoustic model. - :attr float total_minutes_of_audio: The total minutes of accumulated audio + :param float total_minutes_of_audio: The total minutes of accumulated audio summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. - :attr List[AudioResource] audio: An array of `AudioResource` objects that + :param List[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ - def __init__(self, total_minutes_of_audio: float, - audio: List['AudioResource']) -> None: + def __init__( + self, + total_minutes_of_audio: float, + audio: List['AudioResource'], + ) -> None: """ Initialize a AudioResources object. @@ -5376,16 +6304,15 @@ def __init__(self, total_minutes_of_audio: float, def from_dict(cls, _dict: Dict) -> 'AudioResources': """Initialize a AudioResources object from a json dictionary.""" args = {} - if 'total_minutes_of_audio' in _dict: - args['total_minutes_of_audio'] = _dict.get('total_minutes_of_audio') + if (total_minutes_of_audio := + _dict.get('total_minutes_of_audio')) is not None: + args['total_minutes_of_audio'] = total_minutes_of_audio else: raise ValueError( 'Required property \'total_minutes_of_audio\' not present in AudioResources JSON' ) - if 'audio' in _dict: - args['audio'] = [ - AudioResource.from_dict(x) for x in _dict.get('audio') - ] + if (audio := _dict.get('audio')) is not None: + args['audio'] = [AudioResource.from_dict(v) for v in audio] else: raise ValueError( 'Required property \'audio\' not present in AudioResources JSON' @@ -5404,7 +6331,13 @@ def to_dict(self) -> Dict: ) and self.total_minutes_of_audio is not None: _dict['total_minutes_of_audio'] = self.total_minutes_of_audio if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x.to_dict() for x in self.audio] + audio_list = [] + for v in self.audio: + if isinstance(v, dict): + audio_list.append(v) + else: + audio_list.append(v.to_dict()) + _dict['audio'] = audio_list return _dict def _to_dict(self): @@ -5426,16 +6359,19 @@ def __ne__(self, other: 'AudioResources') -> bool: return not self == other -class Corpora(): +class Corpora: """ Information about the corpora from a custom language model. - :attr List[Corpus] corpora: An array of `Corpus` objects that provides + :param List[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ - def __init__(self, corpora: List['Corpus']) -> None: + def __init__( + self, + corpora: List['Corpus'], + ) -> None: """ Initialize a Corpora object. @@ -5449,10 +6385,8 @@ def __init__(self, corpora: List['Corpus']) -> None: def from_dict(cls, _dict: Dict) -> 'Corpora': """Initialize a Corpora object from a json dictionary.""" args = {} - if 'corpora' in _dict: - args['corpora'] = [ - Corpus.from_dict(x) for x in _dict.get('corpora') - ] + if (corpora := _dict.get('corpora')) is not None: + args['corpora'] = [Corpus.from_dict(v) for v in corpora] else: raise ValueError( 'Required property \'corpora\' not present in Corpora JSON') @@ -5467,7 +6401,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'corpora') and self.corpora is not None: - _dict['corpora'] = [x.to_dict() for x in self.corpora] + corpora_list = [] + for v in self.corpora: + if isinstance(v, dict): + corpora_list.append(v) + else: + corpora_list.append(v.to_dict()) + _dict['corpora'] = corpora_list return _dict def _to_dict(self): @@ -5489,37 +6429,39 @@ def __ne__(self, other: 'Corpora') -> bool: return not self == other -class Corpus(): +class Corpus: """ Information about a corpus from a custom language model. - :attr str name: The name of the corpus. - :attr int total_words: The total number of words in the corpus. The value is `0` - while the corpus is being processed. - :attr int out_of_vocabulary_words: _For custom models that are based on - previous-generation models_, the number of OOV words extracted from the corpus. - The value is `0` while the corpus is being processed. + :param str name: The name of the corpus. + :param int total_words: The total number of words in the corpus. The value is + `0` while the corpus is being processed. + :param int out_of_vocabulary_words: _For custom models that are based on large + speech models and previous-generation models_, the number of OOV words extracted + from the corpus. The value is `0` while the corpus is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value is always `0`. - :attr str status: The status of the corpus: + :param str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. * `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. - :attr str error: (optional) If the status of the corpus is `undetermined`, the + :param str error: (optional) If the status of the corpus is `undetermined`, the following message: `Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'`. """ - def __init__(self, - name: str, - total_words: int, - out_of_vocabulary_words: int, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + name: str, + total_words: int, + out_of_vocabulary_words: int, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a Corpus object. @@ -5527,8 +6469,9 @@ def __init__(self, :param int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. :param int out_of_vocabulary_words: _For custom models that are based on - previous-generation models_, the number of OOV words extracted from the - corpus. The value is `0` while the corpus is being processed. + large speech models and previous-generation models_, the number of OOV + words extracted from the corpus. The value is `0` while the corpus is being + processed. _For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value is always `0`. :param str status: The status of the corpus: @@ -5552,30 +6495,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Corpus': """Initialize a Corpus object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Corpus JSON') - if 'total_words' in _dict: - args['total_words'] = _dict.get('total_words') + if (total_words := _dict.get('total_words')) is not None: + args['total_words'] = total_words else: raise ValueError( 'Required property \'total_words\' not present in Corpus JSON') - if 'out_of_vocabulary_words' in _dict: - args['out_of_vocabulary_words'] = _dict.get( - 'out_of_vocabulary_words') + if (out_of_vocabulary_words := + _dict.get('out_of_vocabulary_words')) is not None: + args['out_of_vocabulary_words'] = out_of_vocabulary_words else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Corpus JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Corpus JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -5627,77 +6570,107 @@ class StatusEnum(str, Enum): * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. """ + ANALYZED = 'analyzed' BEING_PROCESSED = 'being_processed' UNDETERMINED = 'undetermined' -class CustomWord(): +class CustomWord: """ Information about a word that is to be added to a custom language model. - :attr str word: (optional) For the [Add custom words](#addwords) method, you + :param str word: (optional) For the [Add custom words](#addwords) method, you must specify the custom word that is to be added to or updated in the custom - model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) - to connect the tokens of compound words. + model. Do not use characters that need to be URL-encoded, for example, spaces, + slashes, backslashes, colons, ampersands, double quotes, plus signs, equals + signs, or question marks. Use a `-` (dash) or `_` (underscore) to connect the + tokens of compound words. A Japanese custom word can include at most 25 + characters, not including leading or trailing spaces. Omit this parameter for the [Add a custom word](#addword) method. - :attr List[str] sounds_like: (optional) _For a custom model that is based on a - previous-generation model_, an array of sounds-like pronunciations for the - custom word. Specify how words that are difficult to pronounce, foreign words, - acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the parameter to - have the service automatically generate a sounds-like pronunciation for the - word. + :param List[str] mapping_only: (optional) Parameter for custom words. You can + use the 'mapping_only' key in custom words as a form of post processing. This + key parameter has a boolean value to determine whether 'sounds_like' (for + non-Japanese models) or word (for Japanese) is not used for the model + fine-tuning, but for the replacement for 'display_as'. This feature helps you + when you use custom words exclusively to map 'sounds_like' (or word) to + 'display_as' value. When you use custom words solely for post-processing + purposes that does not need fine-tuning. + :param List[str] sounds_like: (optional) As array of sounds-like pronunciations + for the custom word. Specify how words that are difficult to pronounce, foreign + words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a word + that is not in the service's base vocabulary, omit the parameter to have the + service automatically generate a sounds-like pronunciation for the word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can - include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this field. - Custom models based on next-generation models do not support the `sounds_like` - field. The service ignores the field. - :attr str display_as: (optional) An alternative spelling for the custom word + include at most 40 characters, not including leading or trailing spaces. A + Japanese pronunciation can include at most 25 characters, not including leading + or trailing spaces. + :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service uses + the spelling of the word as the display-as value if you omit the field. """ - def __init__(self, - *, - word: str = None, - sounds_like: List[str] = None, - display_as: str = None) -> None: + def __init__( + self, + *, + word: Optional[str] = None, + mapping_only: Optional[List[str]] = None, + sounds_like: Optional[List[str]] = None, + display_as: Optional[str] = None, + ) -> None: """ Initialize a CustomWord object. :param str word: (optional) For the [Add custom words](#addwords) method, you must specify the custom word that is to be added to or updated in the - custom model. Do not include spaces in the word. Use a `-` (dash) or `_` - (underscore) to connect the tokens of compound words. + custom model. Do not use characters that need to be URL-encoded, for + example, spaces, slashes, backslashes, colons, ampersands, double quotes, + plus signs, equals signs, or question marks. Use a `-` (dash) or `_` + (underscore) to connect the tokens of compound words. A Japanese custom + word can include at most 25 characters, not including leading or trailing + spaces. Omit this parameter for the [Add a custom word](#addword) method. - :param List[str] sounds_like: (optional) _For a custom model that is based - on a previous-generation model_, an array of sounds-like pronunciations for - the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the - parameter to have the service automatically generate a sounds-like - pronunciation for the word. + :param List[str] mapping_only: (optional) Parameter for custom words. You + can use the 'mapping_only' key in custom words as a form of post + processing. This key parameter has a boolean value to determine whether + 'sounds_like' (for non-Japanese models) or word (for Japanese) is not used + for the model fine-tuning, but for the replacement for 'display_as'. This + feature helps you when you use custom words exclusively to map + 'sounds_like' (or word) to 'display_as' value. When you use custom words + solely for post-processing purposes that does not need fine-tuning. + :param List[str] sounds_like: (optional) As array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a + word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation - can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this - field. Custom models based on next-generation models do not support the - `sounds_like` field. The service ignores the field. + can include at most 40 characters, not including leading or trailing + spaces. A Japanese pronunciation can include at most 25 characters, not + including leading or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service + uses the spelling of the word as the display-as value if you omit the + field. """ self.word = word + self.mapping_only = mapping_only self.sounds_like = sounds_like self.display_as = display_as @@ -5705,12 +6678,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomWord': """Initialize a CustomWord object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') - if 'sounds_like' in _dict: - args['sounds_like'] = _dict.get('sounds_like') - if 'display_as' in _dict: - args['display_as'] = _dict.get('display_as') + if (word := _dict.get('word')) is not None: + args['word'] = word + if (mapping_only := _dict.get('mapping_only')) is not None: + args['mapping_only'] = mapping_only + if (sounds_like := _dict.get('sounds_like')) is not None: + args['sounds_like'] = sounds_like + if (display_as := _dict.get('display_as')) is not None: + args['display_as'] = display_as return cls(**args) @classmethod @@ -5723,6 +6698,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word + if hasattr(self, 'mapping_only') and self.mapping_only is not None: + _dict['mapping_only'] = self.mapping_only if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: @@ -5748,35 +6725,255 @@ def __ne__(self, other: 'CustomWord') -> bool: return not self == other -class Grammar(): +class EnrichedResults: + """ + If enriched results are requested, transcription with inserted punctuation marks such + as periods, commas, question marks, and exclamation points. + + :param EnrichedResultsTranscript transcript: (optional) If enriched results are + requested, transcription with inserted punctuation marks such as periods, + commas, question marks, and exclamation points. + :param str status: (optional) The status of the enriched transcription. + """ + + def __init__( + self, + *, + transcript: Optional['EnrichedResultsTranscript'] = None, + status: Optional[str] = None, + ) -> None: + """ + Initialize a EnrichedResults object. + + :param EnrichedResultsTranscript transcript: (optional) If enriched results + are requested, transcription with inserted punctuation marks such as + periods, commas, question marks, and exclamation points. + :param str status: (optional) The status of the enriched transcription. + """ + self.transcript = transcript + self.status = status + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnrichedResults': + """Initialize a EnrichedResults object from a json dictionary.""" + args = {} + if (transcript := _dict.get('transcript')) is not None: + args['transcript'] = EnrichedResultsTranscript.from_dict(transcript) + if (status := _dict.get('status')) is not None: + args['status'] = status + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichedResults object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'transcript') and self.transcript is not None: + if isinstance(self.transcript, dict): + _dict['transcript'] = self.transcript + else: + _dict['transcript'] = self.transcript.to_dict() + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnrichedResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnrichedResults') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnrichedResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnrichedResultsTranscript: + """ + If enriched results are requested, transcription with inserted punctuation marks such + as periods, commas, question marks, and exclamation points. + + :param str text: (optional) The transcript text. + :param EnrichedResultsTranscriptTimestamp timestamp: (optional) The speaking + time from the beginning of the transcript to the end. + """ + + def __init__( + self, + *, + text: Optional[str] = None, + timestamp: Optional['EnrichedResultsTranscriptTimestamp'] = None, + ) -> None: + """ + Initialize a EnrichedResultsTranscript object. + + :param str text: (optional) The transcript text. + :param EnrichedResultsTranscriptTimestamp timestamp: (optional) The + speaking time from the beginning of the transcript to the end. + """ + self.text = text + self.timestamp = timestamp + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnrichedResultsTranscript': + """Initialize a EnrichedResultsTranscript object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + if (timestamp := _dict.get('timestamp')) is not None: + args['timestamp'] = EnrichedResultsTranscriptTimestamp.from_dict( + timestamp) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichedResultsTranscript object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'timestamp') and self.timestamp is not None: + if isinstance(self.timestamp, dict): + _dict['timestamp'] = self.timestamp + else: + _dict['timestamp'] = self.timestamp.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnrichedResultsTranscript object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnrichedResultsTranscript') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnrichedResultsTranscript') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnrichedResultsTranscriptTimestamp: + """ + The speaking time from the beginning of the transcript to the end. + + :param float from_: (optional) The start time of a word from the transcript. The + value matches the start time of a word from the `timestamps` array. + :param float to: (optional) The end time of a word from the transcript. The + value matches the end time of a word from the `timestamps` array. + """ + + def __init__( + self, + *, + from_: Optional[float] = None, + to: Optional[float] = None, + ) -> None: + """ + Initialize a EnrichedResultsTranscriptTimestamp object. + + :param float from_: (optional) The start time of a word from the + transcript. The value matches the start time of a word from the + `timestamps` array. + :param float to: (optional) The end time of a word from the transcript. The + value matches the end time of a word from the `timestamps` array. + """ + self.from_ = from_ + self.to = to + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnrichedResultsTranscriptTimestamp': + """Initialize a EnrichedResultsTranscriptTimestamp object from a json dictionary.""" + args = {} + if (from_ := _dict.get('from')) is not None: + args['from_'] = from_ + if (to := _dict.get('to')) is not None: + args['to'] = to + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichedResultsTranscriptTimestamp object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'from_') and self.from_ is not None: + _dict['from'] = self.from_ + if hasattr(self, 'to') and self.to is not None: + _dict['to'] = self.to + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnrichedResultsTranscriptTimestamp object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnrichedResultsTranscriptTimestamp') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnrichedResultsTranscriptTimestamp') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Grammar: """ Information about a grammar from a custom language model. - :attr str name: The name of the grammar. - :attr int out_of_vocabulary_words: _For custom models that are based on + :param str name: The name of the grammar. + :param int out_of_vocabulary_words: _For custom models that are based on previous-generation models_, the number of OOV words extracted from the grammar. The value is `0` while the grammar is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from grammars, so the value is always `0`. - :attr str status: The status of the grammar: + :param str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. * `being_processed`: The service is still analyzing the grammar. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. - :attr str error: (optional) If the status of the grammar is `undetermined`, the + :param str error: (optional) If the status of the grammar is `undetermined`, the following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing the error or adding the grammar again by setting the 'allow_overwrite' flag to 'true'.`. """ - def __init__(self, - name: str, - out_of_vocabulary_words: int, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + name: str, + out_of_vocabulary_words: int, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a Grammar object. @@ -5808,25 +7005,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Grammar': """Initialize a Grammar object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Grammar JSON') - if 'out_of_vocabulary_words' in _dict: - args['out_of_vocabulary_words'] = _dict.get( - 'out_of_vocabulary_words') + if (out_of_vocabulary_words := + _dict.get('out_of_vocabulary_words')) is not None: + args['out_of_vocabulary_words'] = out_of_vocabulary_words else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Grammar JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Grammar JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -5876,21 +7073,25 @@ class StatusEnum(str, Enum): * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. """ + ANALYZED = 'analyzed' BEING_PROCESSED = 'being_processed' UNDETERMINED = 'undetermined' -class Grammars(): +class Grammars: """ Information about the grammars from a custom language model. - :attr List[Grammar] grammars: An array of `Grammar` objects that provides + :param List[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ - def __init__(self, grammars: List['Grammar']) -> None: + def __init__( + self, + grammars: List['Grammar'], + ) -> None: """ Initialize a Grammars object. @@ -5904,10 +7105,8 @@ def __init__(self, grammars: List['Grammar']) -> None: def from_dict(cls, _dict: Dict) -> 'Grammars': """Initialize a Grammars object from a json dictionary.""" args = {} - if 'grammars' in _dict: - args['grammars'] = [ - Grammar.from_dict(x) for x in _dict.get('grammars') - ] + if (grammars := _dict.get('grammars')) is not None: + args['grammars'] = [Grammar.from_dict(v) for v in grammars] else: raise ValueError( 'Required property \'grammars\' not present in Grammars JSON') @@ -5922,7 +7121,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'grammars') and self.grammars is not None: - _dict['grammars'] = [x.to_dict() for x in self.grammars] + grammars_list = [] + for v in self.grammars: + if isinstance(v, dict): + grammars_list.append(v) + else: + grammars_list.append(v.to_dict()) + _dict['grammars'] = grammars_list return _dict def _to_dict(self): @@ -5944,20 +7149,25 @@ def __ne__(self, other: 'Grammars') -> bool: return not self == other -class KeywordResult(): +class KeywordResult: """ Information about a match for a keyword from speech recognition results. - :attr str normalized_text: A specified keyword normalized to the spoken phrase + :param str normalized_text: A specified keyword normalized to the spoken phrase that matched in the audio input. - :attr float start_time: The start time in seconds of the keyword match. - :attr float end_time: The end time in seconds of the keyword match. - :attr float confidence: A confidence score for the keyword match in the range of - 0.0 to 1.0. + :param float start_time: The start time in seconds of the keyword match. + :param float end_time: The end time in seconds of the keyword match. + :param float confidence: A confidence score for the keyword match in the range + of 0.0 to 1.0. """ - def __init__(self, normalized_text: str, start_time: float, end_time: float, - confidence: float) -> None: + def __init__( + self, + normalized_text: str, + start_time: float, + end_time: float, + confidence: float, + ) -> None: """ Initialize a KeywordResult object. @@ -5977,26 +7187,26 @@ def __init__(self, normalized_text: str, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'KeywordResult': """Initialize a KeywordResult object from a json dictionary.""" args = {} - if 'normalized_text' in _dict: - args['normalized_text'] = _dict.get('normalized_text') + if (normalized_text := _dict.get('normalized_text')) is not None: + args['normalized_text'] = normalized_text else: raise ValueError( 'Required property \'normalized_text\' not present in KeywordResult JSON' ) - if 'start_time' in _dict: - args['start_time'] = _dict.get('start_time') + if (start_time := _dict.get('start_time')) is not None: + args['start_time'] = start_time else: raise ValueError( 'Required property \'start_time\' not present in KeywordResult JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in KeywordResult JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in KeywordResult JSON' @@ -6041,26 +7251,257 @@ def __ne__(self, other: 'KeywordResult') -> bool: return not self == other -class LanguageModel(): +class LanguageDetectionResult: + """ + Language detection results. + + :param List[LanguageInfo] language_info: (optional) An array of `LanguageInfo` + objects. + """ + + def __init__( + self, + *, + language_info: Optional[List['LanguageInfo']] = None, + ) -> None: + """ + Initialize a LanguageDetectionResult object. + + :param List[LanguageInfo] language_info: (optional) An array of + `LanguageInfo` objects. + """ + self.language_info = language_info + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LanguageDetectionResult': + """Initialize a LanguageDetectionResult object from a json dictionary.""" + args = {} + if (language_info := _dict.get('language_info')) is not None: + args['language_info'] = [ + LanguageInfo.from_dict(v) for v in language_info + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageDetectionResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'language_info') and self.language_info is not None: + language_info_list = [] + for v in self.language_info: + if isinstance(v, dict): + language_info_list.append(v) + else: + language_info_list.append(v.to_dict()) + _dict['language_info'] = language_info_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LanguageDetectionResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LanguageDetectionResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LanguageDetectionResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LanguageDetectionResults: + """ + Language detection results. + + :param List[LanguageDetectionResult] results: (optional) An array of + `LanguageDetectionResult` objects. + :param int result_index: (optional) An index that indicates a change point in + the `results` array. The service increments the index for additional results + that it sends for new audio for the same request. All results with the same + index are delivered at the same time. The same index can include multiple final + results that are delivered with the same response. + """ + + def __init__( + self, + *, + results: Optional[List['LanguageDetectionResult']] = None, + result_index: Optional[int] = None, + ) -> None: + """ + Initialize a LanguageDetectionResults object. + + :param List[LanguageDetectionResult] results: (optional) An array of + `LanguageDetectionResult` objects. + :param int result_index: (optional) An index that indicates a change point + in the `results` array. The service increments the index for additional + results that it sends for new audio for the same request. All results with + the same index are delivered at the same time. The same index can include + multiple final results that are delivered with the same response. + """ + self.results = results + self.result_index = result_index + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LanguageDetectionResults': + """Initialize a LanguageDetectionResults object from a json dictionary.""" + args = {} + if (results := _dict.get('results')) is not None: + args['results'] = [ + LanguageDetectionResult.from_dict(v) for v in results + ] + if (result_index := _dict.get('result_index')) is not None: + args['result_index'] = result_index + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageDetectionResults object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + if hasattr(self, 'result_index') and self.result_index is not None: + _dict['result_index'] = self.result_index + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LanguageDetectionResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LanguageDetectionResults') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LanguageDetectionResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LanguageInfo: + """ + Language detection info such as confidence and language detected. + + :param float confidence: (optional) A score that indicates the service's + confidence in its identification of the language in the range of 0.0 to 1.0. + :param str language: (optional) The language detected in standard abbreviated + ISO 639 format. + :param float timestamp: (optional) The timestamp of the detected language. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + language: Optional[str] = None, + timestamp: Optional[float] = None, + ) -> None: + """ + Initialize a LanguageInfo object. + + :param float confidence: (optional) A score that indicates the service's + confidence in its identification of the language in the range of 0.0 to + 1.0. + :param str language: (optional) The language detected in standard + abbreviated ISO 639 format. + :param float timestamp: (optional) The timestamp of the detected language. + """ + self.confidence = confidence + self.language = language + self.timestamp = timestamp + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LanguageInfo': + """Initialize a LanguageInfo object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (language := _dict.get('language')) is not None: + args['language'] = language + if (timestamp := _dict.get('timestamp')) is not None: + args['timestamp'] = timestamp + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageInfo object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'timestamp') and self.timestamp is not None: + _dict['timestamp'] = self.timestamp + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LanguageInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LanguageInfo') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LanguageInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LanguageModel: """ Information about an existing custom language model. - :attr str customization_id: The customization ID (GUID) of the custom language + :param str customization_id: The customization ID (GUID) of the custom language model. The [Create a custom language model](#createlanguagemodel) method returns only this field of the object; it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was last modified. The `created` and `updated` fields are equal when a language model is first added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom language + :param str language: (optional) The language identifier of the custom language model (for example, `en-US`). The value matches the five-character language identifier from the name of the base model for the custom model. This value might be different from the value of the `dialect` field. - :attr str dialect: (optional) The dialect of the language for the custom + :param str dialect: (optional) The dialect of the language for the custom language model. _For custom models that are based on non-Spanish previous-generation models and on next-generation models,_ the field matches the language of the base model; for example, `en-US` for one of the US English @@ -6073,18 +7514,18 @@ class LanguageModel(): models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :attr List[str] versions: (optional) A list of the available versions of the + :param List[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded to a new version of its base model. Otherwise, only a single version is shown. - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. - :attr str name: (optional) The name of the custom language model. - :attr str description: (optional) The description of the custom language model. - :attr str base_model_name: (optional) The name of the language model for which + :param str name: (optional) The name of the custom language model. + :param str description: (optional) The description of the custom language model. + :param str base_model_name: (optional) The name of the language model for which the custom language model was created. - :attr str status: (optional) The current status of the custom language model: + :param str status: (optional) The current status of the custom language model: * `pending`: The model was created but is waiting either for valid training data to be added or for the service to finish analyzing added data. * `ready`: The model contains valid data and is ready to be trained. If the @@ -6094,37 +7535,39 @@ class LanguageModel(): * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the + :param int progress: (optional) A percentage that indicates the progress of the custom language model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. - :attr str error: (optional) If an error occurred while adding a grammar file to + :param str error: (optional) If an error occurred while adding a grammar file to the custom language model, a message that describes an `Internal Server Error` and includes the string `Cannot compile grammar`. The status of the custom model is not affected by the error, but the grammar cannot be used with the model. - :attr str warnings: (optional) If the request included unknown parameters, the + :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ - def __init__(self, - customization_id: str, - *, - created: str = None, - updated: str = None, - language: str = None, - dialect: str = None, - versions: List[str] = None, - owner: str = None, - name: str = None, - description: str = None, - base_model_name: str = None, - status: str = None, - progress: int = None, - error: str = None, - warnings: str = None) -> None: + def __init__( + self, + customization_id: str, + *, + created: Optional[str] = None, + updated: Optional[str] = None, + language: Optional[str] = None, + dialect: Optional[str] = None, + versions: Optional[List[str]] = None, + owner: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + base_model_name: Optional[str] = None, + status: Optional[str] = None, + progress: Optional[int] = None, + error: Optional[str] = None, + warnings: Optional[str] = None, + ) -> None: """ Initialize a LanguageModel object. @@ -6214,38 +7657,38 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LanguageModel': """Initialize a LanguageModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in LanguageModel JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'dialect' in _dict: - args['dialect'] = _dict.get('dialect') - if 'versions' in _dict: - args['versions'] = _dict.get('versions') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'base_model_name' in _dict: - args['base_model_name'] = _dict.get('base_model_name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'progress' in _dict: - args['progress'] = _dict.get('progress') - if 'error' in _dict: - args['error'] = _dict.get('error') - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (created := _dict.get('created')) is not None: + args['created'] = created + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (language := _dict.get('language')) is not None: + args['language'] = language + if (dialect := _dict.get('dialect')) is not None: + args['dialect'] = dialect + if (versions := _dict.get('versions')) is not None: + args['versions'] = versions + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (base_model_name := _dict.get('base_model_name')) is not None: + args['base_model_name'] = base_model_name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (progress := _dict.get('progress')) is not None: + args['progress'] = progress + if (error := _dict.get('error')) is not None: + args['error'] = error + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -6319,6 +7762,7 @@ class StatusEnum(str, Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ + PENDING = 'pending' READY = 'ready' TRAINING = 'training' @@ -6327,18 +7771,21 @@ class StatusEnum(str, Enum): FAILED = 'failed' -class LanguageModels(): +class LanguageModels: """ Information about existing custom language models. - :attr List[LanguageModel] customizations: An array of `LanguageModel` objects + :param List[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language models for the specified language. """ - def __init__(self, customizations: List['LanguageModel']) -> None: + def __init__( + self, + customizations: List['LanguageModel'], + ) -> None: """ Initialize a LanguageModels object. @@ -6354,9 +7801,9 @@ def __init__(self, customizations: List['LanguageModel']) -> None: def from_dict(cls, _dict: Dict) -> 'LanguageModels': """Initialize a LanguageModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - LanguageModel.from_dict(x) for x in _dict.get('customizations') + LanguageModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -6373,7 +7820,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -6395,38 +7848,40 @@ def __ne__(self, other: 'LanguageModels') -> bool: return not self == other -class ProcessedAudio(): +class ProcessedAudio: """ Detailed timing information about the service's processing of the input audio. - :attr float received: The seconds of audio that the service has received as of + :param float received: The seconds of audio that the service has received as of this response. The value of the field is greater than the values of the `transcription` and `speaker_labels` fields during speech recognition processing, since the service first has to receive the audio before it can begin to process it. The final value can also be greater than the value of the `transcription` and `speaker_labels` fields by a fractional number of seconds. - :attr float seen_by_engine: The seconds of audio that the service has passed to + :param float seen_by_engine: The seconds of audio that the service has passed to its speech-processing engine as of this response. The value of the field is greater than the values of the `transcription` and `speaker_labels` fields during speech recognition processing. The `received` and `seen_by_engine` fields have identical values when the service has finished processing all audio. This final value can be greater than the value of the `transcription` and `speaker_labels` fields by a fractional number of seconds. - :attr float transcription: The seconds of audio that the service has processed + :param float transcription: The seconds of audio that the service has processed for speech recognition as of this response. - :attr float speaker_labels: (optional) If speaker labels are requested, the + :param float speaker_labels: (optional) If speaker labels are requested, the seconds of audio that the service has processed to determine speaker labels as of this response. This value often trails the value of the `transcription` field during speech recognition processing. The `transcription` and `speaker_labels` fields have identical values when the service has finished processing all audio. """ - def __init__(self, - received: float, - seen_by_engine: float, - transcription: float, - *, - speaker_labels: float = None) -> None: + def __init__( + self, + received: float, + seen_by_engine: float, + transcription: float, + *, + speaker_labels: Optional[float] = None, + ) -> None: """ Initialize a ProcessedAudio object. @@ -6463,26 +7918,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProcessedAudio': """Initialize a ProcessedAudio object from a json dictionary.""" args = {} - if 'received' in _dict: - args['received'] = _dict.get('received') + if (received := _dict.get('received')) is not None: + args['received'] = received else: raise ValueError( 'Required property \'received\' not present in ProcessedAudio JSON' ) - if 'seen_by_engine' in _dict: - args['seen_by_engine'] = _dict.get('seen_by_engine') + if (seen_by_engine := _dict.get('seen_by_engine')) is not None: + args['seen_by_engine'] = seen_by_engine else: raise ValueError( 'Required property \'seen_by_engine\' not present in ProcessedAudio JSON' ) - if 'transcription' in _dict: - args['transcription'] = _dict.get('transcription') + if (transcription := _dict.get('transcription')) is not None: + args['transcription'] = transcription else: raise ValueError( 'Required property \'transcription\' not present in ProcessedAudio JSON' ) - if 'speaker_labels' in _dict: - args['speaker_labels'] = _dict.get('speaker_labels') + if (speaker_labels := _dict.get('speaker_labels')) is not None: + args['speaker_labels'] = speaker_labels return cls(**args) @classmethod @@ -6522,15 +7977,15 @@ def __ne__(self, other: 'ProcessedAudio') -> bool: return not self == other -class ProcessingMetrics(): +class ProcessingMetrics: """ If processing metrics are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous [Recognize audio](#recognize) method. - :attr ProcessedAudio processed_audio: Detailed timing information about the + :param ProcessedAudio processed_audio: Detailed timing information about the service's processing of the input audio. - :attr float wall_clock_since_first_byte_received: The amount of real time in + :param float wall_clock_since_first_byte_received: The amount of real time in seconds that has passed since the service received the first byte of input audio. Values in this field are generally multiples of the specified metrics interval, with two differences: @@ -6540,7 +7995,7 @@ class ProcessingMetrics(): * The service also returns values for transcription events if you set the `interim_results` parameter to `true`. The service returns both processing metrics and transcription results when such events occur. - :attr bool periodic: An indication of whether the metrics apply to a periodic + :param bool periodic: An indication of whether the metrics apply to a periodic interval or a transcription event: * `true` means that the response was triggered by a specified processing interval. The information contains processing metrics only. @@ -6550,9 +8005,12 @@ class ProcessingMetrics(): different results if necessary. """ - def __init__(self, processed_audio: 'ProcessedAudio', - wall_clock_since_first_byte_received: float, - periodic: bool) -> None: + def __init__( + self, + processed_audio: 'ProcessedAudio', + wall_clock_since_first_byte_received: float, + periodic: bool, + ) -> None: """ Initialize a ProcessingMetrics object. @@ -6585,22 +8043,22 @@ def __init__(self, processed_audio: 'ProcessedAudio', def from_dict(cls, _dict: Dict) -> 'ProcessingMetrics': """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} - if 'processed_audio' in _dict: - args['processed_audio'] = ProcessedAudio.from_dict( - _dict.get('processed_audio')) + if (processed_audio := _dict.get('processed_audio')) is not None: + args['processed_audio'] = ProcessedAudio.from_dict(processed_audio) else: raise ValueError( 'Required property \'processed_audio\' not present in ProcessingMetrics JSON' ) - if 'wall_clock_since_first_byte_received' in _dict: - args['wall_clock_since_first_byte_received'] = _dict.get( - 'wall_clock_since_first_byte_received') + if (wall_clock_since_first_byte_received := + _dict.get('wall_clock_since_first_byte_received')) is not None: + args[ + 'wall_clock_since_first_byte_received'] = wall_clock_since_first_byte_received else: raise ValueError( 'Required property \'wall_clock_since_first_byte_received\' not present in ProcessingMetrics JSON' ) - if 'periodic' in _dict: - args['periodic'] = _dict.get('periodic') + if (periodic := _dict.get('periodic')) is not None: + args['periodic'] = periodic else: raise ValueError( 'Required property \'periodic\' not present in ProcessingMetrics JSON' @@ -6617,7 +8075,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'processed_audio') and self.processed_audio is not None: - _dict['processed_audio'] = self.processed_audio.to_dict() + if isinstance(self.processed_audio, dict): + _dict['processed_audio'] = self.processed_audio + else: + _dict['processed_audio'] = self.processed_audio.to_dict() if hasattr(self, 'wall_clock_since_first_byte_received' ) and self.wall_clock_since_first_byte_received is not None: _dict[ @@ -6645,12 +8106,12 @@ def __ne__(self, other: 'ProcessingMetrics') -> bool: return not self == other -class RecognitionJob(): +class RecognitionJob: """ Information about a current asynchronous speech recognition job. - :attr str id: The ID of the asynchronous job. - :attr str status: The current status of the job: + :param str id: The ID of the asynchronous job. + :param str status: The current status of the job: * `waiting`: The service is preparing the job for processing. The service returns this status when the job is initially created or when it is waiting for capacity to process the job. The job remains in this state until the service has @@ -6661,41 +8122,45 @@ class RecognitionJob(): sent the results with the callback notification. Otherwise, you must retrieve the results by checking the individual job. * `failed`: The job failed. - :attr str created: The date and time in Coordinated Universal Time (UTC) at + :param str created: The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by the [Check jobs](#checkjobs) and [Check a job[(#checkjob) methods. - :attr str url: (optional) The URL to use to request information about the job + :param str url: (optional) The URL to use to request information about the job with the [Check a job](#checkjob) method. This field is returned only by the [Create a job](#createjob) method. - :attr str user_token: (optional) The user token associated with a job that was + :param str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the [Check jobs](#checkjobs) method. - :attr List[SpeechRecognitionResults] results: (optional) If the status is + :param List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the [Check a job](#checkjob) method. - :attr List[str] warnings: (optional) An array of warning messages about invalid + :param List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field can be returned only by the - [Create a job](#createjob) method. + [Create a job](#createjob) method. (If you use the `character_insertion_bias` + parameter with a previous-generation model, the warning message refers to the + parameter as `lambdaBias`.). """ - def __init__(self, - id: str, - status: str, - created: str, - *, - updated: str = None, - url: str = None, - user_token: str = None, - results: List['SpeechRecognitionResults'] = None, - warnings: List[str] = None) -> None: + def __init__( + self, + id: str, + status: str, + created: str, + *, + updated: Optional[str] = None, + url: Optional[str] = None, + user_token: Optional[str] = None, + results: Optional[List['SpeechRecognitionResults']] = None, + warnings: Optional[List[str]] = None, + ) -> None: """ Initialize a RecognitionJob object. @@ -6735,7 +8200,9 @@ def __init__(self, descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field - can be returned only by the [Create a job](#createjob) method. + can be returned only by the [Create a job](#createjob) method. (If you use + the `character_insertion_bias` parameter with a previous-generation model, + the warning message refers to the parameter as `lambdaBias`.). """ self.id = id self.status = status @@ -6750,36 +8217,35 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RecognitionJob': """Initialize a RecognitionJob object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id else: raise ValueError( 'Required property \'id\' not present in RecognitionJob JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in RecognitionJob JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') + if (created := _dict.get('created')) is not None: + args['created'] = created else: raise ValueError( 'Required property \'created\' not present in RecognitionJob JSON' ) - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'user_token' in _dict: - args['user_token'] = _dict.get('user_token') - if 'results' in _dict: + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (url := _dict.get('url')) is not None: + args['url'] = url + if (user_token := _dict.get('user_token')) is not None: + args['user_token'] = user_token + if (results := _dict.get('results')) is not None: args['results'] = [ - SpeechRecognitionResults.from_dict(x) - for x in _dict.get('results') + SpeechRecognitionResults.from_dict(v) for v in results ] - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -6803,7 +8269,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_token') and self.user_token is not None: _dict['user_token'] = self.user_token if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -6840,22 +8312,26 @@ class StatusEnum(str, Enum): results by checking the individual job. * `failed`: The job failed. """ + WAITING = 'waiting' PROCESSING = 'processing' COMPLETED = 'completed' FAILED = 'failed' -class RecognitionJobs(): +class RecognitionJobs: """ Information about current asynchronous speech recognition jobs. - :attr List[RecognitionJob] recognitions: An array of `RecognitionJob` objects + :param List[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ - def __init__(self, recognitions: List['RecognitionJob']) -> None: + def __init__( + self, + recognitions: List['RecognitionJob'], + ) -> None: """ Initialize a RecognitionJobs object. @@ -6869,9 +8345,9 @@ def __init__(self, recognitions: List['RecognitionJob']) -> None: def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': """Initialize a RecognitionJobs object from a json dictionary.""" args = {} - if 'recognitions' in _dict: + if (recognitions := _dict.get('recognitions')) is not None: args['recognitions'] = [ - RecognitionJob.from_dict(x) for x in _dict.get('recognitions') + RecognitionJob.from_dict(v) for v in recognitions ] else: raise ValueError( @@ -6888,7 +8364,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'recognitions') and self.recognitions is not None: - _dict['recognitions'] = [x.to_dict() for x in self.recognitions] + recognitions_list = [] + for v in self.recognitions: + if isinstance(v, dict): + recognitions_list.append(v) + else: + recognitions_list.append(v.to_dict()) + _dict['recognitions'] = recognitions_list return _dict def _to_dict(self): @@ -6910,19 +8392,23 @@ def __ne__(self, other: 'RecognitionJobs') -> bool: return not self == other -class RegisterStatus(): +class RegisterStatus: """ Information about a request to register a callback for asynchronous speech recognition. - :attr str status: The current status of the job: + :param str status: The current status of the job: * `created`: The service successfully allowlisted the callback URL as a result of the call. * `already created`: The URL was already allowlisted. - :attr str url: The callback URL that is successfully registered. + :param str url: The callback URL that is successfully registered. """ - def __init__(self, status: str, url: str) -> None: + def __init__( + self, + status: str, + url: str, + ) -> None: """ Initialize a RegisterStatus object. @@ -6939,14 +8425,14 @@ def __init__(self, status: str, url: str) -> None: def from_dict(cls, _dict: Dict) -> 'RegisterStatus': """Initialize a RegisterStatus object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in RegisterStatus JSON' ) - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in RegisterStatus JSON') @@ -6991,33 +8477,41 @@ class StatusEnum(str, Enum): the call. * `already created`: The URL was already allowlisted. """ + CREATED = 'created' ALREADY_CREATED = 'already created' -class SpeakerLabelsResult(): +class SpeakerLabelsResult: """ Information about the speakers from speech recognition results. - :attr float from_: The start time of a word from the transcript. The value + :param float from_: The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array. - :attr float to: The end time of a word from the transcript. The value matches + :param float to: The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array. - :attr int speaker: The numeric identifier that the service assigns to a speaker + :param int speaker: The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered. - :attr float confidence: A score that indicates the service's confidence in its + :param float confidence: A score that indicates the service's confidence in its identification of the speaker in the range of 0.0 to 1.0. - :attr bool final: An indication of whether the service might further change word - and speaker-label results. A value of `true` means that the service guarantees - not to send any further updates for the current or any preceding results; - `false` means that the service might send further updates to the results. + :param bool final: An indication of whether the service might further change + word and speaker-label results. A value of `true` means that the service + guarantees not to send any further updates for the current or any preceding + results; `false` means that the service might send further updates to the + results. """ - def __init__(self, from_: float, to: float, speaker: int, confidence: float, - final: bool) -> None: + def __init__( + self, + from_: float, + to: float, + speaker: int, + confidence: float, + final: bool, + ) -> None: """ Initialize a SpeakerLabelsResult object. @@ -7048,32 +8542,32 @@ def __init__(self, from_: float, to: float, speaker: int, confidence: float, def from_dict(cls, _dict: Dict) -> 'SpeakerLabelsResult': """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} - if 'from' in _dict: - args['from_'] = _dict.get('from') + if (from_ := _dict.get('from')) is not None: + args['from_'] = from_ else: raise ValueError( 'Required property \'from\' not present in SpeakerLabelsResult JSON' ) - if 'to' in _dict: - args['to'] = _dict.get('to') + if (to := _dict.get('to')) is not None: + args['to'] = to else: raise ValueError( 'Required property \'to\' not present in SpeakerLabelsResult JSON' ) - if 'speaker' in _dict: - args['speaker'] = _dict.get('speaker') + if (speaker := _dict.get('speaker')) is not None: + args['speaker'] = speaker else: raise ValueError( 'Required property \'speaker\' not present in SpeakerLabelsResult JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in SpeakerLabelsResult JSON' ) - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in SpeakerLabelsResult JSON' @@ -7119,24 +8613,31 @@ def __ne__(self, other: 'SpeakerLabelsResult') -> bool: return not self == other -class SpeechModel(): +class SpeechModel: """ Information about an available language model. - :attr str name: The name of the model for use as an identifier in calls to the + :param str name: The name of the model for use as an identifier in calls to the service (for example, `en-US_BroadbandModel`). - :attr str language: The language identifier of the model (for example, `en-US`). - :attr int rate: The sampling rate (minimum acceptable rate for audio) used by + :param str language: The language identifier of the model (for example, + `en-US`). + :param int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. - :attr str url: The URI for the model. - :attr SupportedFeatures supported_features: Indicates whether select service + :param str url: The URI for the model. + :param SupportedFeatures supported_features: Indicates whether select service features are supported with the model. - :attr str description: A brief description of the model. + :param str description: A brief description of the model. """ - def __init__(self, name: str, language: str, rate: int, url: str, - supported_features: 'SupportedFeatures', - description: str) -> None: + def __init__( + self, + name: str, + language: str, + rate: int, + url: str, + supported_features: 'SupportedFeatures', + description: str, + ) -> None: """ Initialize a SpeechModel object. @@ -7162,36 +8663,36 @@ def __init__(self, name: str, language: str, rate: int, url: str, def from_dict(cls, _dict: Dict) -> 'SpeechModel': """Initialize a SpeechModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SpeechModel JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in SpeechModel JSON' ) - if 'rate' in _dict: - args['rate'] = _dict.get('rate') + if (rate := _dict.get('rate')) is not None: + args['rate'] = rate else: raise ValueError( 'Required property \'rate\' not present in SpeechModel JSON') - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SpeechModel JSON') - if 'supported_features' in _dict: + if (supported_features := _dict.get('supported_features')) is not None: args['supported_features'] = SupportedFeatures.from_dict( - _dict.get('supported_features')) + supported_features) else: raise ValueError( 'Required property \'supported_features\' not present in SpeechModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') + if (description := _dict.get('description')) is not None: + args['description'] = description else: raise ValueError( 'Required property \'description\' not present in SpeechModel JSON' @@ -7217,7 +8718,10 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features.to_dict() + if isinstance(self.supported_features, dict): + _dict['supported_features'] = self.supported_features + else: + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict @@ -7241,15 +8745,18 @@ def __ne__(self, other: 'SpeechModel') -> bool: return not self == other -class SpeechModels(): +class SpeechModels: """ Information about the available language models. - :attr List[SpeechModel] models: An array of `SpeechModel` objects that provides + :param List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ - def __init__(self, models: List['SpeechModel']) -> None: + def __init__( + self, + models: List['SpeechModel'], + ) -> None: """ Initialize a SpeechModels object. @@ -7262,10 +8769,8 @@ def __init__(self, models: List['SpeechModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeechModels': """Initialize a SpeechModels object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - SpeechModel.from_dict(x) for x in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [SpeechModel.from_dict(v) for v in models] else: raise ValueError( 'Required property \'models\' not present in SpeechModels JSON') @@ -7280,7 +8785,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -7302,33 +8813,35 @@ def __ne__(self, other: 'SpeechModels') -> bool: return not self == other -class SpeechRecognitionAlternative(): +class SpeechRecognitionAlternative: """ An alternative transcript from speech recognition results. - :attr str transcript: A transcription of the audio. - :attr float confidence: (optional) A score that indicates the service's + :param str transcript: A transcription of the audio. + :param float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. The service returns a confidence score only for the best alternative and only with results marked as final. - :attr List[str] timestamps: (optional) Time alignments for each word from the + :param List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. - :attr List[str] word_confidence: (optional) A confidence score for each word of + :param List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.86]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ - def __init__(self, - transcript: str, - *, - confidence: float = None, - timestamps: List[str] = None, - word_confidence: List[str] = None) -> None: + def __init__( + self, + transcript: str, + *, + confidence: Optional[float] = None, + timestamps: Optional[List[str]] = None, + word_confidence: Optional[List[str]] = None, + ) -> None: """ Initialize a SpeechRecognitionAlternative object. @@ -7357,18 +8870,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionAlternative': """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} - if 'transcript' in _dict: - args['transcript'] = _dict.get('transcript') + if (transcript := _dict.get('transcript')) is not None: + args['transcript'] = transcript else: raise ValueError( 'Required property \'transcript\' not present in SpeechRecognitionAlternative JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'timestamps' in _dict: - args['timestamps'] = _dict.get('timestamps') - if 'word_confidence' in _dict: - args['word_confidence'] = _dict.get('word_confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (timestamps := _dict.get('timestamps')) is not None: + args['timestamps'] = timestamps + if (word_confidence := _dict.get('word_confidence')) is not None: + args['word_confidence'] = word_confidence return cls(**args) @classmethod @@ -7409,31 +8922,31 @@ def __ne__(self, other: 'SpeechRecognitionAlternative') -> bool: return not self == other -class SpeechRecognitionResult(): +class SpeechRecognitionResult: """ Component results for a speech recognition request. - :attr bool final: An indication of whether the transcription results are final: + :param bool final: An indication of whether the transcription results are final: * If `true`, the results for this utterance are final. They are guaranteed not to be updated further. * If `false`, the results are interim. They can be updated with further interim results until final results are eventually sent. - **Note:** Because `final` is a reserved word in Java and Swift, the field is - renamed `xFinal` in Java and is escaped with back quotes in Swift. - :attr List[SpeechRecognitionAlternative] alternatives: An array of alternative + **Note:** Because `final` is a reserved word in Java, the field is renamed + `xFinal` in Java. + :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. - :attr dict keywords_result: (optional) A dictionary (or associative array) whose - keys are the strings specified for `keywords` if both that parameter and + :param dict keywords_result: (optional) A dictionary (or associative array) + whose keys are the strings specified for `keywords` if both that parameter and `keywords_threshold` are specified. The value for each key is an array of matches spotted in the audio for that keyword. Each match is described by a `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. - :attr List[WordAlternativeResults] word_alternatives: (optional) An array of + :param List[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. - :attr str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` + :param str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` parameter is `true`, describes the reason for the split: * `end_of_data` - The end of the input audio stream. * `full_stop` - A full semantic stop, such as for the conclusion of a @@ -7445,13 +8958,15 @@ class SpeechRecognitionResult(): * `silence` - A pause or silence that is at least as long as the pause interval. """ - def __init__(self, - final: bool, - alternatives: List['SpeechRecognitionAlternative'], - *, - keywords_result: dict = None, - word_alternatives: List['WordAlternativeResults'] = None, - end_of_utterance: str = None) -> None: + def __init__( + self, + final: bool, + alternatives: List['SpeechRecognitionAlternative'], + *, + keywords_result: Optional[dict] = None, + word_alternatives: Optional[List['WordAlternativeResults']] = None, + end_of_utterance: Optional[str] = None, + ) -> None: """ Initialize a SpeechRecognitionResult object. @@ -7461,8 +8976,8 @@ def __init__(self, not to be updated further. * If `false`, the results are interim. They can be updated with further interim results until final results are eventually sent. - **Note:** Because `final` is a reserved word in Java and Swift, the field - is renamed `xFinal` in Java and is escaped with back quotes in Swift. + **Note:** Because `final` is a reserved word in Java, the field is renamed + `xFinal` in Java. :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. @@ -7499,30 +9014,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in SpeechRecognitionResult JSON' ) - if 'alternatives' in _dict: + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - SpeechRecognitionAlternative.from_dict(x) - for x in _dict.get('alternatives') + SpeechRecognitionAlternative.from_dict(v) for v in alternatives ] else: raise ValueError( 'Required property \'alternatives\' not present in SpeechRecognitionResult JSON' ) - if 'keywords_result' in _dict: - args['keywords_result'] = _dict.get('keywords_result') - if 'word_alternatives' in _dict: + if (keywords_result := _dict.get('keywords_result')) is not None: + args['keywords_result'] = keywords_result + if (word_alternatives := _dict.get('word_alternatives')) is not None: args['word_alternatives'] = [ - WordAlternativeResults.from_dict(x) - for x in _dict.get('word_alternatives') + WordAlternativeResults.from_dict(v) for v in word_alternatives ] - if 'end_of_utterance' in _dict: - args['end_of_utterance'] = _dict.get('end_of_utterance') + if (end_of_utterance := _dict.get('end_of_utterance')) is not None: + args['end_of_utterance'] = end_of_utterance return cls(**args) @classmethod @@ -7536,15 +9049,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'final') and self.final is not None: _dict['final'] = self.final if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'keywords_result') and self.keywords_result is not None: _dict['keywords_result'] = self.keywords_result if hasattr(self, 'word_alternatives') and self.word_alternatives is not None: - _dict['word_alternatives'] = [ - x.to_dict() for x in self.word_alternatives - ] + word_alternatives_list = [] + for v in self.word_alternatives: + if isinstance(v, dict): + word_alternatives_list.append(v) + else: + word_alternatives_list.append(v.to_dict()) + _dict['word_alternatives'] = word_alternatives_list if hasattr(self, 'end_of_utterance') and self.end_of_utterance is not None: _dict['end_of_utterance'] = self.end_of_utterance @@ -7581,17 +9104,18 @@ class EndOfUtteranceEnum(str, Enum): use. * `silence` - A pause or silence that is at least as long as the pause interval. """ + END_OF_DATA = 'end_of_data' FULL_STOP = 'full_stop' RESET = 'reset' SILENCE = 'silence' -class SpeechRecognitionResults(): +class SpeechRecognitionResults: """ The complete results for a speech recognition request. - :attr List[SpeechRecognitionResult] results: (optional) An array of + :param List[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further @@ -7602,29 +9126,31 @@ class SpeechRecognitionResults(): incremented to the lowest index in the array that has changed for new results. For more information, see [Understanding speech recognition results](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-basic-response). - :attr int result_index: (optional) An index that indicates a change point in the - `results` array. The service increments the index for additional results that it - sends for new audio for the same request. All results with the same index are - delivered at the same time. The same index can include multiple final results - that are delivered with the same response. - :attr List[SpeakerLabelsResult] speaker_labels: (optional) An array of + :param int result_index: (optional) An index that indicates a change point in + the `results` array. The service increments the index for additional results + that it sends for new audio for the same request. All results with the same + index are delivered at the same time. The same index can include multiple final + results that are delivered with the same response. + :param List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also requested for methods that support them, it is possible for a `SpeechRecognitionResults` object to include only the `speaker_labels` field. - :attr ProcessingMetrics processing_metrics: (optional) If processing metrics are - requested, information about the service's processing of the input audio. + :param ProcessingMetrics processing_metrics: (optional) If processing metrics + are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous [Recognize audio](#recognize) method. - :attr AudioMetrics audio_metrics: (optional) If audio metrics are requested, + :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. - :attr List[str] warnings: (optional) An array of warning messages associated + :param List[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the form - `"{invalid_arg_1}, {invalid_arg_2}."` + `"{invalid_arg_1}, {invalid_arg_2}."` (If you use the `character_insertion_bias` + parameter with a previous-generation model, the warning message refers to the + parameter as `lambdaBias`.) * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your custom model has @@ -7633,16 +9159,22 @@ class SpeechRecognitionResults(): do not do that you will be automatically switched to base model when you used the non-updated custom model."` In both cases, the request succeeds despite the warnings. + :param EnrichedResults enriched_results: (optional) If enriched results are + requested, transcription with inserted punctuation marks such as periods, + commas, question marks, and exclamation points. """ - def __init__(self, - *, - results: List['SpeechRecognitionResult'] = None, - result_index: int = None, - speaker_labels: List['SpeakerLabelsResult'] = None, - processing_metrics: 'ProcessingMetrics' = None, - audio_metrics: 'AudioMetrics' = None, - warnings: List[str] = None) -> None: + def __init__( + self, + *, + results: Optional[List['SpeechRecognitionResult']] = None, + result_index: Optional[int] = None, + speaker_labels: Optional[List['SpeakerLabelsResult']] = None, + processing_metrics: Optional['ProcessingMetrics'] = None, + audio_metrics: Optional['AudioMetrics'] = None, + warnings: Optional[List[str]] = None, + enriched_results: Optional['EnrichedResults'] = None, + ) -> None: """ Initialize a SpeechRecognitionResults object. @@ -7681,7 +9213,9 @@ def __init__(self, * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the - form `"{invalid_arg_1}, {invalid_arg_2}."` + form `"{invalid_arg_1}, {invalid_arg_2}."` (If you use the + `character_insertion_bias` parameter with a previous-generation model, the + warning message refers to the parameter as `lambdaBias`.) * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your @@ -7690,6 +9224,9 @@ def __init__(self, the new base model. If you do not do that you will be automatically switched to base model when you used the non-updated custom model."` In both cases, the request succeeds despite the warnings. + :param EnrichedResults enriched_results: (optional) If enriched results are + requested, transcription with inserted punctuation marks such as periods, + commas, question marks, and exclamation points. """ self.results = results self.result_index = result_index @@ -7697,31 +9234,32 @@ def __init__(self, self.processing_metrics = processing_metrics self.audio_metrics = audio_metrics self.warnings = warnings + self.enriched_results = enriched_results @classmethod def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} - if 'results' in _dict: + if (results := _dict.get('results')) is not None: args['results'] = [ - SpeechRecognitionResult.from_dict(x) - for x in _dict.get('results') + SpeechRecognitionResult.from_dict(v) for v in results ] - if 'result_index' in _dict: - args['result_index'] = _dict.get('result_index') - if 'speaker_labels' in _dict: + if (result_index := _dict.get('result_index')) is not None: + args['result_index'] = result_index + if (speaker_labels := _dict.get('speaker_labels')) is not None: args['speaker_labels'] = [ - SpeakerLabelsResult.from_dict(x) - for x in _dict.get('speaker_labels') + SpeakerLabelsResult.from_dict(v) for v in speaker_labels ] - if 'processing_metrics' in _dict: + if (processing_metrics := _dict.get('processing_metrics')) is not None: args['processing_metrics'] = ProcessingMetrics.from_dict( - _dict.get('processing_metrics')) - if 'audio_metrics' in _dict: - args['audio_metrics'] = AudioMetrics.from_dict( - _dict.get('audio_metrics')) - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + processing_metrics) + if (audio_metrics := _dict.get('audio_metrics')) is not None: + args['audio_metrics'] = AudioMetrics.from_dict(audio_metrics) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings + if (enriched_results := _dict.get('enriched_results')) is not None: + args['enriched_results'] = EnrichedResults.from_dict( + enriched_results) return cls(**args) @classmethod @@ -7733,19 +9271,43 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'result_index') and self.result_index is not None: _dict['result_index'] = self.result_index if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: - _dict['speaker_labels'] = [x.to_dict() for x in self.speaker_labels] + speaker_labels_list = [] + for v in self.speaker_labels: + if isinstance(v, dict): + speaker_labels_list.append(v) + else: + speaker_labels_list.append(v.to_dict()) + _dict['speaker_labels'] = speaker_labels_list if hasattr( self, 'processing_metrics') and self.processing_metrics is not None: - _dict['processing_metrics'] = self.processing_metrics.to_dict() + if isinstance(self.processing_metrics, dict): + _dict['processing_metrics'] = self.processing_metrics + else: + _dict['processing_metrics'] = self.processing_metrics.to_dict() if hasattr(self, 'audio_metrics') and self.audio_metrics is not None: - _dict['audio_metrics'] = self.audio_metrics.to_dict() + if isinstance(self.audio_metrics, dict): + _dict['audio_metrics'] = self.audio_metrics + else: + _dict['audio_metrics'] = self.audio_metrics.to_dict() if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings + if hasattr(self, + 'enriched_results') and self.enriched_results is not None: + if isinstance(self.enriched_results, dict): + _dict['enriched_results'] = self.enriched_results + else: + _dict['enriched_results'] = self.enriched_results.to_dict() return _dict def _to_dict(self): @@ -7767,15 +9329,15 @@ def __ne__(self, other: 'SpeechRecognitionResults') -> bool: return not self == other -class SupportedFeatures(): +class SupportedFeatures: """ Indicates whether select service features are supported with the model. - :attr bool custom_language_model: Indicates whether the customization interface + :param bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. - :attr bool custom_acoustic_model: Indicates whether the customization interface + :param bool custom_acoustic_model: Indicates whether the customization interface can be used to create a custom acoustic model based on the language model. - :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can + :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels are supported for use only with the following languages and models: @@ -7786,18 +9348,20 @@ class SupportedFeatures(): (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish transcription only. Speaker labels are not supported for use with any other languages or models. - :attr bool low_latency: (optional) Indicates whether the `low_latency` parameter - can be used with a next-generation language model. The field is returned only - for next-generation models. Previous-generation models do not support the - `low_latency` parameter. + :param bool low_latency: (optional) Indicates whether the `low_latency` + parameter can be used with a next-generation language model. The field is + returned only for next-generation models. Previous-generation models do not + support the `low_latency` parameter. """ - def __init__(self, - custom_language_model: bool, - custom_acoustic_model: bool, - speaker_labels: bool, - *, - low_latency: bool = None) -> None: + def __init__( + self, + custom_language_model: bool, + custom_acoustic_model: bool, + speaker_labels: bool, + *, + low_latency: Optional[bool] = None, + ) -> None: """ Initialize a SupportedFeatures object. @@ -7834,26 +9398,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - if 'custom_language_model' in _dict: - args['custom_language_model'] = _dict.get('custom_language_model') + if (custom_language_model := + _dict.get('custom_language_model')) is not None: + args['custom_language_model'] = custom_language_model else: raise ValueError( 'Required property \'custom_language_model\' not present in SupportedFeatures JSON' ) - if 'custom_acoustic_model' in _dict: - args['custom_acoustic_model'] = _dict.get('custom_acoustic_model') + if (custom_acoustic_model := + _dict.get('custom_acoustic_model')) is not None: + args['custom_acoustic_model'] = custom_acoustic_model else: raise ValueError( 'Required property \'custom_acoustic_model\' not present in SupportedFeatures JSON' ) - if 'speaker_labels' in _dict: - args['speaker_labels'] = _dict.get('speaker_labels') + if (speaker_labels := _dict.get('speaker_labels')) is not None: + args['speaker_labels'] = speaker_labels else: raise ValueError( 'Required property \'speaker_labels\' not present in SupportedFeatures JSON' ) - if 'low_latency' in _dict: - args['low_latency'] = _dict.get('low_latency') + if (low_latency := _dict.get('low_latency')) is not None: + args['low_latency'] = low_latency return cls(**args) @classmethod @@ -7895,18 +9461,22 @@ def __ne__(self, other: 'SupportedFeatures') -> bool: return not self == other -class TrainingResponse(): +class TrainingResponse: """ The response from training of a custom language or custom acoustic model. - :attr List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` + :param List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` objects that lists any invalid resources contained in the custom model. For custom language models, invalid resources are grouped and identified by type of resource. The method can return warnings only if the `strict` parameter is set to `false`. """ - def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: + def __init__( + self, + *, + warnings: Optional[List['TrainingWarning']] = None, + ) -> None: """ Initialize a TrainingResponse object. @@ -7922,10 +9492,8 @@ def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingResponse': """Initialize a TrainingResponse object from a json dictionary.""" args = {} - if 'warnings' in _dict: - args['warnings'] = [ - TrainingWarning.from_dict(x) for x in _dict.get('warnings') - ] + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [TrainingWarning.from_dict(v) for v in warnings] return cls(**args) @classmethod @@ -7937,7 +9505,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] + warnings_list = [] + for v in self.warnings: + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list return _dict def _to_dict(self): @@ -7959,20 +9533,24 @@ def __ne__(self, other: 'TrainingResponse') -> bool: return not self == other -class TrainingWarning(): +class TrainingWarning: """ A warning from training of a custom language or custom acoustic model. - :attr str code: An identifier for the type of invalid resources listed in the + :param str code: An identifier for the type of invalid resources listed in the `description` field. - :attr str message: A warning message that lists the invalid resources that are + :param str message: A warning message that lists the invalid resources that are excluded from the custom model's training. The message has the following format: `Analysis of the following {resource_type} has not completed successfully: [{resource_names}]. They will be excluded from custom {model_type} model training.`. """ - def __init__(self, code: str, message: str) -> None: + def __init__( + self, + code: str, + message: str, + ) -> None: """ Initialize a TrainingWarning object. @@ -7991,14 +9569,14 @@ def __init__(self, code: str, message: str) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingWarning': """Initialize a TrainingWarning object from a json dictionary.""" args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in TrainingWarning JSON' ) - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message else: raise ValueError( 'Required property \'message\' not present in TrainingWarning JSON' @@ -8041,32 +9619,44 @@ class CodeEnum(str, Enum): """ An identifier for the type of invalid resources listed in the `description` field. """ + INVALID_AUDIO_FILES = 'invalid_audio_files' INVALID_CORPUS_FILES = 'invalid_corpus_files' INVALID_GRAMMAR_FILES = 'invalid_grammar_files' INVALID_WORDS = 'invalid_words' -class Word(): +class Word: """ Information about a word from a custom language model. - :attr str word: A word from the custom model's words resource. The spelling of + :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr List[str] sounds_like: _For a custom model that is based on a - previous-generation model_, an array of as many as five pronunciations for the - word. The array can include the sounds-like pronunciation that is automatically - generated by the service if none is provided when the word is added to the - custom model; the service adds this pronunciation when it finishes processing - the word. - _For a custom model that is based on a next-generation model_, this field does - not apply. Custom models based on next-generation models do not support the - `sounds_like` field, which is ignored. - :attr str display_as: The spelling of the word that the service uses to display - the word in a transcript. The field contains an empty string if no display-as - value is provided for the word, in which case the word is displayed as it is - spelled. - :attr int count: _For a custom model that is based on a previous-generation + :param List[str] mapping_only: (optional) (Optional) Parameter for custom words. + You can use the 'mapping_only' key in custom words as a form of post processing. + A boolean value that indicates whether the added word should be used to + fine-tune the mode for selected next-gen models. This field appears in the + response body only when it's 'For a custom model that is based on a + previous-generation model', the mapping_only field is populated with the value + set by the user, but would not be used. + :param List[str] sounds_like: An array of as many as five pronunciations for the + word. + * _For a custom model that is based on a previous-generation model_, in addition + to sounds-like pronunciations that were added by a user, the array can include a + sounds-like pronunciation that is automatically generated by the service if none + is provided when the word is added to the custom model. + * _For a custom model that is based on a next-generation model_, the array can + include only sounds-like pronunciations that were added by a user. + :param str display_as: The spelling of the word that the service uses to display + the word in a transcript. + * _For a custom model that is based on a previous-generation model_, the field + can contain an empty string if no display-as value is provided for a word that + exists in the service's base vocabulary. In this case, the word is displayed as + it is spelled. + * _For a custom model that is based on a next-generation model_, the service + uses the spelling of the word as the value of the display-as field when the word + is added to the model. + :param int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before @@ -8075,7 +9665,7 @@ class Word(): the number of times it is found in corpora and grammars. _For a custom model that is based on a next-generation model_, the `count` field for any word is always `1`. - :attr List[str] source: An array of sources that describes how the word was + :param List[str] source: An array of sources that describes how the word was added to the custom model's words resource. * _For a custom model that is based on previous-generation model,_ the field includes the name of each corpus and grammar from which the service extracted @@ -8086,37 +9676,44 @@ class Word(): shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. - :attr List[WordError] error: (optional) If the service discovered one or more + :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ - def __init__(self, - word: str, - sounds_like: List[str], - display_as: str, - count: int, - source: List[str], - *, - error: List['WordError'] = None) -> None: + def __init__( + self, + word: str, + sounds_like: List[str], + display_as: str, + count: int, + source: List[str], + *, + mapping_only: Optional[List[str]] = None, + error: Optional[List['WordError']] = None, + ) -> None: """ Initialize a Word object. :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :param List[str] sounds_like: _For a custom model that is based on a - previous-generation model_, an array of as many as five pronunciations for - the word. The array can include the sounds-like pronunciation that is - automatically generated by the service if none is provided when the word is - added to the custom model; the service adds this pronunciation when it - finishes processing the word. - _For a custom model that is based on a next-generation model_, this field - does not apply. Custom models based on next-generation models do not - support the `sounds_like` field, which is ignored. + :param List[str] sounds_like: An array of as many as five pronunciations + for the word. + * _For a custom model that is based on a previous-generation model_, in + addition to sounds-like pronunciations that were added by a user, the array + can include a sounds-like pronunciation that is automatically generated by + the service if none is provided when the word is added to the custom model. + * _For a custom model that is based on a next-generation model_, the array + can include only sounds-like pronunciations that were added by a user. :param str display_as: The spelling of the word that the service uses to - display the word in a transcript. The field contains an empty string if no - display-as value is provided for the word, in which case the word is - displayed as it is spelled. + display the word in a transcript. + * _For a custom model that is based on a previous-generation model_, the + field can contain an empty string if no display-as value is provided for a + word that exists in the service's base vocabulary. In this case, the word + is displayed as it is spelled. + * _For a custom model that is based on a next-generation model_, the + service uses the spelling of the word as the value of the display-as field + when the word is added to the model. :param int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times @@ -8138,11 +9735,19 @@ def __init__(self, shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. + :param List[str] mapping_only: (optional) (Optional) Parameter for custom + words. You can use the 'mapping_only' key in custom words as a form of post + processing. A boolean value that indicates whether the added word should be + used to fine-tune the mode for selected next-gen models. This field appears + in the response body only when it's 'For a custom model that is based on a + previous-generation model', the mapping_only field is populated with the + value set by the user, but would not be used. :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ self.word = word + self.mapping_only = mapping_only self.sounds_like = sounds_like self.display_as = display_as self.count = count @@ -8153,33 +9758,35 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in Word JSON') - if 'sounds_like' in _dict: - args['sounds_like'] = _dict.get('sounds_like') + if (mapping_only := _dict.get('mapping_only')) is not None: + args['mapping_only'] = mapping_only + if (sounds_like := _dict.get('sounds_like')) is not None: + args['sounds_like'] = sounds_like else: raise ValueError( 'Required property \'sounds_like\' not present in Word JSON') - if 'display_as' in _dict: - args['display_as'] = _dict.get('display_as') + if (display_as := _dict.get('display_as')) is not None: + args['display_as'] = display_as else: raise ValueError( 'Required property \'display_as\' not present in Word JSON') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count else: raise ValueError( 'Required property \'count\' not present in Word JSON') - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in Word JSON') - if 'error' in _dict: - args['error'] = [WordError.from_dict(x) for x in _dict.get('error')] + if (error := _dict.get('error')) is not None: + args['error'] = [WordError.from_dict(v) for v in error] return cls(**args) @classmethod @@ -8192,6 +9799,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word + if hasattr(self, 'mapping_only') and self.mapping_only is not None: + _dict['mapping_only'] = self.mapping_only if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: @@ -8201,7 +9810,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'error') and self.error is not None: - _dict['error'] = [x.to_dict() for x in self.error] + error_list = [] + for v in self.error: + if isinstance(v, dict): + error_list.append(v) + else: + error_list.append(v.to_dict()) + _dict['error'] = error_list return _dict def _to_dict(self): @@ -8223,16 +9838,20 @@ def __ne__(self, other: 'Word') -> bool: return not self == other -class WordAlternativeResult(): +class WordAlternativeResult: """ An alternative hypothesis for a word from speech recognition results. - :attr float confidence: A confidence score for the word alternative hypothesis + :param float confidence: A confidence score for the word alternative hypothesis in the range of 0.0 to 1.0. - :attr str word: An alternative hypothesis for a word from the input audio. + :param str word: An alternative hypothesis for a word from the input audio. """ - def __init__(self, confidence: float, word: str) -> None: + def __init__( + self, + confidence: float, + word: str, + ) -> None: """ Initialize a WordAlternativeResult object. @@ -8247,14 +9866,14 @@ def __init__(self, confidence: float, word: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordAlternativeResult': """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in WordAlternativeResult JSON' ) - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in WordAlternativeResult JSON' @@ -8294,20 +9913,24 @@ def __ne__(self, other: 'WordAlternativeResult') -> bool: return not self == other -class WordAlternativeResults(): +class WordAlternativeResults: """ Information about alternative hypotheses for words from speech recognition results. - :attr float start_time: The start time in seconds of the word from the input + :param float start_time: The start time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr float end_time: The end time in seconds of the word from the input audio + :param float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr List[WordAlternativeResult] alternatives: An array of alternative + :param List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ - def __init__(self, start_time: float, end_time: float, - alternatives: List['WordAlternativeResult']) -> None: + def __init__( + self, + start_time: float, + end_time: float, + alternatives: List['WordAlternativeResult'], + ) -> None: """ Initialize a WordAlternativeResults object. @@ -8326,22 +9949,21 @@ def __init__(self, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} - if 'start_time' in _dict: - args['start_time'] = _dict.get('start_time') + if (start_time := _dict.get('start_time')) is not None: + args['start_time'] = start_time else: raise ValueError( 'Required property \'start_time\' not present in WordAlternativeResults JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in WordAlternativeResults JSON' ) - if 'alternatives' in _dict: + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - WordAlternativeResult.from_dict(x) - for x in _dict.get('alternatives') + WordAlternativeResult.from_dict(v) for v in alternatives ] else: raise ValueError( @@ -8362,7 +9984,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'end_time') and self.end_time is not None: _dict['end_time'] = self.end_time if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list return _dict def _to_dict(self): @@ -8384,11 +10012,11 @@ def __ne__(self, other: 'WordAlternativeResults') -> bool: return not self == other -class WordError(): +class WordError: """ An error associated with a word from a custom language model. - :attr str element: A key-value pair that describes an error associated with the + :param str element: A key-value pair that describes an error associated with the definition of a word in the words resource. The pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the problem and `message` describes the problem. The following example describes a @@ -8397,7 +10025,10 @@ class WordError(): '{suggested_string}'."`. """ - def __init__(self, element: str) -> None: + def __init__( + self, + element: str, + ) -> None: """ Initialize a WordError object. @@ -8415,8 +10046,8 @@ def __init__(self, element: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordError': """Initialize a WordError object from a json dictionary.""" args = {} - if 'element' in _dict: - args['element'] = _dict.get('element') + if (element := _dict.get('element')) is not None: + args['element'] = element else: raise ValueError( 'Required property \'element\' not present in WordError JSON') @@ -8453,16 +10084,19 @@ def __ne__(self, other: 'WordError') -> bool: return not self == other -class Words(): +class Words: """ Information about the words from a custom language model. - :attr List[Word] words: An array of `Word` objects that provides information + :param List[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ - def __init__(self, words: List['Word']) -> None: + def __init__( + self, + words: List['Word'], + ) -> None: """ Initialize a Words object. @@ -8476,8 +10110,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -8492,7 +10126,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list return _dict def _to_dict(self): diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index e9119ff72..5f3b3969a 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2021. +# (C) Copyright IBM Corp. 2018, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -42,10 +42,10 @@ def recognize_using_websocket(self, timestamps=None, profanity_filter=None, smart_formatting=None, + smart_formatting_version=None, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, - customization_id=None, grammar_name=None, redaction=None, processing_metrics=None, @@ -56,6 +56,8 @@ def recognize_using_websocket(self, speech_detector_sensitivity=None, background_audio_suppression=None, low_latency=None, + character_insertion_bias=None, + sad_module=None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -175,6 +177,9 @@ def recognize_using_websocket(self, **Note:** Applies to US English, Japanese, and Spanish transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param int smart_formatting_version: (optional) Smart formatting version is + for next-generation models and that is supported in US English, Brazilian + Portuguese, French and German languages. :param bool speaker_labels: (optional) If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. @@ -190,10 +195,6 @@ def recognize_using_websocket(self, labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. - :param str customization_id: (optional) **Deprecated.** Use the - `language_customization_id` parameter to specify the customization ID - (GUID) of a custom language model that is to be used with the recognition - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -287,6 +288,34 @@ def recognize_using_websocket(self, for next-generation models. * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + `Multimedia` and `Telephony` models, an indication of whether the service + is biased to recognize shorter or longer strings of characters when + developing transcription hypotheses. By default, the service is optimized + for each individual model to balance its recognition of strings of + different lengths. The model-specific bias is equivalent to 0.0. + The value that you specify represents a change from a model's default bias. + The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). + :param int sad_module: (optional) Detects speech boundaries within the + audio stream with better performance, improved noise suppression, faster + responsiveness, and increased accuracy. + Specify `sad_module: 2` + See [Speech Activity Detection + (SAD)](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#sad). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict @@ -321,7 +350,6 @@ def recognize_using_websocket(self, params = { 'model': model, - 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id @@ -343,6 +371,7 @@ def recognize_using_websocket(self, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction, @@ -353,7 +382,9 @@ def recognize_using_websocket(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'character_insertion_bias': character_insertion_bias, + 'low_latency': low_latency, + 'sad_module': sad_module, } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index c05763a08..0cd22fd74 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -30,6 +30,9 @@ def synthesize_using_websocket(self, voice=None, timings=None, customization_id=None, + spell_out_mode=None, + rate_percentage=None, + pitch_percentage=None, http_proxy_host=None, http_proxy_port=None, **kwargs): @@ -60,6 +63,51 @@ def synthesize_using_websocket(self, If you include a customization ID, you must call the method with the service credentials of the custom model's owner. Omit the parameter to use the specified voice with no customization. For more information, see [Understanding customization] (https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). + :param str spell_out_mode: (optional) *For German voices,* indicates how + the service is to spell out strings of individual letters. To indicate the + pace of the spelling, specify one of the following values: + * `default` - The service reads the characters at the rate at which it + synthesizes speech for the request. You can also omit the parameter + entirely to achieve the default behavior. + * `singles` - The service reads the characters one at a time, with a brief + pause between each character. + * `pairs` - The service reads the characters two at a time, with a brief + pause between each pair. + * `triples` - The service reads the characters three at a time, with a + brief pause between each triplet. + The parameter is available only for IBM Cloud. + **See also:** [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + :param int rate_percentage: (optional) The percentage change from the + default speaking rate of the voice that is used for speech synthesis. Each + voice has a default speaking rate that is optimized to represent a normal + rate of speech. The parameter accepts an integer that represents the + percentage change from the voice's default rate: + * Specify a signed negative integer to reduce the speaking rate by that + percentage. For example, -10 reduces the rate by ten percent. + * Specify an unsigned or signed positive integer to increase the speaking + rate by that percentage. For example, 10 and +10 increase the rate by ten + percent. + * Specify 0 or omit the parameter to get the default speaking rate for the + voice. + The parameter affects the rate for an entire request. + For more information, see [Modifying the speaking + rate](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-rate-percentage). + :param int pitch_percentage: (optional) The percentage change from the + default speaking pitch of the voice that is used for speech synthesis. Each + voice has a default speaking pitch that is optimized to represent a normal + tone of voice. The parameter accepts an integer that represents the + percentage change from the voice's default tone: + * Specify a signed negative integer to lower the voice's pitch by that + percentage. For example, -5 reduces the tone by five percent. + * Specify an unsigned or signed positive integer to increase the voice's + pitch by that percentage. For example, 5 and +5 increase the tone by five + percent. + * Specify 0 or omit the parameter to get the default speaking pitch for the + voice. + The parameter affects the pitch for an entire request. + For more information, see [Modifying the speaking + pitch](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-pitch-percentage). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param dict headers: A `dict` containing the request headers @@ -90,6 +138,9 @@ def synthesize_using_websocket(self, params = { 'voice': voice, 'customization_id': customization_id, + 'spell_out_mode': spell_out_mode, + 'rate_percentage': rate_percentage, + 'pitch_percentage': pitch_percentage } params = {k: v for k, v in params.items() if v is not None} url += '/v1/synthesize?{0}'.format(urlencode(params)) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 9d5514257..7748b75b1 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -30,18 +30,17 @@ that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic -Phonetic Representation (SPR). For phonetic translation, the Arabic, Chinese, Dutch, -Australian English, Korean, and Swedish voices support only IPA, not SPR. +Phonetic Representation (SPR). The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service -support custom prompts only for US English custom models and voices. +supports custom prompts only for US English custom models and voices. API Version: 1.0.0 See: https://cloud.ibm.com/docs/text-to-speech """ from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -85,7 +84,10 @@ def __init__( # Voices ######################### - def list_voices(self, **kwargs) -> DetailedResponse: + def list_voices( + self, + **kwargs, + ) -> DetailedResponse: """ List voices. @@ -94,8 +96,8 @@ def list_voices(self, **kwargs) -> DetailedResponse: list of voices can change from call to call; do not rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a voice](#getvoice). - **See also:** [Listing all available - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). + **See also:** [Listing all + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-all-voices). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -103,26 +105,35 @@ def list_voices(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_voices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voices', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/voices' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def get_voice(self, - voice: str, - *, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def get_voice( + self, + voice: str, + *, + customization_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get a voice. @@ -132,11 +143,7 @@ def get_voice(self, specified voice. To list information about all available voices, use the [List voices](#listvoices) method. **See also:** [Listing a specific - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-specific-voice). :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a @@ -149,28 +156,35 @@ def get_voice(self, :rtype: DetailedResponse with `dict` result representing a `Voice` object """ - if voice is None: + if not voice: raise ValueError('voice must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_voice') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_voice', + ) headers.update(sdk_headers) - params = {'customization_id': customization_id} + params = { + 'customization_id': customization_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['voice'] path_param_values = self.encode_path_vars(voice) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/voices/{voice}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -179,13 +193,18 @@ def get_voice(self, # Synthesis ######################### - def synthesize(self, - text: str, - *, - accept: str = None, - voice: str = None, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def synthesize( + self, + text: str, + *, + accept: Optional[str] = None, + voice: Optional[str] = None, + customization_id: Optional[str] = None, + spell_out_mode: Optional[str] = None, + rate_percentage: Optional[int] = None, + pitch_percentage: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Synthesize audio. @@ -197,16 +216,12 @@ def synthesize(self, specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. ### Audio formats (accept types) The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the - audio. You must specify a sampling rate for the `audio/l16` and `audio/mulaw` - formats. A specified sampling rate must lie in the range of 8 kHz to 192 kHz. Some - formats restrict the sampling rate to certain values, as noted. + audio. You must specify a sampling rate for the `audio/alaw`, `audio/l16`, and + `audio/mulaw` formats. A specified sampling rate must lie in the range of 8 kHz to + 192 kHz. Some formats restrict the sampling rate to certain values, as noted. * For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio: `endianness=big-endian` or `endianness=little-endian`. @@ -214,36 +229,43 @@ def synthesize(self, of the response audio. If you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec (`audio/ogg;codecs=opus`). The service always returns single-channel audio. + * `audio/alaw` - You must specify the `rate` of the audio. * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. * `audio/flac` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for all other voices. * `audio/l16` - You must specify the `rate` of the audio. You can optionally specify the `endianness` of the audio. The default endianness is `little-endian`. * `audio/mp3` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for for all other + voices. * `audio/mpeg` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for all other voices. * `audio/mulaw` - You must specify the `rate` of the audio. * `audio/ogg` - The service returns the audio in the `vorbis` codec. You can - optionally specify the `rate` of the audio. The default sampling rate is 22,050 + optionally specify the `rate` of the audio. The default sampling rate is 48,000 Hz. * `audio/ogg;codecs=opus` - You can optionally specify the `rate` of the audio. Only the following values are valid sampling rates: `48000`, `24000`, `16000`, `12000`, or `8000`. If you specify a value other than one of these, the service returns an error. The default sampling rate is 48,000 Hz. * `audio/ogg;codecs=vorbis` - You can optionally specify the `rate` of the audio. - The default sampling rate is 22,050 Hz. + The default sampling rate is 48,000 Hz. * `audio/wav` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for all other voices. * `audio/webm` - The service returns the audio in the `opus` codec. The service returns audio with a sampling rate of 48,000 Hz. * `audio/webm;codecs=opus` - The service returns audio with a sampling rate of 48,000 Hz. * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. - The default sampling rate is 22,050 Hz. + The default sampling rate is 48,000 Hz. For more information about specifying an audio format, including additional details about some of the formats, see [Using audio formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats). + **Note:** By default, the service returns audio in the Ogg audio format with the + Opus codec (`audio/ogg;codecs=opus`). However, the Ogg audio format is not + supported with the Safari browser. If you are using the service with the Safari + browser, you must use the `Accept` request header or the `accept` query parameter + specify a different format in which you want the service to return the audio. ### Warning messages If a request includes invalid query parameters, the service returns a `Warnings` response header that provides messages about the invalid parameters. The warning @@ -257,25 +279,67 @@ def synthesize(self, audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. - :param str voice: (optional) The voice to use for synthesis. If you omit - the `voice` parameter, the service uses a default voice, which depends on - the version of the service that you are using: - * _For IBM Cloud,_ the service always uses the US English + :param str voice: (optional) The voice to use for speech synthesis. If you + omit the `voice` parameter, the service uses the US English `en-US_MichaelV3Voice` by default. - * _For IBM Cloud Pak for Data,_ the default voice depends on the voices - that you installed. If you installed the _enhanced neural voices_, the - service uses the US English `en-US_MichaelV3Voice` by default; if that - voice is not installed, you must specify a voice. If you installed the - _neural voices_, the service always uses the Australian English - `en-AU_MadisonVoice` by default. - **See also:** See also [Using languages and - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_MichaelV3Voice`, you must either specify a voice with the request or + specify a new default voice for your installation of the service. + **See also:** + * [Languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) + * [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str customization_id: (optional) The customization ID (GUID) of a custom model to use for the synthesis. If a custom model is specified, it works only if it matches the language of the indicated voice. You must make the request with credentials for the instance of the service that owns the custom model. Omit the parameter to use the specified voice with no customization. + :param str spell_out_mode: (optional) *For German voices,* indicates how + the service is to spell out strings of individual letters. To indicate the + pace of the spelling, specify one of the following values: + * `default` - The service reads the characters at the rate at which it + synthesizes speech for the request. You can also omit the parameter + entirely to achieve the default behavior. + * `singles` - The service reads the characters one at a time, with a brief + pause between each character. + * `pairs` - The service reads the characters two at a time, with a brief + pause between each pair. + * `triples` - The service reads the characters three at a time, with a + brief pause between each triplet. + For more information, see [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + :param int rate_percentage: (optional) The percentage change from the + default speaking rate of the voice that is used for speech synthesis. Each + voice has a default speaking rate that is optimized to represent a normal + rate of speech. The parameter accepts an integer that represents the + percentage change from the voice's default rate: + * Specify a signed negative integer to reduce the speaking rate by that + percentage. For example, -10 reduces the rate by ten percent. + * Specify an unsigned or signed positive integer to increase the speaking + rate by that percentage. For example, 10 and +10 increase the rate by ten + percent. + * Specify 0 or omit the parameter to get the default speaking rate for the + voice. + The parameter affects the rate for an entire request. + For more information, see [Modifying the speaking + rate](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-rate-percentage). + :param int pitch_percentage: (optional) The percentage change from the + default speaking pitch of the voice that is used for speech synthesis. Each + voice has a default speaking pitch that is optimized to represent a normal + tone of voice. The parameter accepts an integer that represents the + percentage change from the voice's default tone: + * Specify a signed negative integer to lower the voice's pitch by that + percentage. For example, -5 reduces the tone by five percent. + * Specify an unsigned or signed positive integer to increase the voice's + pitch by that percentage. For example, 5 and +5 increase the tone by five + percent. + * Specify 0 or omit the parameter to get the default speaking pitch for the + voice. + The parameter affects the pitch for an entire request. + For more information, see [Modifying the speaking + pitch](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-pitch-percentage). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `BinaryIO` result @@ -283,28 +347,43 @@ def synthesize(self, if text is None: raise ValueError('text must be provided') - headers = {'Accept': accept} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='synthesize') + headers = { + 'Accept': accept, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='synthesize', + ) headers.update(sdk_headers) - params = {'voice': voice, 'customization_id': customization_id} + params = { + 'voice': voice, + 'customization_id': customization_id, + 'spell_out_mode': spell_out_mode, + 'rate_percentage': rate_percentage, + 'pitch_percentage': pitch_percentage, + } - data = {'text': text} + data = { + 'text': text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/synthesize' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -313,13 +392,15 @@ def synthesize(self, # Pronunciation ######################### - def get_pronunciation(self, - text: str, - *, - voice: str = None, - format: str = None, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def get_pronunciation( + self, + text: str, + *, + voice: Optional[str] = None, + format: Optional[str] = None, + customization_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get pronunciation. @@ -329,19 +410,20 @@ def get_pronunciation(self, for a specific custom model to see the translation for that model. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which - the pronunciation is to be returned. All voices for the same language (for - example, `en-US`) return the same translation. + the pronunciation is to be returned. If you omit the `voice` parameter, the + service uses the US English `en-US_MichaelV3Voice` by default. All voices + for the same language (for example, `en-US`) return the same translation. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_MichaelV3Voice`, you must either specify a voice with the request or + specify a new default voice for your installation of the service. + **See also:** [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str format: (optional) The phoneme format in which to return the - pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. Omit the parameter to obtain the pronunciation - in the default format. + pronunciation. Omit the parameter to obtain the pronunciation in the + default format. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which the pronunciation is to be returned. The language of a specified custom model must match the language of the specified voice. If @@ -355,30 +437,35 @@ def get_pronunciation(self, :rtype: DetailedResponse with `dict` result representing a `Pronunciation` object """ - if text is None: + if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_pronunciation') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_pronunciation', + ) headers.update(sdk_headers) params = { 'text': text, 'voice': voice, 'format': format, - 'customization_id': customization_id + 'customization_id': customization_id, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/pronunciation' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -387,12 +474,14 @@ def get_pronunciation(self, # Custom models ######################### - def create_custom_model(self, - name: str, - *, - language: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_custom_model( + self, + name: str, + *, + language: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom model. @@ -402,24 +491,21 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR` language - identifier cannot be used to create a custom model; use the `ar-MS` identifier - instead. - :param str name: The name of the new custom model. + :param str name: The name of the new custom model. Use a localized name + that matches the language of the custom model. Use a name that describes + the purpose of the custom model, such as `Medical custom model` or `Legal + custom model`. Use a name that is unique among all custom models that you + own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str language: (optional) The language of the new custom model. You create a custom model for a specific language, not for a specific voice. A custom model can be used with any voice for its specified language. Omit the parameter to use the the default language, `en-US`. - **Important:** If you are using the service on IBM Cloud Pak for Data _and_ - you install the neural voices, the `language`parameter is required. You - must specify the language for the custom model in the indicated format (for - example, `en-AU` for Australian English). The request fails if you do not - specify a language. - :param str description: (optional) A description of the new custom model. - Specifying a description is recommended. + :param str description: (optional) A recommended description of the new + custom model. Use a localized description that matches the language of the + custom model. Include a maximum of 128 characters in the description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `CustomModel` object @@ -428,33 +514,44 @@ def create_custom_model(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_custom_model', + ) headers.update(sdk_headers) - data = {'name': name, 'language': language, 'description': description} + data = { + 'name': name, + 'language': language, + 'description': description, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_custom_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_custom_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom models. @@ -476,33 +573,42 @@ def list_custom_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_custom_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_models', + ) headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_custom_model(self, - customization_id: str, - *, - name: str = None, - description: str = None, - words: List['Word'] = None, - **kwargs) -> DetailedResponse: + def update_custom_model( + self, + customization_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + words: Optional[List['Word']] = None, + **kwargs, + ) -> DetailedResponse: """ Update a custom model. @@ -543,39 +649,51 @@ def update_custom_model(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is not None: words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_custom_model', + ) headers.update(sdk_headers) - data = {'name': name, 'description': description, 'words': words} + data = { + 'name': name, + 'description': description, + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_custom_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_custom_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom model. @@ -595,29 +713,39 @@ def get_custom_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `CustomModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_custom_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_custom_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom model. @@ -634,24 +762,29 @@ def delete_custom_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -660,8 +793,12 @@ def delete_custom_model(self, customization_id: str, # Custom words ######################### - def add_words(self, customization_id: str, words: List['Word'], - **kwargs) -> DetailedResponse: + def add_words( + self, + customization_id: str, + words: List['Word'], + **kwargs, + ) -> DetailedResponse: """ Add custom words. @@ -704,24 +841,29 @@ def add_words(self, customization_id: str, words: List['Word'], :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words', + ) headers.update(sdk_headers) - data = {'words': words} + data = { + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -729,15 +871,21 @@ def add_words(self, customization_id: str, words: List['Word'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_words( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List custom words. @@ -755,16 +903,19 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Words` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -772,18 +923,24 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_word(self, - customization_id: str, - word: str, - translation: str, - *, - part_of_speech: str = None, - **kwargs) -> DetailedResponse: + def add_word( + self, + customization_id: str, + word: str, + translation: str, + *, + part_of_speech: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a custom word. @@ -818,9 +975,8 @@ def add_word(self, :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. A sounds-like is one or more words that, when - combined, sound like the word. + translation. A sounds-like is one or more words that, when combined, sound + like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -833,41 +989,53 @@ def add_word(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') if translation is None: raise ValueError('translation must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word', + ) headers.update(sdk_headers) - data = {'translation': translation, 'part_of_speech': part_of_speech} + data = { + 'translation': translation, + 'part_of_speech': part_of_speech, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'word'] path_param_values = self.encode_path_vars(customization_id, word) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_word(self, customization_id: str, word: str, - **kwargs) -> DetailedResponse: + def get_word( + self, + customization_id: str, + word: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom word. @@ -886,18 +1054,21 @@ def get_word(self, customization_id: str, word: str, :rtype: DetailedResponse with `dict` result representing a `Translation` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word'] @@ -905,13 +1076,21 @@ def get_word(self, customization_id: str, word: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_word(self, customization_id: str, word: str, - **kwargs) -> DetailedResponse: + def delete_word( + self, + customization_id: str, + word: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom word. @@ -929,27 +1108,32 @@ def delete_word(self, customization_id: str, word: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'word'] path_param_values = self.encode_path_vars(customization_id, word) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -958,8 +1142,11 @@ def delete_word(self, customization_id: str, word: str, # Custom prompts ######################### - def list_custom_prompts(self, customization_id: str, - **kwargs) -> DetailedResponse: + def list_custom_prompts( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List custom prompts. @@ -983,16 +1170,19 @@ def list_custom_prompts(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompts` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_custom_prompts') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_prompts', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1000,14 +1190,23 @@ def list_custom_prompts(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_custom_prompt(self, customization_id: str, prompt_id: str, - metadata: 'PromptMetadata', file: BinaryIO, - **kwargs) -> DetailedResponse: + def add_custom_prompt( + self, + customization_id: str, + prompt_id: str, + metadata: 'PromptMetadata', + file: BinaryIO, + **kwargs, + ) -> DetailedResponse: """ Add a custom prompt. @@ -1110,18 +1309,20 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompt` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') if metadata is None: raise ValueError('metadata must be provided') if file is None: raise ValueError('file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_custom_prompt', + ) headers.update(sdk_headers) form_data = [] @@ -1131,6 +1332,7 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'prompt_id'] @@ -1138,16 +1340,22 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_custom_prompt(self, customization_id: str, prompt_id: str, - **kwargs) -> DetailedResponse: + def get_custom_prompt( + self, + customization_id: str, + prompt_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom prompt. @@ -1168,18 +1376,21 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompt` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_prompt', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'prompt_id'] @@ -1187,13 +1398,21 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_custom_prompt(self, customization_id: str, prompt_id: str, - **kwargs) -> DetailedResponse: + def delete_custom_prompt( + self, + customization_id: str, + prompt_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom prompt. @@ -1217,27 +1436,32 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_prompt', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'prompt_id'] path_param_values = self.encode_path_vars(customization_id, prompt_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1246,7 +1470,10 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, # Speaker models ######################### - def list_speaker_models(self, **kwargs) -> DetailedResponse: + def list_speaker_models( + self, + **kwargs, + ) -> DetailedResponse: """ List speaker models. @@ -1264,23 +1491,34 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_speaker_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_speaker_models', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/speakers' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def create_speaker_model(self, speaker_name: str, audio: BinaryIO, - **kwargs) -> DetailedResponse: + def create_speaker_model( + self, + speaker_name: str, + audio: BinaryIO, + **kwargs, + ) -> DetailedResponse: """ Create a speaker model. @@ -1345,36 +1583,47 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, :rtype: DetailedResponse with `dict` result representing a `SpeakerModel` object """ - if speaker_name is None: + if not speaker_name: raise ValueError('speaker_name must be provided') if audio is None: raise ValueError('audio must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_speaker_model', + ) headers.update(sdk_headers) - params = {'speaker_name': speaker_name} + params = { + 'speaker_name': speaker_name, + } data = audio headers['content-type'] = 'audio/wav' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/speakers' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: + def get_speaker_model( + self, + speaker_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a speaker model. @@ -1397,29 +1646,39 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `SpeakerCustomModels` object """ - if speaker_id is None: + if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_speaker_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['speaker_id'] path_param_values = self.encode_path_vars(speaker_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_speaker_model(self, speaker_id: str, - **kwargs) -> DetailedResponse: + def delete_speaker_model( + self, + speaker_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a speaker model. @@ -1444,24 +1703,29 @@ def delete_speaker_model(self, speaker_id: str, :rtype: DetailedResponse """ - if speaker_id is None: + if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_speaker_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['speaker_id'] path_param_values = self.encode_path_vars(speaker_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1470,7 +1734,11 @@ def delete_speaker_model(self, speaker_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -1495,24 +1763,31 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) - params = {'customer_id': customer_id} + params = { + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1527,61 +1802,51 @@ class Voice(str, Enum): """ The voice for which information is to be returned. """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' + EN_CA_HANNAHNATURAL = 'en-CA_HannahNatural' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_CHLOENATURAL = 'en-GB_ChloeNatural' + EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' + EN_GB_GEORGENATURAL = 'en-GB_GeorgeNatural' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' + EN_US_EMMANATURAL = 'en-US_EmmaNatural' + EN_US_ETHANNATURAL = 'en-US_EthanNatural' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_JACKSONNATURAL = 'en-US_JacksonNatural' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' + EN_US_VICTORIANATURAL = 'en-US_VictoriaNatural' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' + ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' + PT_BR_CAMILANATURAL = 'pt-BR_CamilaNatural' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' + PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' + PT_BR_LUCASNATURAL = 'pt-BR_LucasNatural' class SynthesizeEnums: @@ -1596,6 +1861,8 @@ class Accept(str, Enum): specifying an audio format, see **Audio formats (accept types)** in the method description. """ + + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' AUDIO_L16 = 'audio/l16' @@ -1612,74 +1879,85 @@ class Accept(str, Enum): class Voice(str, Enum): """ - The voice to use for synthesis. If you omit the `voice` parameter, the service - uses a default voice, which depends on the version of the service that you are - using: - * _For IBM Cloud,_ the service always uses the US English `en-US_MichaelV3Voice` - by default. - * _For IBM Cloud Pak for Data,_ the default voice depends on the voices that you - installed. If you installed the _enhanced neural voices_, the service uses the US - English `en-US_MichaelV3Voice` by default; if that voice is not installed, you - must specify a voice. If you installed the _neural voices_, the service always - uses the Australian English `en-AU_MadisonVoice` by default. - **See also:** See also [Using languages and - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). - """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' + The voice to use for speech synthesis. If you omit the `voice` parameter, the + service uses the US English `en-US_MichaelV3Voice` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, + you must either specify a voice with the request or specify a new default voice + for your installation of the service. + **See also:** + * [Languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) + * [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). + """ + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' + EN_CA_HANNAHNATURAL = 'en-CA_HannahNatural' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_CHLOENATURAL = 'en-GB_ChloeNatural' + EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' + EN_GB_GEORGENATURAL = 'en-GB_GeorgeNatural' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' + EN_US_EMMANATURAL = 'en-US_EmmaNatural' + EN_US_ETHANNATURAL = 'en-US_EthanNatural' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_JACKSONNATURAL = 'en-US_JacksonNatural' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' + EN_US_VICTORIANATURAL = 'en-US_VictoriaNatural' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' + ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' + PT_BR_CAMILANATURAL = 'pt-BR_CamilaNatural' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' + PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' + PT_BR_LUCASNATURAL = 'pt-BR_LucasNatural' + + class SpellOutMode(str, Enum): + """ + *For German voices,* indicates how the service is to spell out strings of + individual letters. To indicate the pace of the spelling, specify one of the + following values: + * `default` - The service reads the characters at the rate at which it synthesizes + speech for the request. You can also omit the parameter entirely to achieve the + default behavior. + * `singles` - The service reads the characters one at a time, with a brief pause + between each character. + * `pairs` - The service reads the characters two at a time, with a brief pause + between each pair. + * `triples` - The service reads the characters three at a time, with a brief pause + between each triplet. + For more information, see [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + """ + + DEFAULT = 'default' + SINGLES = 'singles' + PAIRS = 'pairs' + TRIPLES = 'triples' class GetPronunciationEnums: @@ -1690,71 +1968,67 @@ class GetPronunciationEnums: class Voice(str, Enum): """ A voice that specifies the language in which the pronunciation is to be returned. - All voices for the same language (for example, `en-US`) return the same - translation. + If you omit the `voice` parameter, the service uses the US English + `en-US_MichaelV3Voice` by default. All voices for the same language (for example, + `en-US`) return the same translation. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, + you must either specify a voice with the request or specify a new default voice + for your installation of the service. + **See also:** [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' + EN_CA_HANNAHNATURAL = 'en-CA_HannahNatural' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_CHLOENATURAL = 'en-GB_ChloeNatural' + EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' + EN_GB_GEORGENATURAL = 'en-GB_GeorgeNatural' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' + EN_US_EMMANATURAL = 'en-US_EmmaNatural' + EN_US_ETHANNATURAL = 'en-US_EthanNatural' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_JACKSONNATURAL = 'en-US_JacksonNatural' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' + EN_US_VICTORIANATURAL = 'en-US_VictoriaNatural' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' + ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' + PT_BR_CAMILANATURAL = 'pt-BR_CamilaNatural' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' + PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' + PT_BR_LUCASNATURAL = 'pt-BR_LucasNatural' class Format(str, Enum): """ - The phoneme format in which to return the pronunciation. The Arabic, Chinese, - Dutch, Australian English, and Korean languages support only IPA. Omit the - parameter to obtain the pronunciation in the default format. + The phoneme format in which to return the pronunciation. Omit the parameter to + obtain the pronunciation in the default format. """ + IBM = 'ibm' IPA = 'ipa' @@ -1770,8 +2044,7 @@ class Language(str, Enum): are to be returned. Omit the parameter to see all custom models that are owned by the requester. """ - AR_MS = 'ar-MS' - CS_CZ = 'cs-CZ' + DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' @@ -1783,12 +2056,8 @@ class Language(str, Enum): FR_FR = 'fr-FR' IT_IT = 'it-IT' JA_JP = 'ja-JP' - KO_KR = 'ko-KR' - NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' - SV_SE = 'sv-SE' - ZH_CN = 'zh-CN' ############################################################################## @@ -1796,49 +2065,51 @@ class Language(str, Enum): ############################################################################## -class CustomModel(): +class CustomModel: """ Information about an existing custom model. - :attr str customization_id: The customization ID (GUID) of the custom model. The - [Create a custom model](#createcustommodel) method returns only this field. It - does not not return the other fields of this object. - :attr str name: (optional) The name of the custom model. - :attr str language: (optional) The language identifier of the custom model (for + :param str customization_id: The customization ID (GUID) of the custom model. + The [Create a custom model](#createcustommodel) method returns only this field. + It does not not return the other fields of this object. + :param str name: (optional) The name of the custom model. + :param str language: (optional) The language identifier of the custom model (for example, `en-US`). - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom model. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str last_modified: (optional) The date and time in Coordinated Universal + :param str last_modified: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom model was last modified. The `created` and `updated` fields are equal when a model is first added but has yet to be updated. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str description: (optional) The description of the custom model. - :attr List[Word] words: (optional) An array of `Word` objects that lists the + :param str description: (optional) The description of the custom model. + :param List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if no words are defined for the custom model. This field is returned only by the [Get a custom model](#getcustommodel) method. - :attr List[Prompt] prompts: (optional) An array of `Prompt` objects that + :param List[Prompt] prompts: (optional) An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. This field is returned only by the [Get a custom model](#getcustommodel) method. """ - def __init__(self, - customization_id: str, - *, - name: str = None, - language: str = None, - owner: str = None, - created: str = None, - last_modified: str = None, - description: str = None, - words: List['Word'] = None, - prompts: List['Prompt'] = None) -> None: + def __init__( + self, + customization_id: str, + *, + name: Optional[str] = None, + language: Optional[str] = None, + owner: Optional[str] = None, + created: Optional[str] = None, + last_modified: Optional[str] = None, + description: Optional[str] = None, + words: Optional[List['Word']] = None, + prompts: Optional[List['Prompt']] = None, + ) -> None: """ Initialize a CustomModel object. @@ -1885,30 +2156,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomModel': """Initialize a CustomModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in CustomModel JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'last_modified' in _dict: - args['last_modified'] = _dict.get('last_modified') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] - if 'prompts' in _dict: - args['prompts'] = [ - Prompt.from_dict(x) for x in _dict.get('prompts') - ] + if (name := _dict.get('name')) is not None: + args['name'] = name + if (language := _dict.get('language')) is not None: + args['language'] = language + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (created := _dict.get('created')) is not None: + args['created'] = created + if (last_modified := _dict.get('last_modified')) is not None: + args['last_modified'] = last_modified + if (description := _dict.get('description')) is not None: + args['description'] = description + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [Prompt.from_dict(v) for v in prompts] return cls(**args) @classmethod @@ -1935,9 +2204,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -1959,17 +2240,20 @@ def __ne__(self, other: 'CustomModel') -> bool: return not self == other -class CustomModels(): +class CustomModels: """ Information about existing custom models. - :attr List[CustomModel] customizations: An array of `CustomModel` objects that + :param List[CustomModel] customizations: An array of `CustomModel` objects that provides information about each available custom model. The array is empty if the requesting credentials own no custom models (if no language is specified) or own no custom models for the specified language. """ - def __init__(self, customizations: List['CustomModel']) -> None: + def __init__( + self, + customizations: List['CustomModel'], + ) -> None: """ Initialize a CustomModels object. @@ -1984,9 +2268,9 @@ def __init__(self, customizations: List['CustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'CustomModels': """Initialize a CustomModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - CustomModel.from_dict(x) for x in _dict.get('customizations') + CustomModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -2003,7 +2287,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -2025,33 +2315,35 @@ def __ne__(self, other: 'CustomModels') -> bool: return not self == other -class Prompt(): +class Prompt: """ Information about a custom prompt. - :attr str prompt: The user-specified text of the prompt. - :attr str prompt_id: The user-specified identifier (name) of the prompt. - :attr str status: The status of the prompt: + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: * `processing`: The service received the request to add the prompt and is analyzing the validity of the prompt. * `available`: The service successfully validated the prompt, which is now ready for use in a speech synthesis request. * `failed`: The service's validation of the prompt failed. The status of the prompt includes an `error` field that describes the reason for the failure. - :attr str error: (optional) If the status of the prompt is `failed`, an error + :param str error: (optional) If the status of the prompt is `failed`, an error message that describes the reason for the failure. The field is omitted if no error occurred. - :attr str speaker_id: (optional) The speaker ID (GUID) of the speaker for which + :param str speaker_id: (optional) The speaker ID (GUID) of the speaker for which the prompt was defined. The field is omitted if no speaker ID was specified. """ - def __init__(self, - prompt: str, - prompt_id: str, - status: str, - *, - error: str = None, - speaker_id: str = None) -> None: + def __init__( + self, + prompt: str, + prompt_id: str, + status: str, + *, + error: Optional[str] = None, + speaker_id: Optional[str] = None, + ) -> None: """ Initialize a Prompt object. @@ -2082,25 +2374,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Prompt': """Initialize a Prompt object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt else: raise ValueError( 'Required property \'prompt\' not present in Prompt JSON') - if 'prompt_id' in _dict: - args['prompt_id'] = _dict.get('prompt_id') + if (prompt_id := _dict.get('prompt_id')) is not None: + args['prompt_id'] = prompt_id else: raise ValueError( 'Required property \'prompt_id\' not present in Prompt JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Prompt JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (error := _dict.get('error')) is not None: + args['error'] = error + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id return cls(**args) @classmethod @@ -2142,7 +2434,7 @@ def __ne__(self, other: 'Prompt') -> bool: return not self == other -class PromptMetadata(): +class PromptMetadata: """ Information about the prompt that is to be added to a custom model. The following example of a `PromptMetadata` object includes both the required prompt text and an @@ -2150,17 +2442,22 @@ class PromptMetadata(): `{ "prompt_text": "Thank you and good-bye!", "speaker_id": "823068b2-ed4e-11ea-b6e0-7b6456aa95cc" }`. - :attr str prompt_text: The required written text of the spoken prompt. The + :param str prompt_text: The required written text of the spoken prompt. The length of a prompt's text is limited to a few sentences. Speaking one or two sentences of text is the recommended limit. A prompt cannot contain more than 1000 characters of text. Escape any XML control characters (double quotes, single quotes, ampersands, angle brackets, and slashes) that appear in the text of the prompt. - :attr str speaker_id: (optional) The optional speaker ID (GUID) of a previously + :param str speaker_id: (optional) The optional speaker ID (GUID) of a previously defined speaker model that is to be associated with the prompt. """ - def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: + def __init__( + self, + prompt_text: str, + *, + speaker_id: Optional[str] = None, + ) -> None: """ Initialize a PromptMetadata object. @@ -2180,14 +2477,14 @@ def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'PromptMetadata': """Initialize a PromptMetadata object from a json dictionary.""" args = {} - if 'prompt_text' in _dict: - args['prompt_text'] = _dict.get('prompt_text') + if (prompt_text := _dict.get('prompt_text')) is not None: + args['prompt_text'] = prompt_text else: raise ValueError( 'Required property \'prompt_text\' not present in PromptMetadata JSON' ) - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id return cls(**args) @classmethod @@ -2223,16 +2520,19 @@ def __ne__(self, other: 'PromptMetadata') -> bool: return not self == other -class Prompts(): +class Prompts: """ Information about the custom prompts that are defined for a custom model. - :attr List[Prompt] prompts: An array of `Prompt` objects that provides + :param List[Prompt] prompts: An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. """ - def __init__(self, prompts: List['Prompt']) -> None: + def __init__( + self, + prompts: List['Prompt'], + ) -> None: """ Initialize a Prompts object. @@ -2246,10 +2546,8 @@ def __init__(self, prompts: List['Prompt']) -> None: def from_dict(cls, _dict: Dict) -> 'Prompts': """Initialize a Prompts object from a json dictionary.""" args = {} - if 'prompts' in _dict: - args['prompts'] = [ - Prompt.from_dict(x) for x in _dict.get('prompts') - ] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [Prompt.from_dict(v) for v in prompts] else: raise ValueError( 'Required property \'prompts\' not present in Prompts JSON') @@ -2264,7 +2562,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2286,16 +2590,19 @@ def __ne__(self, other: 'Prompts') -> bool: return not self == other -class Pronunciation(): +class Pronunciation: """ The pronunciation of the specified text. - :attr str pronunciation: The pronunciation of the specified text in the + :param str pronunciation: The pronunciation of the specified text in the requested voice and format. If a custom model is specified, the pronunciation also reflects that custom model. """ - def __init__(self, pronunciation: str) -> None: + def __init__( + self, + pronunciation: str, + ) -> None: """ Initialize a Pronunciation object. @@ -2309,8 +2616,8 @@ def __init__(self, pronunciation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Pronunciation': """Initialize a Pronunciation object from a json dictionary.""" args = {} - if 'pronunciation' in _dict: - args['pronunciation'] = _dict.get('pronunciation') + if (pronunciation := _dict.get('pronunciation')) is not None: + args['pronunciation'] = pronunciation else: raise ValueError( 'Required property \'pronunciation\' not present in Pronunciation JSON' @@ -2348,15 +2655,19 @@ def __ne__(self, other: 'Pronunciation') -> bool: return not self == other -class Speaker(): +class Speaker: """ Information about a speaker model. - :attr str speaker_id: The speaker ID (GUID) of the speaker. - :attr str name: The user-defined name of the speaker. + :param str speaker_id: The speaker ID (GUID) of the speaker. + :param str name: The user-defined name of the speaker. """ - def __init__(self, speaker_id: str, name: str) -> None: + def __init__( + self, + speaker_id: str, + name: str, + ) -> None: """ Initialize a Speaker object. @@ -2370,13 +2681,13 @@ def __init__(self, speaker_id: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'Speaker': """Initialize a Speaker object from a json dictionary.""" args = {} - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id else: raise ValueError( 'Required property \'speaker_id\' not present in Speaker JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Speaker JSON') @@ -2415,19 +2726,22 @@ def __ne__(self, other: 'Speaker') -> bool: return not self == other -class SpeakerCustomModel(): +class SpeakerCustomModel: """ A custom models for which the speaker has defined prompts. - :attr str customization_id: The customization ID (GUID) of a custom model for + :param str customization_id: The customization ID (GUID) of a custom model for which the speaker has defined one or more prompts. - :attr List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that + :param List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that provides information about each prompt that the user has defined for the custom model. """ - def __init__(self, customization_id: str, - prompts: List['SpeakerPrompt']) -> None: + def __init__( + self, + customization_id: str, + prompts: List['SpeakerPrompt'], + ) -> None: """ Initialize a SpeakerCustomModel object. @@ -2444,16 +2758,14 @@ def __init__(self, customization_id: str, def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModel': """Initialize a SpeakerCustomModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in SpeakerCustomModel JSON' ) - if 'prompts' in _dict: - args['prompts'] = [ - SpeakerPrompt.from_dict(x) for x in _dict.get('prompts') - ] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [SpeakerPrompt.from_dict(v) for v in prompts] else: raise ValueError( 'Required property \'prompts\' not present in SpeakerCustomModel JSON' @@ -2472,7 +2784,13 @@ def to_dict(self) -> Dict: 'customization_id') and self.customization_id is not None: _dict['customization_id'] = self.customization_id if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2494,17 +2812,20 @@ def __ne__(self, other: 'SpeakerCustomModel') -> bool: return not self == other -class SpeakerCustomModels(): +class SpeakerCustomModels: """ Custom models for which the speaker has defined prompts. - :attr List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` + :param List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` objects. Each object provides information about the prompts that are defined for a specified speaker in the custom models that are owned by a specified service instance. The array is empty if no prompts are defined for the speaker. """ - def __init__(self, customizations: List['SpeakerCustomModel']) -> None: + def __init__( + self, + customizations: List['SpeakerCustomModel'], + ) -> None: """ Initialize a SpeakerCustomModels object. @@ -2520,10 +2841,9 @@ def __init__(self, customizations: List['SpeakerCustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModels': """Initialize a SpeakerCustomModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - SpeakerCustomModel.from_dict(x) - for x in _dict.get('customizations') + SpeakerCustomModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -2540,7 +2860,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -2562,14 +2888,17 @@ def __ne__(self, other: 'SpeakerCustomModels') -> bool: return not self == other -class SpeakerModel(): +class SpeakerModel: """ The speaker ID of the speaker model. - :attr str speaker_id: The speaker ID (GUID) of the speaker model. + :param str speaker_id: The speaker ID (GUID) of the speaker model. """ - def __init__(self, speaker_id: str) -> None: + def __init__( + self, + speaker_id: str, + ) -> None: """ Initialize a SpeakerModel object. @@ -2581,8 +2910,8 @@ def __init__(self, speaker_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'SpeakerModel': """Initialize a SpeakerModel object from a json dictionary.""" args = {} - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id else: raise ValueError( 'Required property \'speaker_id\' not present in SpeakerModel JSON' @@ -2620,30 +2949,32 @@ def __ne__(self, other: 'SpeakerModel') -> bool: return not self == other -class SpeakerPrompt(): +class SpeakerPrompt: """ A prompt that a speaker has defined for a custom model. - :attr str prompt: The user-specified text of the prompt. - :attr str prompt_id: The user-specified identifier (name) of the prompt. - :attr str status: The status of the prompt: + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: * `processing`: The service received the request to add the prompt and is analyzing the validity of the prompt. * `available`: The service successfully validated the prompt, which is now ready for use in a speech synthesis request. * `failed`: The service's validation of the prompt failed. The status of the prompt includes an `error` field that describes the reason for the failure. - :attr str error: (optional) If the status of the prompt is `failed`, an error + :param str error: (optional) If the status of the prompt is `failed`, an error message that describes the reason for the failure. The field is omitted if no error occurred. """ - def __init__(self, - prompt: str, - prompt_id: str, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + prompt: str, + prompt_id: str, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a SpeakerPrompt object. @@ -2670,26 +3001,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeakerPrompt': """Initialize a SpeakerPrompt object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt else: raise ValueError( 'Required property \'prompt\' not present in SpeakerPrompt JSON' ) - if 'prompt_id' in _dict: - args['prompt_id'] = _dict.get('prompt_id') + if (prompt_id := _dict.get('prompt_id')) is not None: + args['prompt_id'] = prompt_id else: raise ValueError( 'Required property \'prompt_id\' not present in SpeakerPrompt JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in SpeakerPrompt JSON' ) - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -2729,16 +3060,19 @@ def __ne__(self, other: 'SpeakerPrompt') -> bool: return not self == other -class Speakers(): +class Speakers: """ Information about all speaker models for the service instance. - :attr List[Speaker] speakers: An array of `Speaker` objects that provides + :param List[Speaker] speakers: An array of `Speaker` objects that provides information about the speakers for the service instance. The array is empty if the service instance has no speakers. """ - def __init__(self, speakers: List['Speaker']) -> None: + def __init__( + self, + speakers: List['Speaker'], + ) -> None: """ Initialize a Speakers object. @@ -2752,10 +3086,8 @@ def __init__(self, speakers: List['Speaker']) -> None: def from_dict(cls, _dict: Dict) -> 'Speakers': """Initialize a Speakers object from a json dictionary.""" args = {} - if 'speakers' in _dict: - args['speakers'] = [ - Speaker.from_dict(x) for x in _dict.get('speakers') - ] + if (speakers := _dict.get('speakers')) is not None: + args['speakers'] = [Speaker.from_dict(v) for v in speakers] else: raise ValueError( 'Required property \'speakers\' not present in Speakers JSON') @@ -2770,7 +3102,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'speakers') and self.speakers is not None: - _dict['speakers'] = [x.to_dict() for x in self.speakers] + speakers_list = [] + for v in self.speakers: + if isinstance(v, dict): + speakers_list.append(v) + else: + speakers_list.append(v.to_dict()) + _dict['speakers'] = speakers_list return _dict def _to_dict(self): @@ -2792,30 +3130,32 @@ def __ne__(self, other: 'Speakers') -> bool: return not self == other -class SupportedFeatures(): +class SupportedFeatures: """ Additional service features that are supported with the voice. - :attr bool custom_pronunciation: If `true`, the voice can be customized; if + :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). - :attr bool voice_transformation: If `true`, the voice can be transformed by - using the SSML <voice-transformation> element; if `false`, the voice - cannot be transformed. The feature was available only for the now-deprecated - standard voices. You cannot use the feature with neural voices. + :param bool voice_transformation: If `true`, the voice can be transformed by + using the SSML `` element; if `false`, the voice cannot be + transformed. **Note:** The SSML `` element is obsolete. + You can no longer use the element with any supported voice. """ - def __init__(self, custom_pronunciation: bool, - voice_transformation: bool) -> None: + def __init__( + self, + custom_pronunciation: bool, + voice_transformation: bool, + ) -> None: """ Initialize a SupportedFeatures object. :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). :param bool voice_transformation: If `true`, the voice can be transformed - by using the SSML <voice-transformation> element; if `false`, the - voice cannot be transformed. The feature was available only for the - now-deprecated standard voices. You cannot use the feature with neural - voices. + by using the SSML `` element; if `false`, the voice + cannot be transformed. **Note:** The SSML `` element + is obsolete. You can no longer use the element with any supported voice. """ self.custom_pronunciation = custom_pronunciation self.voice_transformation = voice_transformation @@ -2824,14 +3164,16 @@ def __init__(self, custom_pronunciation: bool, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - if 'custom_pronunciation' in _dict: - args['custom_pronunciation'] = _dict.get('custom_pronunciation') + if (custom_pronunciation := + _dict.get('custom_pronunciation')) is not None: + args['custom_pronunciation'] = custom_pronunciation else: raise ValueError( 'Required property \'custom_pronunciation\' not present in SupportedFeatures JSON' ) - if 'voice_transformation' in _dict: - args['voice_transformation'] = _dict.get('voice_transformation') + if (voice_transformation := + _dict.get('voice_transformation')) is not None: + args['voice_transformation'] = voice_transformation else: raise ValueError( 'Required property \'voice_transformation\' not present in SupportedFeatures JSON' @@ -2873,17 +3215,15 @@ def __ne__(self, other: 'SupportedFeatures') -> bool: return not self == other -class Translation(): +class Translation: """ Information about the translation for the specified text. - :attr str translation: The phonetic or sounds-like translation for the word. A + :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA translation or as an IBM SPR translation. The - Arabic, Chinese, Dutch, Australian English, and Korean languages support only - IPA. A sounds-like is one or more words that, when combined, sound like the - word. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + string of a word either as an IPA translation or as an IBM SPR translation. A + sounds-like is one or more words that, when combined, sound like the word. + :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of @@ -2891,16 +3231,20 @@ class Translation(): entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, translation: str, *, part_of_speech: str = None) -> None: + def __init__( + self, + translation: str, + *, + part_of_speech: Optional[str] = None, + ) -> None: """ Initialize a Translation object. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. A sounds-like is one or more words that, when - combined, sound like the word. + translation. A sounds-like is one or more words that, when combined, sound + like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -2916,14 +3260,14 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' ) - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -2967,6 +3311,7 @@ class PartOfSpeechEnum(str, Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ + DOSI = 'Dosi' FUKU = 'Fuku' GOBI = 'Gobi' @@ -2986,37 +3331,40 @@ class PartOfSpeechEnum(str, Enum): SUJI = 'Suji' -class Voice(): +class Voice: """ Information about an available voice. - :attr str url: The URI of the voice. - :attr str gender: The gender of the voice: `male` or `female`. - :attr str name: The name of the voice. Use this as the voice identifier in all + :param str url: The URI of the voice. + :param str gender: The gender of the voice: `male` or `female`. + :param str name: The name of the voice. Use this as the voice identifier in all requests. - :attr str language: The language and region of the voice (for example, `en-US`). - :attr str description: A textual description of the voice. - :attr bool customizable: If `true`, the voice can be customized; if `false`, the - voice cannot be customized. (Same as `custom_pronunciation`; maintained for + :param str language: The language and region of the voice (for example, + `en-US`). + :param str description: A textual description of the voice. + :param bool customizable: If `true`, the voice can be customized; if `false`, + the voice cannot be customized. (Same as `custom_pronunciation`; maintained for backward compatibility.). - :attr SupportedFeatures supported_features: Additional service features that are - supported with the voice. - :attr CustomModel customization: (optional) Returns information about a + :param SupportedFeatures supported_features: Additional service features that + are supported with the voice. + :param CustomModel customization: (optional) Returns information about a specified custom model. This field is returned only by the [Get a voice](#getvoice) method and only when you specify the customization ID of a custom model. """ - def __init__(self, - url: str, - gender: str, - name: str, - language: str, - description: str, - customizable: bool, - supported_features: 'SupportedFeatures', - *, - customization: 'CustomModel' = None) -> None: + def __init__( + self, + url: str, + gender: str, + name: str, + language: str, + description: str, + customizable: bool, + supported_features: 'SupportedFeatures', + *, + customization: Optional['CustomModel'] = None, + ) -> None: """ Initialize a Voice object. @@ -3050,46 +3398,45 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Voice': """Initialize a Voice object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in Voice JSON') - if 'gender' in _dict: - args['gender'] = _dict.get('gender') + if (gender := _dict.get('gender')) is not None: + args['gender'] = gender else: raise ValueError( 'Required property \'gender\' not present in Voice JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Voice JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Voice JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (description := _dict.get('description')) is not None: + args['description'] = description else: raise ValueError( 'Required property \'description\' not present in Voice JSON') - if 'customizable' in _dict: - args['customizable'] = _dict.get('customizable') + if (customizable := _dict.get('customizable')) is not None: + args['customizable'] = customizable else: raise ValueError( 'Required property \'customizable\' not present in Voice JSON') - if 'supported_features' in _dict: + if (supported_features := _dict.get('supported_features')) is not None: args['supported_features'] = SupportedFeatures.from_dict( - _dict.get('supported_features')) + supported_features) else: raise ValueError( 'Required property \'supported_features\' not present in Voice JSON' ) - if 'customization' in _dict: - args['customization'] = CustomModel.from_dict( - _dict.get('customization')) + if (customization := _dict.get('customization')) is not None: + args['customization'] = CustomModel.from_dict(customization) return cls(**args) @classmethod @@ -3115,9 +3462,15 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features.to_dict() + if isinstance(self.supported_features, dict): + _dict['supported_features'] = self.supported_features + else: + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'customization') and self.customization is not None: - _dict['customization'] = self.customization.to_dict() + if isinstance(self.customization, dict): + _dict['customization'] = self.customization + else: + _dict['customization'] = self.customization.to_dict() return _dict def _to_dict(self): @@ -3139,14 +3492,17 @@ def __ne__(self, other: 'Voice') -> bool: return not self == other -class Voices(): +class Voices: """ Information about all available voices. - :attr List[Voice] voices: A list of available voices. + :param List[Voice] voices: A list of available voices. """ - def __init__(self, voices: List['Voice']) -> None: + def __init__( + self, + voices: List['Voice'], + ) -> None: """ Initialize a Voices object. @@ -3158,8 +3514,8 @@ def __init__(self, voices: List['Voice']) -> None: def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} - if 'voices' in _dict: - args['voices'] = [Voice.from_dict(x) for x in _dict.get('voices')] + if (voices := _dict.get('voices')) is not None: + args['voices'] = [Voice.from_dict(v) for v in voices] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') @@ -3174,7 +3530,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'voices') and self.voices is not None: - _dict['voices'] = [x.to_dict() for x in self.voices] + voices_list = [] + for v in self.voices: + if isinstance(v, dict): + voices_list.append(v) + else: + voices_list.append(v.to_dict()) + _dict['voices'] = voices_list return _dict def _to_dict(self): @@ -3196,19 +3558,18 @@ def __ne__(self, other: 'Voices') -> bool: return not self == other -class Word(): +class Word: """ Information about a word for the custom model. - :attr str word: The word for the custom model. The maximum length of a word is + :param str word: The word for the custom model. The maximum length of a word is 49 characters. - :attr str translation: The phonetic or sounds-like translation for the word. A + :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, - Dutch, Australian English, and Korean languages support only IPA. A sounds-like + string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. The maximum length of a translation is 499 characters. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of @@ -3216,11 +3577,13 @@ class Word(): entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, - word: str, - translation: str, - *, - part_of_speech: str = None) -> None: + def __init__( + self, + word: str, + translation: str, + *, + part_of_speech: Optional[str] = None, + ) -> None: """ Initialize a Word object. @@ -3228,11 +3591,9 @@ def __init__(self, word is 49 characters. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing - the phonetic string of a word either as an IPA or IBM SPR translation. The - Arabic, Chinese, Dutch, Australian English, and Korean languages support - only IPA. A sounds-like translation consists of one or more words that, - when combined, sound like the word. The maximum length of a translation is - 499 characters. + the phonetic string of a word either as an IPA or IBM SPR translation. A + sounds-like translation consists of one or more words that, when combined, + sound like the word. The maximum length of a translation is 499 characters. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -3249,18 +3610,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in Word JSON') - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Word JSON') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -3306,6 +3667,7 @@ class PartOfSpeechEnum(str, Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ + DOSI = 'Dosi' FUKU = 'Fuku' GOBI = 'Gobi' @@ -3325,14 +3687,14 @@ class PartOfSpeechEnum(str, Enum): SUJI = 'Suji' -class Words(): +class Words: """ For the [Add custom words](#addwords) method, one or more words that are to be added or updated for the custom model and the translation for each specified word. For the [List custom words](#listwords) method, the words and their translations from the custom model. - :attr List[Word] words: The [Add custom words](#addwords) method accepts an + :param List[Word] words: The [Add custom words](#addwords) method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom model and the word's translation. The [List custom words](#listwords) method returns an array of `Word` objects. @@ -3341,7 +3703,10 @@ class Words(): letters. The array is empty if the custom model contains no words. """ - def __init__(self, words: List['Word']) -> None: + def __init__( + self, + words: List['Word'], + ) -> None: """ Initialize a Words object. @@ -3360,8 +3725,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -3376,7 +3741,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list return _dict def _to_dict(self): diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 1d4672ff0..00eae9620 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.3.0' +__version__ = '11.2.0' diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index c0d988c58..43eb79618 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -227,7 +227,7 @@ def on_error(self, ws, error): """ self.callback.on_error(error) - def on_close(self, ws): + def on_close(self, ws, *args): """ Callback executed when websocket connection is closed diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index dee6e28a6..33caf81d5 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -120,7 +120,7 @@ def on_error(self, ws, error): """ self.callback.on_error(error) - def on_close(self, ws, **kwargs): + def on_close(self, ws, *args, **kwargs): """ Callback executed when websocket connection is closed diff --git a/pyproject.toml b/pyproject.toml index 07de284aa..09eb447dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,20 @@ [build-system] requires = ["setuptools", "wheel"] -build-backend = "setuptools.build_meta" \ No newline at end of file +build-backend = "setuptools.build_meta" + +[tool.semantic_release] +version_variables = [ + "setup.py:__version__", + "ibm_watson/version.py:__version__", +] +version_toml = [] +branch = "master" + +[tool.semantic_release.changelog] +exclude_commit_patterns = [ + '''chore(?:\([^)]*?\))?: .+''', + '''ci(?:\([^)]*?\))?: .+''', + '''refactor(?:\([^)]*?\))?: .+''', + '''test(?:\([^)]*?\))?: .+''', + '''build\((?!deps\): .+)''', +] \ No newline at end of file diff --git a/requirements-dev.txt b/requirements-dev.txt index 086cfe4e8..f04883ea7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,4 +17,4 @@ Sphinx==3.5.2 bumpversion==0.6.0 # Web sockets -websocket-client==1.1.0 +websocket-client>=1.1.0 diff --git a/requirements.txt b/requirements.txt index 7df31b85a..461b8746a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 -websocket-client==1.1.0 +websocket-client>=1.1.0 ibm_cloud_sdk_core>=3.3.6, == 3.* diff --git a/setup.py b/setup.py index 09a62b2a8..6947cb83d 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2015, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.3.0' +__version__ = '11.2.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) @@ -27,7 +27,7 @@ version=__version__, description='Client library to use the IBM Watson Services', packages=['ibm_watson'], - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==1.1.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client>=1.1.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures'], license='Apache 2.0', author='IBM Watson', @@ -36,13 +36,13 @@ long_description_content_type='text/markdown', url='https://github.com/watson-developer-cloud/python-sdk', include_package_data=True, - keywords='language, vision, question and answer' + - ' tone_analyzer, natural language classifier,' + - ' text to speech, language translation, ' + + keywords='language, question and answer,' + + ' tone_analyzer,' + + ' text to speech,' + 'language identification, concept expansion, machine translation, ' + - 'personality insights, message resonance, watson developer cloud, ' + + 'message resonance, watson developer cloud, ' + ' wdc, watson, ibm, dialog, user modeling,' + - 'tone analyzer, speech to text, visual recognition', + 'speech to text', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', diff --git a/test/integration/test_assistant_v2.py b/test/integration/test_assistant_v2.py new file mode 100644 index 000000000..db17bcae0 --- /dev/null +++ b/test/integration/test_assistant_v2.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +# Copyright 2019, 2024 IBM All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase +import ibm_watson +from ibm_watson.assistant_v2 import MessageInput +from ibm_watson.common import parse_sse_stream_data +import pytest +import json +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +class TestAssistantV2(TestCase): + + def setUp(self): + + with open('./auth.json') as f: + data = json.load(f) + assistant_auth = data.get("assistantv2") + self.assistant_id = assistant_auth.get("assistantId") + self.environment_id = assistant_auth.get("environmentId") + + self.authenticator = IAMAuthenticator(apikey=assistant_auth.get("apikey")) + self.assistant = ibm_watson.AssistantV2(version='2024-08-25', authenticator=self.authenticator) + self.assistant.set_service_url(assistant_auth.get("serviceUrl")) + self.assistant.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + def test_list_assistants(self): + response = self.assistant.list_assistants().get_result() + assert response is not None + + def test_message_stream_stateless(self): + input = MessageInput(message_type="text", text="can you list the steps to create a custom extension?") + user_id = "Angelo" + + response = self.assistant.message_stream_stateless(self.assistant_id, self.environment_id, input=input, user_id=user_id).get_result() + + for data in parse_sse_stream_data(response): + # One of these items must exist + # assert "partial_item" in data_json or "complete_item" in data_json or "final_item" in data_json + + if "partial_item" in data: + assert data["partial_item"]["text"] is not None + elif "complete_item" in data: + assert data["complete_item"]["text"] is not None + elif "final_response" in data: + assert data["final_response"] is not None + else: + pytest.fail("Should be impossible to get here") + diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py deleted file mode 100644 index 6809fefe6..000000000 --- a/test/integration/test_discovery_v1.py +++ /dev/null @@ -1,292 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -import os -import ibm_watson -import random -import pytest - - -@pytest.mark.skipif(os.getenv('DISCOVERY_APIKEY') is None, - reason='requires DISCOVERY_APIKEY') -class Discoveryv1(TestCase): - discovery = None - environment_id = os.getenv('DISCOVERY_ENVIRONMENT_ID') # This environment is created for integration testing - collection_id = None - collection_name = 'FOR-PYTHON-DELETE-ME' - - @classmethod - def setup_class(cls): - cls.discovery = ibm_watson.DiscoveryV1(version='2018-08-01') - cls.discovery.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) - - collections = cls.discovery.list_collections( - cls.environment_id).get_result()['collections'] - for collection in collections: - if collection['name'] == cls.collection_name: - cls.collection_id = collection['collection_id'] - - if cls.collection_id is None: - print("Creating a new temporary collection") - cls.collection_id = cls.discovery.create_collection( - cls.environment_id, - cls.collection_name, - description="Integration test for python sdk").get_result( - )['collection_id'] - - @classmethod - def teardown_class(cls): - collections = cls.discovery.list_collections( - cls.environment_id).get_result()['collections'] - for collection in collections: - if collection['name'] == cls.collection_name: - print('Deleting the temporary collection') - cls.discovery.delete_collection(cls.environment_id, - cls.collection_id) - break - - def test_environments(self): - envs = self.discovery.list_environments().get_result() - assert envs is not None - env = self.discovery.get_environment( - envs['environments'][0]['environment_id']).get_result() - assert env is not None - fields = self.discovery.list_fields(self.environment_id, - self.collection_id).get_result() - assert fields is not None - - def test_configurations(self): - configs = self.discovery.list_configurations( - self.environment_id).get_result() - assert configs is not None - - name = 'test' + random.choice('ABCDEFGHIJKLMNOPQ') - new_configuration_id = self.discovery.create_configuration( - self.environment_id, - name, - description='creating new config for python sdk').get_result( - )['configuration_id'] - assert new_configuration_id is not None - self.discovery.get_configuration(self.environment_id, - new_configuration_id).get_result() - - updated_config = self.discovery.update_configuration( - self.environment_id, new_configuration_id, 'lala').get_result() - assert updated_config['name'] == 'lala' - - deleted_config = self.discovery.delete_configuration( - self.environment_id, new_configuration_id).get_result() - assert deleted_config['status'] == 'deleted' - - def test_collections_and_expansions(self): - self.discovery.get_collection(self.environment_id, self.collection_id) - updated_collection = self.discovery.update_collection( - self.environment_id, - self.collection_id, - self.collection_name, - description='Updating description').get_result() - assert updated_collection['description'] == 'Updating description' - - self.discovery.create_expansions(self.environment_id, - self.collection_id, [{ - 'input_terms': ['a'], - 'expanded_terms': ['aa'] - }]).get_result() - expansions = self.discovery.list_expansions( - self.environment_id, self.collection_id).get_result() - assert expansions['expansions'] - self.discovery.delete_expansions(self.environment_id, - self.collection_id) - - def test_documents(self): - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/simple.html'), 'r') as fileinfo: - add_doc = self.discovery.add_document( - environment_id=self.environment_id, - collection_id=self.collection_id, - file=fileinfo).get_result() - assert add_doc['document_id'] is not None - - doc_status = self.discovery.get_document_status( - self.environment_id, self.collection_id, - add_doc['document_id']).get_result() - assert doc_status is not None - - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/simple.html'), 'r') as fileinfo: - update_doc = self.discovery.update_document( - self.environment_id, - self.collection_id, - add_doc['document_id'], - file=fileinfo, - filename='newname.html').get_result() - assert update_doc is not None - delete_doc = self.discovery.delete_document( - self.environment_id, self.collection_id, - add_doc['document_id']).get_result() - assert delete_doc['status'] == 'deleted' - - def test_queries(self): - query_results = self.discovery.query( - self.environment_id, - self.collection_id, - filter='extracted_metadata.sha1::9181d244*').get_result() - assert query_results is not None - - @pytest.mark.skip( - reason="Temporary skipping because update_credentials fails") - def test_credentials(self): - credential_details = { - 'credential_type': 'username_password', - 'url': 'https://login.salesforce.com', - 'username': 'user@email.com', - 'password': 'xxx' - } - credentials = self.discovery.create_credentials( - self.environment_id, - source_type='salesforce', - credential_details=credential_details).get_result() - assert credentials['credential_id'] is not None - credential_id = credentials['credential_id'] - - get_credentials = self.discovery.get_credentials( - self.environment_id, credential_id).get_result() - assert get_credentials['credential_id'] == credential_id - - list_credentials = self.discovery.list_credentials( - self.environment_id).get_result() - assert list_credentials is not None - - new_credential_details = { - 'credential_type': 'username_password', - 'url': 'https://logo.salesforce.com', - 'username': 'user@email.com', - 'password': 'xxx' - } - updated_credentials = self.discovery.update_credentials( - self.environment_id, - credential_id, - source_type='salesforce', - credential_details=new_credential_details).get_result() - assert updated_credentials is not None - - get_credentials = self.discovery.get_credentials( - self.environment_id, credentials['credential_id']).get_result() - assert get_credentials['credential_details'][ - 'url'] == new_credential_details['url'] - - delete_credentials = self.discovery.delete_credentials( - self.environment_id, credential_id).get_result() - assert delete_credentials['credential_id'] is not None - - def test_create_event(self): - # create test document - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/simple.html'), 'r') as fileinfo: - add_doc = self.discovery.add_document( - environment_id=self.environment_id, - collection_id=self.collection_id, - file=fileinfo).get_result() - assert add_doc['document_id'] is not None - document_id = add_doc['document_id'] - - # make query to get session token - query = self.discovery.query( - self.environment_id, - self.collection_id, - natural_language_query='The content of the first chapter' - ).get_result() - assert query['session_token'] is not None - - # create_event - event_data = { - "environment_id": self.environment_id, - "session_token": query['session_token'], - "collection_id": self.collection_id, - "document_id": document_id, - } - create_event_response = self.discovery.create_event( - 'click', event_data).get_result() - assert create_event_response['type'] == 'click' - - #delete the documment - self.discovery.delete_document(self.environment_id, self.collection_id, - document_id).get_result() - - @pytest.mark.skip(reason="Temporary disable") - def test_tokenization_dictionary(self): - result = self.discovery.get_tokenization_dictionary_status( - self.environment_id, self.collection_id).get_result() - assert result['status'] is not None - - def test_feedback(self): - response = self.discovery.get_metrics_event_rate( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query_event( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query_no_results( - start_time='2018-07-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query_token_event( - count=10).get_result() - assert response['aggregations'] is not None - - response = self.discovery.query_log(count=2).get_result() - assert response is not None - - @pytest.mark.skip(reason="Skip temporarily.") - def test_stopword_operations(self): - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/stopwords.txt'), - 'r') as stopwords_file: - create_stopword_list_result = self.discovery.create_stopword_list( - self.environment_id, self.collection_id, - stopwords_file).get_result() - assert create_stopword_list_result is not None - - delete_stopword_list_result = self.discovery.delete_stopword_list( - self.environment_id, self.collection_id).get_result() - assert delete_stopword_list_result is None - - def test_gateway_configuration(self): - create_gateway_result = self.discovery.create_gateway( - self.environment_id, - name='test-gateway-configuration-python').get_result() - assert create_gateway_result['gateway_id'] is not None - - get_gateway_result = self.discovery.get_gateway( - self.environment_id, - create_gateway_result['gateway_id']).get_result() - assert get_gateway_result is not None - - list_gateways_result = self.discovery.list_gateways( - self.environment_id).get_result() - assert list_gateways_result is not None - - delete_gateways_result = self.discovery.delete_gateway( - self.environment_id, - create_gateway_result['gateway_id']).get_result() - assert delete_gateways_result is not None diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py deleted file mode 100644 index 1fcfd057d..000000000 --- a/test/integration/test_language_translator_v3.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding: utf-8 -import unittest -import ibm_watson -from os.path import join, dirname -import pytest -import os - - -@pytest.mark.skipif(os.getenv('LANGUAGE_TRANSLATOR_APIKEY') is None, - reason='requires LANGUAGE_TRANSLATOR_APIKEY') -class TestIntegrationLanguageTranslatorV3(unittest.TestCase): - - @classmethod - def setup_class(cls): - cls.language_translator = ibm_watson.LanguageTranslatorV3('2018-05-01') - cls.language_translator.set_default_headers({'X-Watson-Test': '1'}) - - def test_translate(self): - translation = self.language_translator.translate( - text='Hello', model_id='en-es').get_result() - assert translation is not None - translation = self.language_translator.translate( - text='Hello, how are you?', target='es').get_result() - assert translation is not None - - def test_list_languages(self): - languages = self.language_translator.list_languages() - assert languages is not None - - def test_document_translation(self): - with open(join(dirname(__file__), '../../resources/hello_world.txt'), - 'r') as fileinfo: - translation = self.language_translator.translate_document( - file=fileinfo, file_content_type='text/plain', - model_id='en-es').get_result() - document_id = translation.get('document_id') - assert document_id is not None - - document_status = self.language_translator.get_document_status( - document_id).get_result() - assert document_status is not None - - if document_status.get('status') == 'available': - response = self.language_translator.get_translated_document( - document_id, 'text/plain').get_result() - assert response.content is not None - - list_documents = self.language_translator.list_documents().get_result() - assert list_documents is not None - - delete_document = self.language_translator.delete_document( - document_id).get_result() - assert delete_document is None diff --git a/test/integration/test_natural_language_understanding_v1.py b/test/integration/test_natural_language_understanding_v1.py index faedb7593..1255b5067 100644 --- a/test/integration/test_natural_language_understanding_v1.py +++ b/test/integration/test_natural_language_understanding_v1.py @@ -6,17 +6,22 @@ import json import time from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') is None, - reason='requires NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') class TestNaturalLanguageUnderstandingV1(TestCase): def setUp(self): - self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16') - self.natural_language_understanding.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) + + with open('./auth.json') as f: + data = json.load(f) + nlu_auth = data.get("nlu") + + self.authenticator = IAMAuthenticator(nlu_auth.get("apikey")) + self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16', authenticator=self.authenticator) + self.natural_language_understanding.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) def test_analyze(self): response = self.natural_language_understanding.analyze( diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index c0e0d1865..4defbea19 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -119,20 +119,15 @@ def on_data(self, data): ['transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' def test_on_transcription_interim_results_false(self): - class MyRecognizeCallback(RecognizeCallback): - def __init__(self): RecognizeCallback.__init__(self) self.error = None self.transcript = None - def on_error(self, error): self.error = error - def on_transcription(self, transcript): self.transcript = transcript - test_callback = MyRecognizeCallback() with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: audio_source = AudioSource(audio_file, False) @@ -140,26 +135,20 @@ def on_transcription(self, transcript): interim_results=False, low_latency=False) assert test_callback.error is None assert test_callback.transcript is not None - assert test_callback.transcript[0][0]['transcript'] == 'isolated tornadoes ' + assert test_callback.transcript[0][0]['transcript'] in ['isolated tornadoes ', 'isolated tornados '] assert test_callback.transcript[1][0]['transcript'] == 'and heavy rain ' - def test_on_transcription_interim_results_true(self): - class MyRecognizeCallback(RecognizeCallback): - def __init__(self): RecognizeCallback.__init__(self) self.error = None self.transcript = None - def on_error(self, error): self.error = error - def on_transcription(self, transcript): self.transcript = transcript assert transcript[0]['confidence'] is not None assert transcript[0]['transcript'] is not None - test_callback = MyRecognizeCallback() with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: audio_source = AudioSource(audio_file, False) @@ -168,24 +157,18 @@ def on_transcription(self, transcript): assert test_callback.error is None assert test_callback.transcript is not None assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' - def test_on_transcription_interim_results_true_low_latency_false(self): - class MyRecognizeCallback(RecognizeCallback): - def __init__(self): RecognizeCallback.__init__(self) self.error = None self.transcript = None - def on_error(self, error): self.error = error - def on_transcription(self, transcript): self.transcript = transcript assert transcript[0]['confidence'] is not None assert transcript[0]['transcript'] is not None - test_callback = MyRecognizeCallback() with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: audio_source = AudioSource(audio_file, False) @@ -194,7 +177,7 @@ def on_transcription(self, transcript): assert test_callback.error is None assert test_callback.transcript is not None assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' - + def test_custom_grammars(self): customization_id = None for custom_model in self.custom_models.get('customizations'): diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index d0eee91a1..407abd68d 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -163,7 +163,7 @@ def on_close(self): 'She sells seashells by the seashore', test_callback, accept='audio/wav', - voice='en-AU_CraigVoice') + voice='en-GB_JamesV3Voice') assert test_callback.error is None assert test_callback.fd is not None assert os.stat(file).st_size > 0 diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 696a08a7b..82781955f 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ _service = AssistantV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' @@ -47,23 +47,15 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -71,7 +63,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestMessage(): + +class TestMessage: """ Test Class for message """ @@ -83,12 +76,14 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a MessageInput model message_input_model = {} @@ -164,7 +159,7 @@ def test_message_all_params(self): # Construct a dict representation of a Context model context_model = {} context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -186,28 +181,14 @@ def test_message_all_params(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - # Construct a dict representation of a DialogNodeOutputOptionsElementValue model - dialog_node_output_options_element_value_model = {} - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - # Construct a dict representation of a DialogNodeOutputOptionsElement model - dialog_node_output_options_element_model = {} - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeOption model + # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeText model runtime_response_generic_model = {} - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a OutputData model @@ -240,14 +221,14 @@ def test_message_all_params(self): output=output, user_id=user_id, nodes_visited_details=nodes_visited_details, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'nodes_visited_details={}'.format('true' if nodes_visited_details else 'false') in query_string # Validate body params @@ -276,12 +257,14 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -289,7 +272,7 @@ def test_message_required_params(self): # Invoke method response = _service.message( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -312,12 +295,14 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -327,11 +312,10 @@ def test_message_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message(**req_copy) - def test_message_value_error_with_retries(self): # Enable retries and run test_message_value_error. _service.enable_retries() @@ -341,6 +325,7 @@ def test_message_value_error_with_retries(self): _service.disable_retries() self.test_message_value_error() + # endregion ############################################################################## # End of Service: Message @@ -351,7 +336,8 @@ def test_message_value_error_with_retries(self): ############################################################################## # region -class TestBulkClassify(): + +class TestBulkClassify: """ Test Class for bulk_classify """ @@ -364,11 +350,13 @@ def test_bulk_classify_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -382,7 +370,7 @@ def test_bulk_classify_all_params(self): response = _service.bulk_classify( workspace_id, input=input, - headers={} + headers={}, ) # Check for correct operation @@ -409,11 +397,13 @@ def test_bulk_classify_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -421,7 +411,7 @@ def test_bulk_classify_required_params(self): # Invoke method response = _service.bulk_classify( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -445,11 +435,13 @@ def test_bulk_classify_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -459,11 +451,10 @@ def test_bulk_classify_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) - def test_bulk_classify_value_error_with_retries(self): # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() @@ -473,6 +464,7 @@ def test_bulk_classify_value_error_with_retries(self): _service.disable_retries() self.test_bulk_classify_value_error() + # endregion ############################################################################## # End of Service: BulkClassify @@ -483,7 +475,8 @@ def test_bulk_classify_value_error_with_retries(self): ############################################################################## # region -class TestListWorkspaces(): + +class TestListWorkspaces: """ Test Class for list_workspaces """ @@ -495,15 +488,17 @@ def test_list_workspaces_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -516,14 +511,14 @@ def test_list_workspaces_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -547,17 +542,18 @@ def test_list_workspaces_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_workspaces() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -578,22 +574,23 @@ def test_list_workspaces_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_workspaces(**req_copy) - def test_list_workspaces_value_error_with_retries(self): # Enable retries and run test_list_workspaces_value_error. _service.enable_retries() @@ -603,7 +600,8 @@ def test_list_workspaces_value_error_with_retries(self): _service.disable_retries() self.test_list_workspaces_value_error() -class TestCreateWorkspace(): + +class TestCreateWorkspace: """ Test Class for create_workspace """ @@ -615,26 +613,30 @@ def test_create_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -643,13 +645,13 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -662,7 +664,7 @@ def test_create_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -675,7 +677,7 @@ def test_create_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -714,15 +716,20 @@ def test_create_workspace_all_params(self): workspace_system_settings_off_topic_model = {} workspace_system_settings_off_topic_model['enabled'] = False + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model @@ -755,7 +762,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -764,7 +771,7 @@ def test_create_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -774,7 +781,7 @@ def test_create_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -796,14 +803,14 @@ def test_create_workspace_all_params(self): intents=intents, entities=entities, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -813,7 +820,7 @@ def test_create_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -836,17 +843,18 @@ def test_create_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Invoke method response = _service.create_workspace() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 @@ -867,22 +875,23 @@ def test_create_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_workspace(**req_copy) - def test_create_workspace_value_error_with_retries(self): # Enable retries and run test_create_workspace_value_error. _service.enable_retries() @@ -892,7 +901,8 @@ def test_create_workspace_value_error_with_retries(self): _service.disable_retries() self.test_create_workspace_value_error() -class TestGetWorkspace(): + +class TestGetWorkspace: """ Test Class for get_workspace """ @@ -904,12 +914,14 @@ def test_get_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -923,14 +935,14 @@ def test_get_workspace_all_params(self): export=export, include_audit=include_audit, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -952,12 +964,14 @@ def test_get_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -965,7 +979,7 @@ def test_get_workspace_required_params(self): # Invoke method response = _service.get_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -988,12 +1002,14 @@ def test_get_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1003,11 +1019,10 @@ def test_get_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_workspace(**req_copy) - def test_get_workspace_value_error_with_retries(self): # Enable retries and run test_get_workspace_value_error. _service.enable_retries() @@ -1017,7 +1032,8 @@ def test_get_workspace_value_error_with_retries(self): _service.disable_retries() self.test_get_workspace_value_error() -class TestUpdateWorkspace(): + +class TestUpdateWorkspace: """ Test Class for update_workspace """ @@ -1029,26 +1045,30 @@ def test_update_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1057,13 +1077,13 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1076,7 +1096,7 @@ def test_update_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1089,7 +1109,7 @@ def test_update_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1128,15 +1148,20 @@ def test_update_workspace_all_params(self): workspace_system_settings_off_topic_model = {} workspace_system_settings_off_topic_model['enabled'] = False + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model @@ -1169,7 +1194,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1178,7 +1203,7 @@ def test_update_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1189,7 +1214,7 @@ def test_update_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1214,14 +1239,14 @@ def test_update_workspace_all_params(self): entities=entities, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1232,7 +1257,7 @@ def test_update_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1255,12 +1280,14 @@ def test_update_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1268,7 +1295,7 @@ def test_update_workspace_required_params(self): # Invoke method response = _service.update_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1291,83 +1318,828 @@ def test_update_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_workspace(**req_copy) + + def test_update_workspace_value_error_with_retries(self): + # Enable retries and run test_update_workspace_value_error. + _service.enable_retries() + self.test_update_workspace_value_error() + + # Disable retries and run test_update_workspace_value_error. + _service.disable_retries() + self.test_update_workspace_value_error() + + +class TestDeleteWorkspace: + """ + Test Class for delete_workspace + """ + + @responses.activate + def test_delete_workspace_all_params(self): + """ + delete_workspace() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + responses.add( + responses.DELETE, + url, + status=200, + ) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.delete_workspace( + workspace_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_workspace_all_params_with_retries(self): + # Enable retries and run test_delete_workspace_all_params. + _service.enable_retries() + self.test_delete_workspace_all_params() + + # Disable retries and run test_delete_workspace_all_params. + _service.disable_retries() + self.test_delete_workspace_all_params() + + @responses.activate + def test_delete_workspace_value_error(self): + """ + test_delete_workspace_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "workspace_id": workspace_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_workspace(**req_copy) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_workspace(**req_copy) + + def test_delete_workspace_value_error_with_retries(self): + # Enable retries and run test_delete_workspace_value_error. + _service.enable_retries() + self.test_delete_workspace_value_error() + + # Disable retries and run test_delete_workspace_value_error. + _service.disable_retries() + self.test_delete_workspace_value_error() + + +class TestCreateWorkspaceAsync: + """ + Test Class for create_workspace_async + """ + + @responses.activate + def test_create_workspace_async_all_params(self): + """ + create_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} + dialog_node_context_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = False + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = False + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model + workspace_system_settings_model['foo'] = 'testString' + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {'anyKey': 'anyValue'} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {'anyKey': 'anyValue'} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {'anyKey': 'anyValue'} + learning_opt_out = False + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + + # Invoke method + response = _service.create_workspace_async( + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {'anyKey': 'anyValue'} + assert req_body['learning_opt_out'] == False + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + def test_create_workspace_async_all_params_with_retries(self): + # Enable retries and run test_create_workspace_async_all_params. + _service.enable_retries() + self.test_create_workspace_async_all_params() + + # Disable retries and run test_create_workspace_async_all_params. + _service.disable_retries() + self.test_create_workspace_async_all_params() + + @responses.activate + def test_create_workspace_async_required_params(self): + """ + test_create_workspace_async_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Invoke method + response = _service.create_workspace_async() + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_create_workspace_async_required_params_with_retries(self): + # Enable retries and run test_create_workspace_async_required_params. + _service.enable_retries() + self.test_create_workspace_async_required_params() + + # Disable retries and run test_create_workspace_async_required_params. + _service.disable_retries() + self.test_create_workspace_async_required_params() + + @responses.activate + def test_create_workspace_async_value_error(self): + """ + test_create_workspace_async_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_workspace_async(**req_copy) + + def test_create_workspace_async_value_error_with_retries(self): + # Enable retries and run test_create_workspace_async_value_error. + _service.enable_retries() + self.test_create_workspace_async_value_error() + + # Disable retries and run test_create_workspace_async_value_error. + _service.disable_retries() + self.test_create_workspace_async_value_error() + + +class TestUpdateWorkspaceAsync: + """ + Test Class for update_workspace_async + """ + + @responses.activate + def test_update_workspace_async_all_params(self): + """ + update_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} + dialog_node_context_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = False + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = False + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model + workspace_system_settings_model['foo'] = 'testString' + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {'anyKey': 'anyValue'} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {'anyKey': 'anyValue'} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + workspace_id = 'testString' + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {'anyKey': 'anyValue'} + learning_opt_out = False + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + append = False + + # Invoke method + response = _service.update_workspace_async( + workspace_id, + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + append=append, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {'anyKey': 'anyValue'} + assert req_body['learning_opt_out'] == False + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + def test_update_workspace_async_all_params_with_retries(self): + # Enable retries and run test_update_workspace_async_all_params. + _service.enable_retries() + self.test_update_workspace_async_all_params() + + # Disable retries and run test_update_workspace_async_all_params. + _service.disable_retries() + self.test_update_workspace_async_all_params() + + @responses.activate + def test_update_workspace_async_required_params(self): + """ + test_update_workspace_async_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.update_workspace_async( + workspace_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_update_workspace_async_required_params_with_retries(self): + # Enable retries and run test_update_workspace_async_required_params. + _service.enable_retries() + self.test_update_workspace_async_required_params() + + # Disable retries and run test_update_workspace_async_required_params. + _service.disable_retries() + self.test_update_workspace_async_required_params() + + @responses.activate + def test_update_workspace_async_value_error(self): + """ + test_update_workspace_async_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_workspace_async(**req_copy) + + def test_update_workspace_async_value_error_with_retries(self): + # Enable retries and run test_update_workspace_async_value_error. + _service.enable_retries() + self.test_update_workspace_async_value_error() + + # Disable retries and run test_update_workspace_async_value_error. + _service.disable_retries() + self.test_update_workspace_async_value_error() + + +class TestExportWorkspaceAsync: + """ + Test Class for export_workspace_async + """ + + @responses.activate + def test_export_workspace_async_all_params(self): + """ + export_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + workspace_id = 'testString' + include_audit = False + sort = 'stable' + verbose = False + + # Invoke method + response = _service.export_workspace_async( + workspace_id, + include_audit=include_audit, + sort=sort, + verbose=verbose, + headers={}, + ) + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'verbose={}'.format('true' if verbose else 'false') in query_string - def test_update_workspace_value_error_with_retries(self): - # Enable retries and run test_update_workspace_value_error. + def test_export_workspace_async_all_params_with_retries(self): + # Enable retries and run test_export_workspace_async_all_params. _service.enable_retries() - self.test_update_workspace_value_error() + self.test_export_workspace_async_all_params() - # Disable retries and run test_update_workspace_value_error. + # Disable retries and run test_export_workspace_async_all_params. _service.disable_retries() - self.test_update_workspace_value_error() - -class TestDeleteWorkspace(): - """ - Test Class for delete_workspace - """ + self.test_export_workspace_async_all_params() @responses.activate - def test_delete_workspace_all_params(self): + def test_export_workspace_async_required_params(self): """ - delete_workspace() + test_export_workspace_async_required_params() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, - url, - status=200) + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' # Invoke method - response = _service.delete_workspace( + response = _service.export_workspace_async( workspace_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - def test_delete_workspace_all_params_with_retries(self): - # Enable retries and run test_delete_workspace_all_params. + def test_export_workspace_async_required_params_with_retries(self): + # Enable retries and run test_export_workspace_async_required_params. _service.enable_retries() - self.test_delete_workspace_all_params() + self.test_export_workspace_async_required_params() - # Disable retries and run test_delete_workspace_all_params. + # Disable retries and run test_export_workspace_async_required_params. _service.disable_retries() - self.test_delete_workspace_all_params() + self.test_export_workspace_async_required_params() @responses.activate - def test_delete_workspace_value_error(self): + def test_export_workspace_async_value_error(self): """ - test_delete_workspace_value_error() + test_export_workspace_async_value_error() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, - url, - status=200) + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1377,19 +2149,19 @@ def test_delete_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_workspace(**req_copy) + _service.export_workspace_async(**req_copy) - - def test_delete_workspace_value_error_with_retries(self): - # Enable retries and run test_delete_workspace_value_error. + def test_export_workspace_async_value_error_with_retries(self): + # Enable retries and run test_export_workspace_async_value_error. _service.enable_retries() - self.test_delete_workspace_value_error() + self.test_export_workspace_async_value_error() - # Disable retries and run test_delete_workspace_value_error. + # Disable retries and run test_export_workspace_async_value_error. _service.disable_retries() - self.test_delete_workspace_value_error() + self.test_export_workspace_async_value_error() + # endregion ############################################################################## @@ -1401,7 +2173,8 @@ def test_delete_workspace_value_error_with_retries(self): ############################################################################## # region -class TestListIntents(): + +class TestListIntents: """ Test Class for list_intents """ @@ -1414,16 +2187,18 @@ def test_list_intents_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'intent' cursor = 'testString' @@ -1438,14 +2213,14 @@ def test_list_intents_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -1471,11 +2246,13 @@ def test_list_intents_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1483,7 +2260,7 @@ def test_list_intents_required_params(self): # Invoke method response = _service.list_intents( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1507,11 +2284,13 @@ def test_list_intents_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1521,11 +2300,10 @@ def test_list_intents_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_intents(**req_copy) - def test_list_intents_value_error_with_retries(self): # Enable retries and run test_list_intents_value_error. _service.enable_retries() @@ -1535,7 +2313,8 @@ def test_list_intents_value_error_with_retries(self): _service.disable_retries() self.test_list_intents_value_error() -class TestCreateIntent(): + +class TestCreateIntent: """ Test Class for create_intent """ @@ -1548,11 +2327,13 @@ def test_create_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -1578,14 +2359,14 @@ def test_create_intent_all_params(self): description=description, examples=examples, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -1611,11 +2392,13 @@ def test_create_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -1639,7 +2422,7 @@ def test_create_intent_required_params(self): intent, description=description, examples=examples, - headers={} + headers={}, ) # Check for correct operation @@ -1668,11 +2451,13 @@ def test_create_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -1696,11 +2481,10 @@ def test_create_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_intent(**req_copy) - def test_create_intent_value_error_with_retries(self): # Enable retries and run test_create_intent_value_error. _service.enable_retries() @@ -1710,7 +2494,8 @@ def test_create_intent_value_error_with_retries(self): _service.disable_retries() self.test_create_intent_value_error() -class TestGetIntent(): + +class TestGetIntent: """ Test Class for get_intent """ @@ -1723,11 +2508,13 @@ def test_get_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1741,14 +2528,14 @@ def test_get_intent_all_params(self): intent, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1770,11 +2557,13 @@ def test_get_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1784,7 +2573,7 @@ def test_get_intent_required_params(self): response = _service.get_intent( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -1808,11 +2597,13 @@ def test_get_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1824,11 +2615,10 @@ def test_get_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_intent(**req_copy) - def test_get_intent_value_error_with_retries(self): # Enable retries and run test_get_intent_value_error. _service.enable_retries() @@ -1838,7 +2628,8 @@ def test_get_intent_value_error_with_retries(self): _service.disable_retries() self.test_get_intent_value_error() -class TestUpdateIntent(): + +class TestUpdateIntent: """ Test Class for update_intent """ @@ -1851,11 +2642,13 @@ def test_update_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -1885,14 +2678,14 @@ def test_update_intent_all_params(self): new_examples=new_examples, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1919,11 +2712,13 @@ def test_update_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -1949,7 +2744,7 @@ def test_update_intent_required_params(self): new_intent=new_intent, new_description=new_description, new_examples=new_examples, - headers={} + headers={}, ) # Check for correct operation @@ -1978,11 +2773,13 @@ def test_update_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2007,11 +2804,10 @@ def test_update_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_intent(**req_copy) - def test_update_intent_value_error_with_retries(self): # Enable retries and run test_update_intent_value_error. _service.enable_retries() @@ -2021,7 +2817,8 @@ def test_update_intent_value_error_with_retries(self): _service.disable_retries() self.test_update_intent_value_error() -class TestDeleteIntent(): + +class TestDeleteIntent: """ Test Class for delete_intent """ @@ -2033,9 +2830,11 @@ def test_delete_intent_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2045,7 +2844,7 @@ def test_delete_intent_all_params(self): response = _service.delete_intent( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2068,9 +2867,11 @@ def test_delete_intent_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2082,11 +2883,10 @@ def test_delete_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_intent(**req_copy) - def test_delete_intent_value_error_with_retries(self): # Enable retries and run test_delete_intent_value_error. _service.enable_retries() @@ -2096,6 +2896,7 @@ def test_delete_intent_value_error_with_retries(self): _service.disable_retries() self.test_delete_intent_value_error() + # endregion ############################################################################## # End of Service: Intents @@ -2106,7 +2907,8 @@ def test_delete_intent_value_error_with_retries(self): ############################################################################## # region -class TestListExamples(): + +class TestListExamples: """ Test Class for list_examples """ @@ -2119,16 +2921,18 @@ def test_list_examples_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' intent = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'text' cursor = 'testString' @@ -2143,14 +2947,14 @@ def test_list_examples_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -2175,11 +2979,13 @@ def test_list_examples_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2189,7 +2995,7 @@ def test_list_examples_required_params(self): response = _service.list_examples( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2213,11 +3019,13 @@ def test_list_examples_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2229,11 +3037,10 @@ def test_list_examples_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_examples(**req_copy) - def test_list_examples_value_error_with_retries(self): # Enable retries and run test_list_examples_value_error. _service.enable_retries() @@ -2243,7 +3050,8 @@ def test_list_examples_value_error_with_retries(self): _service.disable_retries() self.test_list_examples_value_error() -class TestCreateExample(): + +class TestCreateExample: """ Test Class for create_example """ @@ -2256,11 +3064,13 @@ def test_create_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2281,14 +3091,14 @@ def test_create_example_all_params(self): text, mentions=mentions, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2313,11 +3123,13 @@ def test_create_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2336,7 +3148,7 @@ def test_create_example_required_params(self): intent, text, mentions=mentions, - headers={} + headers={}, ) # Check for correct operation @@ -2364,11 +3176,13 @@ def test_create_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2388,11 +3202,10 @@ def test_create_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_example(**req_copy) - def test_create_example_value_error_with_retries(self): # Enable retries and run test_create_example_value_error. _service.enable_retries() @@ -2402,7 +3215,8 @@ def test_create_example_value_error_with_retries(self): _service.disable_retries() self.test_create_example_value_error() -class TestGetExample(): + +class TestGetExample: """ Test Class for get_example """ @@ -2415,11 +3229,13 @@ def test_get_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2433,14 +3249,14 @@ def test_get_example_all_params(self): intent, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2461,11 +3277,13 @@ def test_get_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2477,7 +3295,7 @@ def test_get_example_required_params(self): workspace_id, intent, text, - headers={} + headers={}, ) # Check for correct operation @@ -2501,11 +3319,13 @@ def test_get_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2519,11 +3339,10 @@ def test_get_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_example(**req_copy) - def test_get_example_value_error_with_retries(self): # Enable retries and run test_get_example_value_error. _service.enable_retries() @@ -2533,7 +3352,8 @@ def test_get_example_value_error_with_retries(self): _service.disable_retries() self.test_get_example_value_error() -class TestUpdateExample(): + +class TestUpdateExample: """ Test Class for update_example """ @@ -2546,11 +3366,13 @@ def test_update_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2573,14 +3395,14 @@ def test_update_example_all_params(self): new_text=new_text, new_mentions=new_mentions, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2605,11 +3427,13 @@ def test_update_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2630,7 +3454,7 @@ def test_update_example_required_params(self): text, new_text=new_text, new_mentions=new_mentions, - headers={} + headers={}, ) # Check for correct operation @@ -2658,11 +3482,13 @@ def test_update_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2683,11 +3509,10 @@ def test_update_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_example(**req_copy) - def test_update_example_value_error_with_retries(self): # Enable retries and run test_update_example_value_error. _service.enable_retries() @@ -2697,7 +3522,8 @@ def test_update_example_value_error_with_retries(self): _service.disable_retries() self.test_update_example_value_error() -class TestDeleteExample(): + +class TestDeleteExample: """ Test Class for delete_example """ @@ -2709,9 +3535,11 @@ def test_delete_example_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2723,7 +3551,7 @@ def test_delete_example_all_params(self): workspace_id, intent, text, - headers={} + headers={}, ) # Check for correct operation @@ -2746,9 +3574,11 @@ def test_delete_example_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2762,11 +3592,10 @@ def test_delete_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_example(**req_copy) - def test_delete_example_value_error_with_retries(self): # Enable retries and run test_delete_example_value_error. _service.enable_retries() @@ -2776,6 +3605,7 @@ def test_delete_example_value_error_with_retries(self): _service.disable_retries() self.test_delete_example_value_error() + # endregion ############################################################################## # End of Service: Examples @@ -2786,7 +3616,8 @@ def test_delete_example_value_error_with_retries(self): ############################################################################## # region -class TestListCounterexamples(): + +class TestListCounterexamples: """ Test Class for list_counterexamples """ @@ -2799,15 +3630,17 @@ def test_list_counterexamples_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'text' cursor = 'testString' @@ -2821,14 +3654,14 @@ def test_list_counterexamples_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -2853,11 +3686,13 @@ def test_list_counterexamples_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2865,7 +3700,7 @@ def test_list_counterexamples_required_params(self): # Invoke method response = _service.list_counterexamples( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -2889,11 +3724,13 @@ def test_list_counterexamples_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2903,11 +3740,10 @@ def test_list_counterexamples_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_counterexamples(**req_copy) - def test_list_counterexamples_value_error_with_retries(self): # Enable retries and run test_list_counterexamples_value_error. _service.enable_retries() @@ -2917,7 +3753,8 @@ def test_list_counterexamples_value_error_with_retries(self): _service.disable_retries() self.test_list_counterexamples_value_error() -class TestCreateCounterexample(): + +class TestCreateCounterexample: """ Test Class for create_counterexample """ @@ -2930,11 +3767,13 @@ def test_create_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -2946,14 +3785,14 @@ def test_create_counterexample_all_params(self): workspace_id, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2977,11 +3816,13 @@ def test_create_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -2991,7 +3832,7 @@ def test_create_counterexample_required_params(self): response = _service.create_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3018,11 +3859,13 @@ def test_create_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3034,11 +3877,10 @@ def test_create_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_counterexample(**req_copy) - def test_create_counterexample_value_error_with_retries(self): # Enable retries and run test_create_counterexample_value_error. _service.enable_retries() @@ -3048,7 +3890,8 @@ def test_create_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_create_counterexample_value_error() -class TestGetCounterexample(): + +class TestGetCounterexample: """ Test Class for get_counterexample """ @@ -3061,11 +3904,13 @@ def test_get_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3077,14 +3922,14 @@ def test_get_counterexample_all_params(self): workspace_id, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3105,11 +3950,13 @@ def test_get_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3119,7 +3966,7 @@ def test_get_counterexample_required_params(self): response = _service.get_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3143,11 +3990,13 @@ def test_get_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3159,11 +4008,10 @@ def test_get_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_counterexample(**req_copy) - def test_get_counterexample_value_error_with_retries(self): # Enable retries and run test_get_counterexample_value_error. _service.enable_retries() @@ -3173,7 +4021,8 @@ def test_get_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_get_counterexample_value_error() -class TestUpdateCounterexample(): + +class TestUpdateCounterexample: """ Test Class for update_counterexample """ @@ -3186,11 +4035,13 @@ def test_update_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3204,14 +4055,14 @@ def test_update_counterexample_all_params(self): text, new_text=new_text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3235,11 +4086,13 @@ def test_update_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3251,7 +4104,7 @@ def test_update_counterexample_required_params(self): workspace_id, text, new_text=new_text, - headers={} + headers={}, ) # Check for correct operation @@ -3278,11 +4131,13 @@ def test_update_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3295,11 +4150,10 @@ def test_update_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_counterexample(**req_copy) - def test_update_counterexample_value_error_with_retries(self): # Enable retries and run test_update_counterexample_value_error. _service.enable_retries() @@ -3309,7 +4163,8 @@ def test_update_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_update_counterexample_value_error() -class TestDeleteCounterexample(): + +class TestDeleteCounterexample: """ Test Class for delete_counterexample """ @@ -3321,9 +4176,11 @@ def test_delete_counterexample_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3333,7 +4190,7 @@ def test_delete_counterexample_all_params(self): response = _service.delete_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3356,9 +4213,11 @@ def test_delete_counterexample_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3370,11 +4229,10 @@ def test_delete_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_counterexample(**req_copy) - def test_delete_counterexample_value_error_with_retries(self): # Enable retries and run test_delete_counterexample_value_error. _service.enable_retries() @@ -3384,6 +4242,7 @@ def test_delete_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_delete_counterexample_value_error() + # endregion ############################################################################## # End of Service: Counterexamples @@ -3394,7 +4253,8 @@ def test_delete_counterexample_value_error_with_retries(self): ############################################################################## # region -class TestListEntities(): + +class TestListEntities: """ Test Class for list_entities """ @@ -3406,17 +4266,19 @@ def test_list_entities_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'entity' cursor = 'testString' @@ -3431,14 +4293,14 @@ def test_list_entities_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -3463,12 +4325,14 @@ def test_list_entities_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3476,7 +4340,7 @@ def test_list_entities_required_params(self): # Invoke method response = _service.list_entities( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -3499,12 +4363,14 @@ def test_list_entities_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3514,11 +4380,10 @@ def test_list_entities_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_entities(**req_copy) - def test_list_entities_value_error_with_retries(self): # Enable retries and run test_list_entities_value_error. _service.enable_retries() @@ -3528,7 +4393,8 @@ def test_list_entities_value_error_with_retries(self): _service.disable_retries() self.test_list_entities_value_error() -class TestCreateEntity(): + +class TestCreateEntity: """ Test Class for create_entity """ @@ -3540,17 +4406,19 @@ def test_create_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3559,7 +4427,7 @@ def test_create_entity_all_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] include_audit = False @@ -3573,21 +4441,21 @@ def test_create_entity_all_params(self): fuzzy_match=fuzzy_match, values=values, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3607,17 +4475,19 @@ def test_create_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3626,7 +4496,7 @@ def test_create_entity_required_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] @@ -3638,7 +4508,7 @@ def test_create_entity_required_params(self): metadata=metadata, fuzzy_match=fuzzy_match, values=values, - headers={} + headers={}, ) # Check for correct operation @@ -3648,7 +4518,7 @@ def test_create_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3668,17 +4538,19 @@ def test_create_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3687,7 +4559,7 @@ def test_create_entity_value_error(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] @@ -3697,11 +4569,10 @@ def test_create_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_entity(**req_copy) - def test_create_entity_value_error_with_retries(self): # Enable retries and run test_create_entity_value_error. _service.enable_retries() @@ -3711,7 +4582,8 @@ def test_create_entity_value_error_with_retries(self): _service.disable_retries() self.test_create_entity_value_error() -class TestGetEntity(): + +class TestGetEntity: """ Test Class for get_entity """ @@ -3723,12 +4595,14 @@ def test_get_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3742,14 +4616,14 @@ def test_get_entity_all_params(self): entity, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3770,12 +4644,14 @@ def test_get_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3785,7 +4661,7 @@ def test_get_entity_required_params(self): response = _service.get_entity( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -3808,12 +4684,14 @@ def test_get_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3825,11 +4703,10 @@ def test_get_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_entity(**req_copy) - def test_get_entity_value_error_with_retries(self): # Enable retries and run test_get_entity_value_error. _service.enable_retries() @@ -3839,7 +4716,8 @@ def test_get_entity_value_error_with_retries(self): _service.disable_retries() self.test_get_entity_value_error() -class TestUpdateEntity(): + +class TestUpdateEntity: """ Test Class for update_entity """ @@ -3851,17 +4729,19 @@ def test_update_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3871,7 +4751,7 @@ def test_update_entity_all_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] append = False @@ -3888,14 +4768,14 @@ def test_update_entity_all_params(self): new_values=new_values, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3903,7 +4783,7 @@ def test_update_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3923,17 +4803,19 @@ def test_update_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3943,7 +4825,7 @@ def test_update_entity_required_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] @@ -3956,7 +4838,7 @@ def test_update_entity_required_params(self): new_metadata=new_metadata, new_fuzzy_match=new_fuzzy_match, new_values=new_values, - headers={} + headers={}, ) # Check for correct operation @@ -3966,7 +4848,7 @@ def test_update_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3986,17 +4868,19 @@ def test_update_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4006,7 +4890,7 @@ def test_update_entity_value_error(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] @@ -4016,11 +4900,10 @@ def test_update_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_entity(**req_copy) - def test_update_entity_value_error_with_retries(self): # Enable retries and run test_update_entity_value_error. _service.enable_retries() @@ -4030,7 +4913,8 @@ def test_update_entity_value_error_with_retries(self): _service.disable_retries() self.test_update_entity_value_error() -class TestDeleteEntity(): + +class TestDeleteEntity: """ Test Class for delete_entity """ @@ -4042,9 +4926,11 @@ def test_delete_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4054,7 +4940,7 @@ def test_delete_entity_all_params(self): response = _service.delete_entity( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4077,9 +4963,11 @@ def test_delete_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4091,11 +4979,10 @@ def test_delete_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_entity(**req_copy) - def test_delete_entity_value_error_with_retries(self): # Enable retries and run test_delete_entity_value_error. _service.enable_retries() @@ -4105,6 +4992,7 @@ def test_delete_entity_value_error_with_retries(self): _service.disable_retries() self.test_delete_entity_value_error() + # endregion ############################################################################## # End of Service: Entities @@ -4115,7 +5003,8 @@ def test_delete_entity_value_error_with_retries(self): ############################################################################## # region -class TestListMentions(): + +class TestListMentions: """ Test Class for list_mentions """ @@ -4128,11 +5017,13 @@ def test_list_mentions_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4146,14 +5037,14 @@ def test_list_mentions_all_params(self): entity, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4175,11 +5066,13 @@ def test_list_mentions_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4189,7 +5082,7 @@ def test_list_mentions_required_params(self): response = _service.list_mentions( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4213,11 +5106,13 @@ def test_list_mentions_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4229,11 +5124,10 @@ def test_list_mentions_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_mentions(**req_copy) - def test_list_mentions_value_error_with_retries(self): # Enable retries and run test_list_mentions_value_error. _service.enable_retries() @@ -4243,6 +5137,7 @@ def test_list_mentions_value_error_with_retries(self): _service.disable_retries() self.test_list_mentions_value_error() + # endregion ############################################################################## # End of Service: Mentions @@ -4253,7 +5148,8 @@ def test_list_mentions_value_error_with_retries(self): ############################################################################## # region -class TestListValues(): + +class TestListValues: """ Test Class for list_values """ @@ -4265,18 +5161,20 @@ def test_list_values_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'value' cursor = 'testString' @@ -4292,14 +5190,14 @@ def test_list_values_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -4324,12 +5222,14 @@ def test_list_values_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4339,7 +5239,7 @@ def test_list_values_required_params(self): response = _service.list_values( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4362,12 +5262,14 @@ def test_list_values_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4379,11 +5281,10 @@ def test_list_values_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_values(**req_copy) - def test_list_values_value_error_with_retries(self): # Enable retries and run test_list_values_value_error. _service.enable_retries() @@ -4393,7 +5294,8 @@ def test_list_values_value_error_with_retries(self): _service.disable_retries() self.test_list_values_value_error() -class TestCreateValue(): + +class TestCreateValue: """ Test Class for create_value """ @@ -4405,18 +5307,20 @@ def test_create_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4432,20 +5336,20 @@ def test_create_value_all_params(self): synonyms=synonyms, patterns=patterns, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4466,18 +5370,20 @@ def test_create_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4491,7 +5397,7 @@ def test_create_value_required_params(self): type=type, synonyms=synonyms, patterns=patterns, - headers={} + headers={}, ) # Check for correct operation @@ -4500,7 +5406,7 @@ def test_create_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4521,18 +5427,20 @@ def test_create_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4544,11 +5452,10 @@ def test_create_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_value(**req_copy) - def test_create_value_value_error_with_retries(self): # Enable retries and run test_create_value_value_error. _service.enable_retries() @@ -4558,7 +5465,8 @@ def test_create_value_value_error_with_retries(self): _service.disable_retries() self.test_create_value_value_error() -class TestGetValue(): + +class TestGetValue: """ Test Class for get_value """ @@ -4570,12 +5478,14 @@ def test_get_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4591,14 +5501,14 @@ def test_get_value_all_params(self): value, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4619,12 +5529,14 @@ def test_get_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4636,7 +5548,7 @@ def test_get_value_required_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -4659,12 +5571,14 @@ def test_get_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4678,11 +5592,10 @@ def test_get_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_value(**req_copy) - def test_get_value_value_error_with_retries(self): # Enable retries and run test_get_value_value_error. _service.enable_retries() @@ -4692,7 +5605,8 @@ def test_get_value_value_error_with_retries(self): _service.disable_retries() self.test_get_value_value_error() -class TestUpdateValue(): + +class TestUpdateValue: """ Test Class for update_value """ @@ -4704,19 +5618,21 @@ def test_update_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4735,21 +5651,21 @@ def test_update_value_all_params(self): new_patterns=new_patterns, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4770,19 +5686,21 @@ def test_update_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4797,7 +5715,7 @@ def test_update_value_required_params(self): new_type=new_type, new_synonyms=new_synonyms, new_patterns=new_patterns, - headers={} + headers={}, ) # Check for correct operation @@ -4806,7 +5724,7 @@ def test_update_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4827,19 +5745,21 @@ def test_update_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4851,11 +5771,10 @@ def test_update_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_value(**req_copy) - def test_update_value_value_error_with_retries(self): # Enable retries and run test_update_value_value_error. _service.enable_retries() @@ -4865,7 +5784,8 @@ def test_update_value_value_error_with_retries(self): _service.disable_retries() self.test_update_value_value_error() -class TestDeleteValue(): + +class TestDeleteValue: """ Test Class for delete_value """ @@ -4877,9 +5797,11 @@ def test_delete_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4891,7 +5813,7 @@ def test_delete_value_all_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -4914,9 +5836,11 @@ def test_delete_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4930,11 +5854,10 @@ def test_delete_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_value(**req_copy) - def test_delete_value_value_error_with_retries(self): # Enable retries and run test_delete_value_value_error. _service.enable_retries() @@ -4944,6 +5867,7 @@ def test_delete_value_value_error_with_retries(self): _service.disable_retries() self.test_delete_value_value_error() + # endregion ############################################################################## # End of Service: Values @@ -4954,7 +5878,8 @@ def test_delete_value_value_error_with_retries(self): ############################################################################## # region -class TestListSynonyms(): + +class TestListSynonyms: """ Test Class for list_synonyms """ @@ -4967,17 +5892,19 @@ def test_list_synonyms_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'synonym' cursor = 'testString' @@ -4993,14 +5920,14 @@ def test_list_synonyms_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -5025,11 +5952,13 @@ def test_list_synonyms_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5041,7 +5970,7 @@ def test_list_synonyms_required_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5065,11 +5994,13 @@ def test_list_synonyms_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5083,11 +6014,10 @@ def test_list_synonyms_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_synonyms(**req_copy) - def test_list_synonyms_value_error_with_retries(self): # Enable retries and run test_list_synonyms_value_error. _service.enable_retries() @@ -5097,7 +6027,8 @@ def test_list_synonyms_value_error_with_retries(self): _service.disable_retries() self.test_list_synonyms_value_error() -class TestCreateSynonym(): + +class TestCreateSynonym: """ Test Class for create_synonym """ @@ -5110,11 +6041,13 @@ def test_create_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5130,14 +6063,14 @@ def test_create_synonym_all_params(self): value, synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -5161,11 +6094,13 @@ def test_create_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5179,7 +6114,7 @@ def test_create_synonym_required_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -5206,11 +6141,13 @@ def test_create_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5226,11 +6163,10 @@ def test_create_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_synonym(**req_copy) - def test_create_synonym_value_error_with_retries(self): # Enable retries and run test_create_synonym_value_error. _service.enable_retries() @@ -5240,7 +6176,8 @@ def test_create_synonym_value_error_with_retries(self): _service.disable_retries() self.test_create_synonym_value_error() -class TestGetSynonym(): + +class TestGetSynonym: """ Test Class for get_synonym """ @@ -5253,11 +6190,13 @@ def test_get_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5273,14 +6212,14 @@ def test_get_synonym_all_params(self): value, synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -5301,11 +6240,13 @@ def test_get_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5319,7 +6260,7 @@ def test_get_synonym_required_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -5343,11 +6284,13 @@ def test_get_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5363,11 +6306,10 @@ def test_get_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_synonym(**req_copy) - def test_get_synonym_value_error_with_retries(self): # Enable retries and run test_get_synonym_value_error. _service.enable_retries() @@ -5377,7 +6319,8 @@ def test_get_synonym_value_error_with_retries(self): _service.disable_retries() self.test_get_synonym_value_error() -class TestUpdateSynonym(): + +class TestUpdateSynonym: """ Test Class for update_synonym """ @@ -5390,11 +6333,13 @@ def test_update_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5412,14 +6357,14 @@ def test_update_synonym_all_params(self): synonym, new_synonym=new_synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -5443,11 +6388,13 @@ def test_update_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5463,7 +6410,7 @@ def test_update_synonym_required_params(self): value, synonym, new_synonym=new_synonym, - headers={} + headers={}, ) # Check for correct operation @@ -5490,11 +6437,13 @@ def test_update_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5511,11 +6460,10 @@ def test_update_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_synonym(**req_copy) - def test_update_synonym_value_error_with_retries(self): # Enable retries and run test_update_synonym_value_error. _service.enable_retries() @@ -5525,7 +6473,8 @@ def test_update_synonym_value_error_with_retries(self): _service.disable_retries() self.test_update_synonym_value_error() -class TestDeleteSynonym(): + +class TestDeleteSynonym: """ Test Class for delete_synonym """ @@ -5537,9 +6486,11 @@ def test_delete_synonym_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5553,7 +6504,7 @@ def test_delete_synonym_all_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -5576,9 +6527,11 @@ def test_delete_synonym_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5594,11 +6547,10 @@ def test_delete_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_synonym(**req_copy) - def test_delete_synonym_value_error_with_retries(self): # Enable retries and run test_delete_synonym_value_error. _service.enable_retries() @@ -5608,6 +6560,7 @@ def test_delete_synonym_value_error_with_retries(self): _service.disable_retries() self.test_delete_synonym_value_error() + # endregion ############################################################################## # End of Service: Synonyms @@ -5618,7 +6571,8 @@ def test_delete_synonym_value_error_with_retries(self): ############################################################################## # region -class TestListDialogNodes(): + +class TestListDialogNodes: """ Test Class for list_dialog_nodes """ @@ -5630,16 +6584,18 @@ def test_list_dialog_nodes_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'dialog_node' cursor = 'testString' @@ -5653,14 +6609,14 @@ def test_list_dialog_nodes_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -5684,12 +6640,14 @@ def test_list_dialog_nodes_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5697,7 +6655,7 @@ def test_list_dialog_nodes_required_params(self): # Invoke method response = _service.list_dialog_nodes( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -5720,12 +6678,14 @@ def test_list_dialog_nodes_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5735,11 +6695,10 @@ def test_list_dialog_nodes_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_dialog_nodes(**req_copy) - def test_list_dialog_nodes_value_error_with_retries(self): # Enable retries and run test_list_dialog_nodes_value_error. _service.enable_retries() @@ -5749,7 +6708,8 @@ def test_list_dialog_nodes_value_error_with_retries(self): _service.disable_retries() self.test_list_dialog_nodes_value_error() -class TestCreateDialogNode(): + +class TestCreateDialogNode: """ Test Class for create_dialog_node """ @@ -5761,26 +6721,30 @@ def test_create_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5789,13 +6753,13 @@ def test_create_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -5808,7 +6772,7 @@ def test_create_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -5821,7 +6785,7 @@ def test_create_dialog_node_all_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -5858,14 +6822,14 @@ def test_create_dialog_node_all_params(self): user_label=user_label, disambiguation_opt_out=disambiguation_opt_out, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -5877,7 +6841,7 @@ def test_create_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -5906,26 +6870,30 @@ def test_create_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5934,13 +6902,13 @@ def test_create_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -5953,7 +6921,7 @@ def test_create_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -5966,7 +6934,7 @@ def test_create_dialog_node_required_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6001,7 +6969,7 @@ def test_create_dialog_node_required_params(self): digress_out_slots=digress_out_slots, user_label=user_label, disambiguation_opt_out=disambiguation_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -6016,7 +6984,7 @@ def test_create_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6045,26 +7013,30 @@ def test_create_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6073,13 +7045,13 @@ def test_create_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6092,7 +7064,7 @@ def test_create_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6105,7 +7077,7 @@ def test_create_dialog_node_value_error(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6124,11 +7096,10 @@ def test_create_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_dialog_node(**req_copy) - def test_create_dialog_node_value_error_with_retries(self): # Enable retries and run test_create_dialog_node_value_error. _service.enable_retries() @@ -6138,7 +7109,8 @@ def test_create_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_create_dialog_node_value_error() -class TestGetDialogNode(): + +class TestGetDialogNode: """ Test Class for get_dialog_node """ @@ -6150,12 +7122,14 @@ def test_get_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6167,14 +7141,14 @@ def test_get_dialog_node_all_params(self): workspace_id, dialog_node, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -6194,12 +7168,14 @@ def test_get_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6209,7 +7185,7 @@ def test_get_dialog_node_required_params(self): response = _service.get_dialog_node( workspace_id, dialog_node, - headers={} + headers={}, ) # Check for correct operation @@ -6232,12 +7208,14 @@ def test_get_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6249,11 +7227,10 @@ def test_get_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_dialog_node(**req_copy) - def test_get_dialog_node_value_error_with_retries(self): # Enable retries and run test_get_dialog_node_value_error. _service.enable_retries() @@ -6263,7 +7240,8 @@ def test_get_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_get_dialog_node_value_error() -class TestUpdateDialogNode(): + +class TestUpdateDialogNode: """ Test Class for update_dialog_node """ @@ -6275,26 +7253,30 @@ def test_update_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6303,13 +7285,13 @@ def test_update_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6322,7 +7304,7 @@ def test_update_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6336,7 +7318,7 @@ def test_update_dialog_node_all_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6374,14 +7356,14 @@ def test_update_dialog_node_all_params(self): new_user_label=new_user_label, new_disambiguation_opt_out=new_disambiguation_opt_out, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -6393,7 +7375,7 @@ def test_update_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6422,26 +7404,30 @@ def test_update_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6450,13 +7436,13 @@ def test_update_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6469,7 +7455,7 @@ def test_update_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6483,7 +7469,7 @@ def test_update_dialog_node_required_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6519,7 +7505,7 @@ def test_update_dialog_node_required_params(self): new_digress_out_slots=new_digress_out_slots, new_user_label=new_user_label, new_disambiguation_opt_out=new_disambiguation_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -6534,7 +7520,7 @@ def test_update_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6563,26 +7549,30 @@ def test_update_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6591,13 +7581,13 @@ def test_update_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6610,7 +7600,7 @@ def test_update_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6624,7 +7614,7 @@ def test_update_dialog_node_value_error(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6643,11 +7633,10 @@ def test_update_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_dialog_node(**req_copy) - def test_update_dialog_node_value_error_with_retries(self): # Enable retries and run test_update_dialog_node_value_error. _service.enable_retries() @@ -6657,7 +7646,8 @@ def test_update_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_update_dialog_node_value_error() -class TestDeleteDialogNode(): + +class TestDeleteDialogNode: """ Test Class for delete_dialog_node """ @@ -6669,9 +7659,11 @@ def test_delete_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6681,7 +7673,7 @@ def test_delete_dialog_node_all_params(self): response = _service.delete_dialog_node( workspace_id, dialog_node, - headers={} + headers={}, ) # Check for correct operation @@ -6704,9 +7696,11 @@ def test_delete_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6718,11 +7712,10 @@ def test_delete_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_dialog_node(**req_copy) - def test_delete_dialog_node_value_error_with_retries(self): # Enable retries and run test_delete_dialog_node_value_error. _service.enable_retries() @@ -6732,6 +7725,7 @@ def test_delete_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_delete_dialog_node_value_error() + # endregion ############################################################################## # End of Service: DialogNodes @@ -6742,7 +7736,8 @@ def test_delete_dialog_node_value_error_with_retries(self): ############################################################################## # region -class TestListLogs(): + +class TestListLogs: """ Test Class for list_logs """ @@ -6754,18 +7749,20 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' sort = 'testString' filter = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -6775,14 +7772,14 @@ def test_list_logs_all_params(self): filter=filter, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'sort={}'.format(sort) in query_string assert 'filter={}'.format(filter) in query_string @@ -6805,12 +7802,14 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6818,7 +7817,7 @@ def test_list_logs_required_params(self): # Invoke method response = _service.list_logs( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -6841,12 +7840,14 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6856,11 +7857,10 @@ def test_list_logs_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_logs(**req_copy) - def test_list_logs_value_error_with_retries(self): # Enable retries and run test_list_logs_value_error. _service.enable_retries() @@ -6870,7 +7870,8 @@ def test_list_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_logs_value_error() -class TestListAllLogs(): + +class TestListAllLogs: """ Test Class for list_all_logs """ @@ -6882,17 +7883,19 @@ def test_list_all_logs_all_params(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' sort = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -6901,14 +7904,14 @@ def test_list_all_logs_all_params(self): sort=sort, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'sort={}'.format(sort) in query_string @@ -6931,12 +7934,14 @@ def test_list_all_logs_required_params(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' @@ -6944,14 +7949,14 @@ def test_list_all_logs_required_params(self): # Invoke method response = _service.list_all_logs( filter, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string @@ -6971,12 +7976,14 @@ def test_list_all_logs_value_error(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' @@ -6986,11 +7993,10 @@ def test_list_all_logs_value_error(self): "filter": filter, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_all_logs(**req_copy) - def test_list_all_logs_value_error_with_retries(self): # Enable retries and run test_list_all_logs_value_error. _service.enable_retries() @@ -7000,6 +8006,7 @@ def test_list_all_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_all_logs_value_error() + # endregion ############################################################################## # End of Service: Logs @@ -7010,7 +8017,8 @@ def test_list_all_logs_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -7022,9 +8030,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -7032,14 +8042,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -7059,9 +8069,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -7071,11 +8083,10 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -7085,6 +8096,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -7095,7 +8107,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + + +class TestModel_AgentAvailabilityMessage: """ Test Class for AgentAvailabilityMessage """ @@ -7124,7 +8138,8 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestModel_BulkClassifyOutput(): + +class TestModel_BulkClassifyOutput: """ Test Class for BulkClassifyOutput """ @@ -7136,14 +8151,14 @@ def test_bulk_classify_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -7171,14 +8186,14 @@ def test_bulk_classify_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -7188,7 +8203,7 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -7213,7 +8228,8 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestModel_BulkClassifyResponse(): + +class TestModel_BulkClassifyResponse: """ Test Class for BulkClassifyResponse """ @@ -7225,14 +8241,14 @@ def test_bulk_classify_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -7260,14 +8276,14 @@ def test_bulk_classify_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -7277,11 +8293,11 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model = {} # BulkClassifyOutput bulk_classify_output_model['input'] = bulk_classify_utterance_model bulk_classify_output_model['entities'] = [runtime_entity_model] bulk_classify_output_model['intents'] = [runtime_intent_model] @@ -7305,7 +8321,8 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestModel_BulkClassifyUtterance(): + +class TestModel_BulkClassifyUtterance: """ Test Class for BulkClassifyUtterance """ @@ -7334,7 +8351,8 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestModel_CaptureGroup(): + +class TestModel_CaptureGroup: """ Test Class for CaptureGroup """ @@ -7364,7 +8382,8 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestModel_ChannelTransferInfo(): + +class TestModel_ChannelTransferInfo: """ Test Class for ChannelTransferInfo """ @@ -7376,10 +8395,10 @@ def test_channel_transfer_info_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model # Construct a json representation of a ChannelTransferInfo model @@ -7401,7 +8420,8 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestModel_ChannelTransferTarget(): + +class TestModel_ChannelTransferTarget: """ Test Class for ChannelTransferTarget """ @@ -7413,7 +8433,7 @@ def test_channel_transfer_target_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' # Construct a json representation of a ChannelTransferTarget model @@ -7435,7 +8455,8 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestModel_ChannelTransferTargetChat(): + +class TestModel_ChannelTransferTargetChat: """ Test Class for ChannelTransferTargetChat """ @@ -7464,7 +8485,8 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestModel_Context(): + +class TestModel_Context: """ Test Class for Context """ @@ -7476,14 +8498,14 @@ def test_context_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' # Construct a json representation of a Context model context_model_json = {} context_model_json['conversation_id'] = 'testString' - context_model_json['system'] = {} + context_model_json['system'] = {'anyKey': 'anyValue'} context_model_json['metadata'] = message_context_metadata_model context_model_json['foo'] = 'testString' @@ -7510,9 +8532,10 @@ def test_context_serialization(self): expected_dict = {'foo': 'testString'} context_model.set_properties(expected_dict) actual_dict = context_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() -class TestModel_Counterexample(): + +class TestModel_Counterexample: """ Test Class for Counterexample """ @@ -7525,8 +8548,6 @@ def test_counterexample_serialization(self): # Construct a json representation of a Counterexample model counterexample_model_json = {} counterexample_model_json['text'] = 'testString' - counterexample_model_json['created'] = '2019-01-01T12:00:00Z' - counterexample_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Counterexample by calling from_dict on the json representation counterexample_model = Counterexample.from_dict(counterexample_model_json) @@ -7543,7 +8564,8 @@ def test_counterexample_serialization(self): counterexample_model_json2 = counterexample_model.to_dict() assert counterexample_model_json2 == counterexample_model_json -class TestModel_CounterexampleCollection(): + +class TestModel_CounterexampleCollection: """ Test Class for CounterexampleCollection """ @@ -7555,12 +8577,10 @@ def test_counterexample_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -7588,7 +8608,8 @@ def test_counterexample_collection_serialization(self): counterexample_collection_model_json2 = counterexample_collection_model.to_dict() assert counterexample_collection_model_json2 == counterexample_collection_model_json -class TestModel_CreateEntity(): + +class TestModel_CreateEntity: """ Test Class for CreateEntity """ @@ -7600,23 +8621,19 @@ def test_create_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - create_value_model = {} # CreateValue + create_value_model = {} # CreateValue create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] - create_value_model['created'] = '2019-01-01T12:00:00Z' - create_value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateEntity model create_entity_model_json = {} create_entity_model_json['entity'] = 'testString' create_entity_model_json['description'] = 'testString' - create_entity_model_json['metadata'] = {} + create_entity_model_json['metadata'] = {'anyKey': 'anyValue'} create_entity_model_json['fuzzy_match'] = True - create_entity_model_json['created'] = '2019-01-01T12:00:00Z' - create_entity_model_json['updated'] = '2019-01-01T12:00:00Z' create_entity_model_json['values'] = [create_value_model] # Construct a model instance of CreateEntity by calling from_dict on the json representation @@ -7634,7 +8651,8 @@ def test_create_entity_serialization(self): create_entity_model_json2 = create_entity_model.to_dict() assert create_entity_model_json2 == create_entity_model_json -class TestModel_CreateIntent(): + +class TestModel_CreateIntent: """ Test Class for CreateIntent """ @@ -7646,22 +8664,18 @@ def test_create_intent_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateIntent model create_intent_model_json = {} create_intent_model_json['intent'] = 'testString' create_intent_model_json['description'] = 'testString' - create_intent_model_json['created'] = '2019-01-01T12:00:00Z' - create_intent_model_json['updated'] = '2019-01-01T12:00:00Z' create_intent_model_json['examples'] = [example_model] # Construct a model instance of CreateIntent by calling from_dict on the json representation @@ -7679,7 +8693,8 @@ def test_create_intent_serialization(self): create_intent_model_json2 = create_intent_model.to_dict() assert create_intent_model_json2 == create_intent_model_json -class TestModel_CreateValue(): + +class TestModel_CreateValue: """ Test Class for CreateValue """ @@ -7692,12 +8707,10 @@ def test_create_value_serialization(self): # Construct a json representation of a CreateValue model create_value_model_json = {} create_value_model_json['value'] = 'testString' - create_value_model_json['metadata'] = {} + create_value_model_json['metadata'] = {'anyKey': 'anyValue'} create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] - create_value_model_json['created'] = '2019-01-01T12:00:00Z' - create_value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of CreateValue by calling from_dict on the json representation create_value_model = CreateValue.from_dict(create_value_model_json) @@ -7714,7 +8727,8 @@ def test_create_value_serialization(self): create_value_model_json2 = create_value_model.to_dict() assert create_value_model_json2 == create_value_model_json -class TestModel_DialogNode(): + +class TestModel_DialogNode: """ Test Class for DialogNode """ @@ -7726,40 +8740,41 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7772,7 +8787,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json['previous_sibling'] = 'testString' dialog_node_model_json['output'] = dialog_node_output_model dialog_node_model_json['context'] = dialog_node_context_model - dialog_node_model_json['metadata'] = {} + dialog_node_model_json['metadata'] = {'anyKey': 'anyValue'} dialog_node_model_json['next_step'] = dialog_node_next_step_model dialog_node_model_json['title'] = 'testString' dialog_node_model_json['type'] = 'standard' @@ -7784,9 +8799,6 @@ def test_dialog_node_serialization(self): dialog_node_model_json['digress_out_slots'] = 'not_allowed' dialog_node_model_json['user_label'] = 'testString' dialog_node_model_json['disambiguation_opt_out'] = False - dialog_node_model_json['disabled'] = True - dialog_node_model_json['created'] = '2019-01-01T12:00:00Z' - dialog_node_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of DialogNode by calling from_dict on the json representation dialog_node_model = DialogNode.from_dict(dialog_node_model_json) @@ -7803,7 +8815,8 @@ def test_dialog_node_serialization(self): dialog_node_model_json2 = dialog_node_model.to_dict() assert dialog_node_model_json2 == dialog_node_model_json -class TestModel_DialogNodeAction(): + +class TestModel_DialogNodeAction: """ Test Class for DialogNodeAction """ @@ -7817,7 +8830,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {} + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -7836,7 +8849,8 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestModel_DialogNodeCollection(): + +class TestModel_DialogNodeCollection: """ Test Class for DialogNodeCollection """ @@ -7848,44 +8862,45 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -7893,7 +8908,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -7905,11 +8920,8 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -7937,7 +8949,8 @@ def test_dialog_node_collection_serialization(self): dialog_node_collection_model_json2 = dialog_node_collection_model.to_dict() assert dialog_node_collection_model_json2 == dialog_node_collection_model_json -class TestModel_DialogNodeContext(): + +class TestModel_DialogNodeContext: """ Test Class for DialogNodeContext """ @@ -7949,7 +8962,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} - dialog_node_context_model_json['integrations'] = {} + dialog_node_context_model_json['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation @@ -7975,9 +8988,10 @@ def test_dialog_node_context_serialization(self): expected_dict = {'foo': 'testString'} dialog_node_context_model.set_properties(expected_dict) actual_dict = dialog_node_context_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() + -class TestModel_DialogNodeNextStep(): +class TestModel_DialogNodeNextStep: """ Test Class for DialogNodeNextStep """ @@ -8008,7 +9022,8 @@ def test_dialog_node_next_step_serialization(self): dialog_node_next_step_model_json2 = dialog_node_next_step_model.to_dict() assert dialog_node_next_step_model_json2 == dialog_node_next_step_model_json -class TestModel_DialogNodeOutput(): + +class TestModel_DialogNodeOutput: """ Test Class for DialogNodeOutput """ @@ -8020,25 +9035,26 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True # Construct a json representation of a DialogNodeOutput model dialog_node_output_model_json = {} dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model_json['integrations'] = {} + dialog_node_output_model_json['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model_json['foo'] = 'testString' @@ -8065,9 +9081,10 @@ def test_dialog_node_output_serialization(self): expected_dict = {'foo': 'testString'} dialog_node_output_model.set_properties(expected_dict) actual_dict = dialog_node_output_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() + -class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -8079,7 +9096,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -8096,7 +9113,8 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestModel_DialogNodeOutputModifiers(): + +class TestModel_DialogNodeOutputModifiers: """ Test Class for DialogNodeOutputModifiers """ @@ -8125,7 +9143,8 @@ def test_dialog_node_output_modifiers_serialization(self): dialog_node_output_modifiers_model_json2 = dialog_node_output_modifiers_model.to_dict() assert dialog_node_output_modifiers_model_json2 == dialog_node_output_modifiers_model_json -class TestModel_DialogNodeOutputOptionsElement(): + +class TestModel_DialogNodeOutputOptionsElement: """ Test Class for DialogNodeOutputOptionsElement """ @@ -8137,23 +9156,21 @@ def test_dialog_node_output_options_element_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8181,14 +9198,14 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8198,7 +9215,7 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] @@ -8223,7 +9240,8 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestModel_DialogNodeOutputOptionsElementValue(): + +class TestModel_DialogNodeOutputOptionsElementValue: """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -8235,23 +9253,21 @@ def test_dialog_node_output_options_element_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8279,14 +9295,14 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8317,7 +9333,8 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_DialogNodeOutputTextValuesElement(): + +class TestModel_DialogNodeOutputTextValuesElement: """ Test Class for DialogNodeOutputTextValuesElement """ @@ -8346,7 +9363,8 @@ def test_dialog_node_output_text_values_element_serialization(self): dialog_node_output_text_values_element_model_json2 = dialog_node_output_text_values_element_model.to_dict() assert dialog_node_output_text_values_element_model_json2 == dialog_node_output_text_values_element_model_json -class TestModel_DialogNodeVisitedDetails(): + +class TestModel_DialogNodeVisitedDetails: """ Test Class for DialogNodeVisitedDetails """ @@ -8377,7 +9395,8 @@ def test_dialog_node_visited_details_serialization(self): dialog_node_visited_details_model_json2 = dialog_node_visited_details_model.to_dict() assert dialog_node_visited_details_model_json2 == dialog_node_visited_details_model_json -class TestModel_DialogSuggestion(): + +class TestModel_DialogSuggestion: """ Test Class for DialogSuggestion """ @@ -8389,23 +9408,21 @@ def test_dialog_suggestion_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8433,14 +9450,14 @@ def test_dialog_suggestion_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8450,7 +9467,7 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model dialog_suggestion_value_model['intents'] = [runtime_intent_model] dialog_suggestion_value_model['entities'] = [runtime_entity_model] @@ -8459,7 +9476,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {} + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} dialog_suggestion_model_json['dialog_node'] = 'testString' # Construct a model instance of DialogSuggestion by calling from_dict on the json representation @@ -8477,7 +9494,8 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_DialogSuggestionValue(): + +class TestModel_DialogSuggestionValue: """ Test Class for DialogSuggestionValue """ @@ -8489,23 +9507,21 @@ def test_dialog_suggestion_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8533,14 +9549,14 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8571,7 +9587,8 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_Entity(): + +class TestModel_Entity: """ Test Class for Entity """ @@ -8583,23 +9600,19 @@ def test_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Entity model entity_model_json = {} entity_model_json['entity'] = 'testString' entity_model_json['description'] = 'testString' - entity_model_json['metadata'] = {} + entity_model_json['metadata'] = {'anyKey': 'anyValue'} entity_model_json['fuzzy_match'] = True - entity_model_json['created'] = '2019-01-01T12:00:00Z' - entity_model_json['updated'] = '2019-01-01T12:00:00Z' entity_model_json['values'] = [value_model] # Construct a model instance of Entity by calling from_dict on the json representation @@ -8617,7 +9630,8 @@ def test_entity_serialization(self): entity_model_json2 = entity_model.to_dict() assert entity_model_json2 == entity_model_json -class TestModel_EntityCollection(): + +class TestModel_EntityCollection: """ Test Class for EntityCollection """ @@ -8629,25 +9643,21 @@ def test_entity_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8675,7 +9685,8 @@ def test_entity_collection_serialization(self): entity_collection_model_json2 = entity_collection_model.to_dict() assert entity_collection_model_json2 == entity_collection_model_json -class TestModel_EntityMention(): + +class TestModel_EntityMention: """ Test Class for EntityMention """ @@ -8706,7 +9717,8 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestModel_EntityMentionCollection(): + +class TestModel_EntityMentionCollection: """ Test Class for EntityMentionCollection """ @@ -8718,12 +9730,12 @@ def test_entity_mention_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['intent'] = 'testString' entity_mention_model['location'] = [38] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8751,7 +9763,8 @@ def test_entity_mention_collection_serialization(self): entity_mention_collection_model_json2 = entity_mention_collection_model.to_dict() assert entity_mention_collection_model_json2 == entity_mention_collection_model_json -class TestModel_Example(): + +class TestModel_Example: """ Test Class for Example """ @@ -8763,7 +9776,7 @@ def test_example_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] @@ -8771,8 +9784,6 @@ def test_example_serialization(self): example_model_json = {} example_model_json['text'] = 'testString' example_model_json['mentions'] = [mention_model] - example_model_json['created'] = '2019-01-01T12:00:00Z' - example_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Example by calling from_dict on the json representation example_model = Example.from_dict(example_model_json) @@ -8789,7 +9800,8 @@ def test_example_serialization(self): example_model_json2 = example_model.to_dict() assert example_model_json2 == example_model_json -class TestModel_ExampleCollection(): + +class TestModel_ExampleCollection: """ Test Class for ExampleCollection """ @@ -8801,17 +9813,15 @@ def test_example_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8839,7 +9849,8 @@ def test_example_collection_serialization(self): example_collection_model_json2 = example_collection_model.to_dict() assert example_collection_model_json2 == example_collection_model_json -class TestModel_Intent(): + +class TestModel_Intent: """ Test Class for Intent """ @@ -8851,22 +9862,18 @@ def test_intent_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Intent model intent_model_json = {} intent_model_json['intent'] = 'testString' intent_model_json['description'] = 'testString' - intent_model_json['created'] = '2019-01-01T12:00:00Z' - intent_model_json['updated'] = '2019-01-01T12:00:00Z' intent_model_json['examples'] = [example_model] # Construct a model instance of Intent by calling from_dict on the json representation @@ -8884,7 +9891,8 @@ def test_intent_serialization(self): intent_model_json2 = intent_model.to_dict() assert intent_model_json2 == intent_model_json -class TestModel_IntentCollection(): + +class TestModel_IntentCollection: """ Test Class for IntentCollection """ @@ -8896,24 +9904,20 @@ def test_intent_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8941,7 +9945,8 @@ def test_intent_collection_serialization(self): intent_collection_model_json2 = intent_collection_model.to_dict() assert intent_collection_model_json2 == intent_collection_model_json -class TestModel_Log(): + +class TestModel_Log: """ Test Class for Log """ @@ -8953,23 +9958,21 @@ def test_log_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8997,14 +10000,14 @@ def test_log_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9014,83 +10017,62 @@ def test_log_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model - message_request_model['actions'] = [dialog_node_action_model] message_request_model['user_id'] = 'testString' - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model - message_response_model['actions'] = [dialog_node_action_model] message_response_model['user_id'] = 'testString' # Construct a json representation of a Log model @@ -9118,7 +10100,8 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestModel_LogCollection(): + +class TestModel_LogCollection: """ Test Class for LogCollection """ @@ -9130,23 +10113,21 @@ def test_log_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9174,14 +10155,14 @@ def test_log_collection_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9191,86 +10172,65 @@ def test_log_collection_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model - message_request_model['actions'] = [dialog_node_action_model] message_request_model['user_id'] = 'testString' - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model - message_response_model['actions'] = [dialog_node_action_model] message_response_model['user_id'] = 'testString' - log_model = {} # Log + log_model = {} # Log log_model['request'] = message_request_model log_model['response'] = message_response_model log_model['log_id'] = 'testString' @@ -9279,7 +10239,7 @@ def test_log_collection_serialization(self): log_model['workspace_id'] = 'testString' log_model['language'] = 'testString' - log_pagination_model = {} # LogPagination + log_pagination_model = {} # LogPagination log_pagination_model['next_url'] = 'testString' log_pagination_model['matched'] = 38 log_pagination_model['next_cursor'] = 'testString' @@ -9304,7 +10264,8 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestModel_LogMessage(): + +class TestModel_LogMessage: """ Test Class for LogMessage """ @@ -9316,7 +10277,7 @@ def test_log_message_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' @@ -9342,7 +10303,8 @@ def test_log_message_serialization(self): log_message_model_json2 = log_message_model.to_dict() assert log_message_model_json2 == log_message_model_json -class TestModel_LogMessageSource(): + +class TestModel_LogMessageSource: """ Test Class for LogMessageSource """ @@ -9372,7 +10334,8 @@ def test_log_message_source_serialization(self): log_message_source_model_json2 = log_message_source_model.to_dict() assert log_message_source_model_json2 == log_message_source_model_json -class TestModel_LogPagination(): + +class TestModel_LogPagination: """ Test Class for LogPagination """ @@ -9403,7 +10366,8 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_Mention(): + +class TestModel_Mention: """ Test Class for Mention """ @@ -9433,7 +10397,8 @@ def test_mention_serialization(self): mention_model_json2 = mention_model.to_dict() assert mention_model_json2 == mention_model_json -class TestModel_MessageContextMetadata(): + +class TestModel_MessageContextMetadata: """ Test Class for MessageContextMetadata """ @@ -9463,7 +10428,8 @@ def test_message_context_metadata_serialization(self): message_context_metadata_model_json2 = message_context_metadata_model.to_dict() assert message_context_metadata_model_json2 == message_context_metadata_model_json -class TestModel_MessageInput(): + +class TestModel_MessageInput: """ Test Class for MessageInput """ @@ -9478,8 +10444,6 @@ def test_message_input_serialization(self): message_input_model_json['text'] = 'testString' message_input_model_json['spelling_suggestions'] = False message_input_model_json['spelling_auto_correct'] = False - message_input_model_json['suggested_text'] = 'testString' - message_input_model_json['original_text'] = 'testString' message_input_model_json['foo'] = 'testString' # Construct a model instance of MessageInput by calling from_dict on the json representation @@ -9505,9 +10469,10 @@ def test_message_input_serialization(self): expected_dict = {'foo': 'testString'} message_input_model.set_properties(expected_dict) actual_dict = message_input_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() + -class TestModel_MessageRequest(): +class TestModel_MessageRequest: """ Test Class for MessageRequest """ @@ -9519,23 +10484,21 @@ def test_message_request_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9563,14 +10526,14 @@ def test_message_request_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9580,65 +10543,46 @@ def test_message_request_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageRequest model message_request_model_json = {} message_request_model_json['input'] = message_input_model @@ -9647,7 +10591,6 @@ def test_message_request_serialization(self): message_request_model_json['alternate_intents'] = False message_request_model_json['context'] = context_model message_request_model_json['output'] = output_data_model - message_request_model_json['actions'] = [dialog_node_action_model] message_request_model_json['user_id'] = 'testString' # Construct a model instance of MessageRequest by calling from_dict on the json representation @@ -9665,7 +10608,8 @@ def test_message_request_serialization(self): message_request_model_json2 = message_request_model.to_dict() assert message_request_model_json2 == message_request_model_json -class TestModel_MessageResponse(): + +class TestModel_MessageResponse: """ Test Class for MessageResponse """ @@ -9677,23 +10621,21 @@ def test_message_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9721,14 +10663,14 @@ def test_message_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9738,65 +10680,46 @@ def test_message_response_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageResponse model message_response_model_json = {} message_response_model_json['input'] = message_input_model @@ -9805,7 +10728,6 @@ def test_message_response_serialization(self): message_response_model_json['alternate_intents'] = False message_response_model_json['context'] = context_model message_response_model_json['output'] = output_data_model - message_response_model_json['actions'] = [dialog_node_action_model] message_response_model_json['user_id'] = 'testString' # Construct a model instance of MessageResponse by calling from_dict on the json representation @@ -9823,7 +10745,8 @@ def test_message_response_serialization(self): message_response_model_json2 = message_response_model.to_dict() assert message_response_model_json2 == message_response_model_json -class TestModel_OutputData(): + +class TestModel_OutputData: """ Test Class for OutputData """ @@ -9835,100 +10758,27 @@ def test_output_data_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - message_input_model = {} # MessageInput - message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = False - message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' - message_input_model['foo'] = 'testString' - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a json representation of a OutputData model @@ -9962,9 +10812,10 @@ def test_output_data_serialization(self): expected_dict = {'foo': 'testString'} output_data_model.set_properties(expected_dict) actual_dict = output_data_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() + -class TestModel_Pagination(): +class TestModel_Pagination: """ Test Class for Pagination """ @@ -9998,7 +10849,8 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestModel_ResponseGenericChannel(): + +class TestModel_ResponseGenericChannel: """ Test Class for ResponseGenericChannel """ @@ -10027,7 +10879,8 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_RuntimeEntity(): + +class TestModel_RuntimeEntity: """ Test Class for RuntimeEntity """ @@ -10039,11 +10892,11 @@ def test_runtime_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10071,11 +10924,11 @@ def test_runtime_entity_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' # Construct a json representation of a RuntimeEntity model @@ -10104,7 +10957,8 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_RuntimeEntityAlternative(): + +class TestModel_RuntimeEntityAlternative: """ Test Class for RuntimeEntityAlternative """ @@ -10134,7 +10988,8 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_RuntimeEntityInterpretation(): + +class TestModel_RuntimeEntityInterpretation: """ Test Class for RuntimeEntityInterpretation """ @@ -10188,7 +11043,8 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestModel_RuntimeEntityRole(): + +class TestModel_RuntimeEntityRole: """ Test Class for RuntimeEntityRole """ @@ -10217,7 +11073,8 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_RuntimeIntent(): + +class TestModel_RuntimeIntent: """ Test Class for RuntimeIntent """ @@ -10247,7 +11104,38 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestModel_Synonym(): + +class TestModel_StatusError: + """ + Test Class for StatusError + """ + + def test_status_error_serialization(self): + """ + Test serialization/deserialization for StatusError + """ + + # Construct a json representation of a StatusError model + status_error_model_json = {} + status_error_model_json['message'] = 'testString' + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model = StatusError.from_dict(status_error_model_json) + assert status_error_model != False + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ + status_error_model2 = StatusError(**status_error_model_dict) + + # Verify the model instances are equivalent + assert status_error_model == status_error_model2 + + # Convert model instance back to dict and verify no loss of data + status_error_model_json2 = status_error_model.to_dict() + assert status_error_model_json2 == status_error_model_json + + +class TestModel_Synonym: """ Test Class for Synonym """ @@ -10260,8 +11148,6 @@ def test_synonym_serialization(self): # Construct a json representation of a Synonym model synonym_model_json = {} synonym_model_json['synonym'] = 'testString' - synonym_model_json['created'] = '2019-01-01T12:00:00Z' - synonym_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Synonym by calling from_dict on the json representation synonym_model = Synonym.from_dict(synonym_model_json) @@ -10278,7 +11164,8 @@ def test_synonym_serialization(self): synonym_model_json2 = synonym_model.to_dict() assert synonym_model_json2 == synonym_model_json -class TestModel_SynonymCollection(): + +class TestModel_SynonymCollection: """ Test Class for SynonymCollection """ @@ -10290,12 +11177,10 @@ def test_synonym_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - synonym_model = {} # Synonym + synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - synonym_model['created'] = '2019-01-01T12:00:00Z' - synonym_model['updated'] = '2019-01-01T12:00:00Z' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10323,7 +11208,8 @@ def test_synonym_collection_serialization(self): synonym_collection_model_json2 = synonym_collection_model.to_dict() assert synonym_collection_model_json2 == synonym_collection_model_json -class TestModel_Value(): + +class TestModel_Value: """ Test Class for Value """ @@ -10336,12 +11222,10 @@ def test_value_serialization(self): # Construct a json representation of a Value model value_model_json = {} value_model_json['value'] = 'testString' - value_model_json['metadata'] = {} + value_model_json['metadata'] = {'anyKey': 'anyValue'} value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] - value_model_json['created'] = '2019-01-01T12:00:00Z' - value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Value by calling from_dict on the json representation value_model = Value.from_dict(value_model_json) @@ -10358,7 +11242,8 @@ def test_value_serialization(self): value_model_json2 = value_model.to_dict() assert value_model_json2 == value_model_json -class TestModel_ValueCollection(): + +class TestModel_ValueCollection: """ Test Class for ValueCollection """ @@ -10370,16 +11255,14 @@ def test_value_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10407,7 +11290,8 @@ def test_value_collection_serialization(self): value_collection_model_json2 = value_collection_model.to_dict() assert value_collection_model_json2 == value_collection_model_json -class TestModel_Webhook(): + +class TestModel_Webhook: """ Test Class for Webhook """ @@ -10419,7 +11303,7 @@ def test_webhook_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -10444,7 +11328,8 @@ def test_webhook_serialization(self): webhook_model_json2 = webhook_model.to_dict() assert webhook_model_json2 == webhook_model_json -class TestModel_WebhookHeader(): + +class TestModel_WebhookHeader: """ Test Class for WebhookHeader """ @@ -10474,7 +11359,8 @@ def test_webhook_header_serialization(self): webhook_header_model_json2 = webhook_header_model.to_dict() assert webhook_header_model_json2 == webhook_header_model_json -class TestModel_Workspace(): + +class TestModel_Workspace: """ Test Class for Workspace """ @@ -10486,44 +11372,45 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -10531,7 +11418,7 @@ def test_workspace_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -10543,19 +11430,14 @@ def test_workspace_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -10564,64 +11446,60 @@ def test_workspace_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'testString' + + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' - webhook_model = {} # Webhook + webhook_model = {} # Webhook webhook_model['url'] = 'testString' webhook_model['name'] = 'testString' webhook_model['headers'] = [webhook_header_model] - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] # Construct a json representation of a Workspace model @@ -10629,15 +11507,11 @@ def test_workspace_serialization(self): workspace_model_json['name'] = 'testString' workspace_model_json['description'] = 'testString' workspace_model_json['language'] = 'testString' - workspace_model_json['workspace_id'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['created'] = '2019-01-01T12:00:00Z' - workspace_model_json['updated'] = '2019-01-01T12:00:00Z' - workspace_model_json['metadata'] = {} + workspace_model_json['metadata'] = {'anyKey': 'anyValue'} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model - workspace_model_json['status'] = 'Non Existent' workspace_model_json['webhooks'] = [webhook_model] workspace_model_json['intents'] = [intent_model] workspace_model_json['entities'] = [entity_model] @@ -10657,7 +11531,8 @@ def test_workspace_serialization(self): workspace_model_json2 = workspace_model.to_dict() assert workspace_model_json2 == workspace_model_json -class TestModel_WorkspaceCollection(): + +class TestModel_WorkspaceCollection: """ Test Class for WorkspaceCollection """ @@ -10669,44 +11544,45 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -10714,7 +11590,7 @@ def test_workspace_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -10726,19 +11602,14 @@ def test_workspace_collection_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -10747,84 +11618,76 @@ def test_workspace_collection_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'testString' + + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' - webhook_model = {} # Webhook + webhook_model = {} # Webhook webhook_model['url'] = 'testString' webhook_model['name'] = 'testString' webhook_model['headers'] = [webhook_header_model] - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] - workspace_model = {} # Workspace + workspace_model = {} # Workspace workspace_model['name'] = 'testString' workspace_model['description'] = 'testString' workspace_model['language'] = 'testString' - workspace_model['workspace_id'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['created'] = '2019-01-01T12:00:00Z' - workspace_model['updated'] = '2019-01-01T12:00:00Z' - workspace_model['metadata'] = {} + workspace_model['metadata'] = {'anyKey': 'anyValue'} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model - workspace_model['status'] = 'Non Existent' workspace_model['webhooks'] = [webhook_model] workspace_model['intents'] = [intent_model] workspace_model['entities'] = [entity_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10852,7 +11715,40 @@ def test_workspace_collection_serialization(self): workspace_collection_model_json2 = workspace_collection_model.to_dict() assert workspace_collection_model_json2 == workspace_collection_model_json -class TestModel_WorkspaceSystemSettings(): + +class TestModel_WorkspaceCounts: + """ + Test Class for WorkspaceCounts + """ + + def test_workspace_counts_serialization(self): + """ + Test serialization/deserialization for WorkspaceCounts + """ + + # Construct a json representation of a WorkspaceCounts model + workspace_counts_model_json = {} + workspace_counts_model_json['intent'] = 38 + workspace_counts_model_json['entity'] = 38 + workspace_counts_model_json['node'] = 38 + + # Construct a model instance of WorkspaceCounts by calling from_dict on the json representation + workspace_counts_model = WorkspaceCounts.from_dict(workspace_counts_model_json) + assert workspace_counts_model != False + + # Construct a model instance of WorkspaceCounts by calling from_dict on the json representation + workspace_counts_model_dict = WorkspaceCounts.from_dict(workspace_counts_model_json).__dict__ + workspace_counts_model2 = WorkspaceCounts(**workspace_counts_model_dict) + + # Verify the model instances are equivalent + assert workspace_counts_model == workspace_counts_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_counts_model_json2 = workspace_counts_model.to_dict() + assert workspace_counts_model_json2 == workspace_counts_model_json + + +class TestModel_WorkspaceSystemSettings: """ Test Class for WorkspaceSystemSettings """ @@ -10864,10 +11760,10 @@ def test_workspace_system_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -10876,21 +11772,25 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'testString' + # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model_json['human_agent_assist'] = {} + workspace_system_settings_model_json['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model_json['spelling_suggestions'] = False workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model_json['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model_json['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model_json['foo'] = 'testString' # Construct a model instance of WorkspaceSystemSettings by calling from_dict on the json representation @@ -10916,9 +11816,10 @@ def test_workspace_system_settings_serialization(self): expected_dict = {'foo': 'testString'} workspace_system_settings_model.set_properties(expected_dict) actual_dict = workspace_system_settings_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() -class TestModel_WorkspaceSystemSettingsDisambiguation(): + +class TestModel_WorkspaceSystemSettingsDisambiguation: """ Test Class for WorkspaceSystemSettingsDisambiguation """ @@ -10953,7 +11854,38 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json -class TestModel_WorkspaceSystemSettingsOffTopic(): + +class TestModel_WorkspaceSystemSettingsNlp: + """ + Test Class for WorkspaceSystemSettingsNlp + """ + + def test_workspace_system_settings_nlp_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsNlp + """ + + # Construct a json representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model_json = {} + workspace_system_settings_nlp_model_json['model'] = 'testString' + + # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation + workspace_system_settings_nlp_model = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json) + assert workspace_system_settings_nlp_model != False + + # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation + workspace_system_settings_nlp_model_dict = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json).__dict__ + workspace_system_settings_nlp_model2 = WorkspaceSystemSettingsNlp(**workspace_system_settings_nlp_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_nlp_model == workspace_system_settings_nlp_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_nlp_model_json2 = workspace_system_settings_nlp_model.to_dict() + assert workspace_system_settings_nlp_model_json2 == workspace_system_settings_nlp_model_json + + +class TestModel_WorkspaceSystemSettingsOffTopic: """ Test Class for WorkspaceSystemSettingsOffTopic """ @@ -10982,7 +11914,8 @@ def test_workspace_system_settings_off_topic_serialization(self): workspace_system_settings_off_topic_model_json2 = workspace_system_settings_off_topic_model.to_dict() assert workspace_system_settings_off_topic_model_json2 == workspace_system_settings_off_topic_model_json -class TestModel_WorkspaceSystemSettingsSystemEntities(): + +class TestModel_WorkspaceSystemSettingsSystemEntities: """ Test Class for WorkspaceSystemSettingsSystemEntities """ @@ -11011,7 +11944,8 @@ def test_workspace_system_settings_system_entities_serialization(self): workspace_system_settings_system_entities_model_json2 = workspace_system_settings_system_entities_model.to_dict() assert workspace_system_settings_system_entities_model_json2 == workspace_system_settings_system_entities_model_json -class TestModel_WorkspaceSystemSettingsTooling(): + +class TestModel_WorkspaceSystemSettingsTooling: """ Test Class for WorkspaceSystemSettingsTooling """ @@ -11040,7 +11974,8 @@ def test_workspace_system_settings_tooling_serialization(self): workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio """ @@ -11052,7 +11987,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model @@ -11062,7 +11997,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation @@ -11080,7 +12015,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_audio_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_audio_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer """ @@ -11092,16 +12028,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model @@ -11126,7 +12062,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent """ @@ -11138,13 +12075,13 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent model @@ -11171,7 +12108,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe """ @@ -11183,7 +12121,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_seri # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe model @@ -11210,7 +12148,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_seri dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_iframe_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage """ @@ -11222,7 +12161,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model @@ -11249,7 +12188,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_image_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_image_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeOption """ @@ -11261,23 +12201,21 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -11305,14 +12243,14 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -11322,16 +12260,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption model @@ -11358,7 +12296,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_option_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_option_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypePause """ @@ -11370,7 +12309,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypePause model @@ -11395,7 +12334,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_pause_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_pause_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill """ @@ -11407,7 +12347,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill model @@ -11434,7 +12374,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_search_skill_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeText """ @@ -11446,10 +12387,10 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model @@ -11457,7 +12398,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json['response_type'] = 'text' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_dialog_node_output_response_type_text_model_json['selection_policy'] = 'sequential' - dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\n' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\\n' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation @@ -11475,7 +12416,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_text_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_text_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined """ @@ -11487,13 +12429,13 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' - dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation @@ -11511,7 +12453,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_user_defined_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo """ @@ -11523,7 +12466,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo model @@ -11533,7 +12476,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation @@ -11551,7 +12494,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_video_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_video_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio """ @@ -11563,7 +12507,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model @@ -11573,7 +12517,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -11591,7 +12535,8 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -11603,16 +12548,16 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model @@ -11637,7 +12582,8 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -11649,13 +12595,13 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model @@ -11684,7 +12630,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe """ @@ -11696,7 +12643,7 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model @@ -11723,7 +12670,8 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -11735,7 +12683,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model @@ -11762,7 +12710,8 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -11774,23 +12723,21 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -11818,14 +12765,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -11835,16 +12782,16 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model @@ -11871,7 +12818,8 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause: """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -11883,7 +12831,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model @@ -11908,7 +12856,8 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -11920,23 +12869,21 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -11964,14 +12911,14 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -11981,18 +12928,18 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model dialog_suggestion_value_model['intents'] = [runtime_intent_model] dialog_suggestion_value_model['entities'] = [runtime_entity_model] - dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {} + dialog_suggestion_model['output'] = {'anyKey': 'anyValue'} dialog_suggestion_model['dialog_node'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model @@ -12017,7 +12964,8 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -12029,7 +12977,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model @@ -12053,7 +13001,8 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ @@ -12065,13 +13014,13 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -12089,7 +13038,8 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo """ @@ -12101,7 +13051,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model @@ -12111,7 +13061,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 2542016ee..f2ab84821 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2019, 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,13 +17,17 @@ Unit Tests for AssistantV2 """ +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect +import io import json import pytest import re import requests import responses +import tempfile import urllib from ibm_watson.assistant_v2 import * @@ -31,7 +35,7 @@ _service = AssistantV2( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' @@ -45,345 +49,598 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## -# Start of Service: Sessions +# Start of Service: ConversationalSkillProviders ############################################################################## # region -class TestCreateSession(): + +class TestCreateProvider: """ - Test Class for create_session + Test Class for create_provider """ @responses.activate - def test_create_session_all_params(self): + def test_create_provider_all_params(self): """ - create_session() + create_provider() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions') - mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + url = preprocess_url('/v2/providers') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model # Set up parameter values - assistant_id = 'testString' + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model # Invoke method - response = _service.create_session( - assistant_id, - headers={} + response = _service.create_provider( + provider_id, + specification, + private, + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 201 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['provider_id'] == 'testString' + assert req_body['specification'] == provider_specification_model + assert req_body['private'] == provider_private_model - def test_create_session_all_params_with_retries(self): - # Enable retries and run test_create_session_all_params. + def test_create_provider_all_params_with_retries(self): + # Enable retries and run test_create_provider_all_params. _service.enable_retries() - self.test_create_session_all_params() + self.test_create_provider_all_params() - # Disable retries and run test_create_session_all_params. + # Disable retries and run test_create_provider_all_params. _service.disable_retries() - self.test_create_session_all_params() + self.test_create_provider_all_params() @responses.activate - def test_create_session_value_error(self): + def test_create_provider_value_error(self): """ - test_create_session_value_error() + test_create_provider_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions') - mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + url = preprocess_url('/v2/providers') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model # Set up parameter values - assistant_id = 'testString' + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, + "provider_id": provider_id, + "specification": specification, + "private": private, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_session(**req_copy) - + _service.create_provider(**req_copy) - def test_create_session_value_error_with_retries(self): - # Enable retries and run test_create_session_value_error. + def test_create_provider_value_error_with_retries(self): + # Enable retries and run test_create_provider_value_error. _service.enable_retries() - self.test_create_session_value_error() + self.test_create_provider_value_error() - # Disable retries and run test_create_session_value_error. + # Disable retries and run test_create_provider_value_error. _service.disable_retries() - self.test_create_session_value_error() + self.test_create_provider_value_error() + -class TestDeleteSession(): +class TestListProviders: """ - Test Class for delete_session + Test Class for list_providers """ @responses.activate - def test_delete_session_all_params(self): + def test_list_providers_all_params(self): """ - delete_session() + list_providers() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString') - responses.add(responses.DELETE, - url, - status=200) + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - assistant_id = 'testString' - session_id = 'testString' + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False # Invoke method - response = _service.delete_session( - assistant_id, - session_id, - headers={} + response = _service.list_providers( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_delete_session_all_params_with_retries(self): - # Enable retries and run test_delete_session_all_params. + def test_list_providers_all_params_with_retries(self): + # Enable retries and run test_list_providers_all_params. _service.enable_retries() - self.test_delete_session_all_params() + self.test_list_providers_all_params() - # Disable retries and run test_delete_session_all_params. + # Disable retries and run test_list_providers_all_params. _service.disable_retries() - self.test_delete_session_all_params() + self.test_list_providers_all_params() @responses.activate - def test_delete_session_value_error(self): + def test_list_providers_required_params(self): """ - test_delete_session_value_error() + test_list_providers_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString') - responses.add(responses.DELETE, - url, - status=200) + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Set up parameter values - assistant_id = 'testString' - session_id = 'testString' + # Invoke method + response = _service.list_providers() + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_providers_required_params_with_retries(self): + # Enable retries and run test_list_providers_required_params. + _service.enable_retries() + self.test_list_providers_required_params() + + # Disable retries and run test_list_providers_required_params. + _service.disable_retries() + self.test_list_providers_required_params() + + @responses.activate + def test_list_providers_value_error(self): + """ + test_list_providers_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, - "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_session(**req_copy) - + _service.list_providers(**req_copy) - def test_delete_session_value_error_with_retries(self): - # Enable retries and run test_delete_session_value_error. + def test_list_providers_value_error_with_retries(self): + # Enable retries and run test_list_providers_value_error. _service.enable_retries() - self.test_delete_session_value_error() + self.test_list_providers_value_error() - # Disable retries and run test_delete_session_value_error. + # Disable retries and run test_list_providers_value_error. _service.disable_retries() - self.test_delete_session_value_error() - -# endregion -############################################################################## -# End of Service: Sessions -############################################################################## + self.test_list_providers_value_error() -############################################################################## -# Start of Service: Message -############################################################################## -# region -class TestMessage(): +class TestUpdateProvider: """ - Test Class for message + Test Class for update_provider """ @responses.activate - def test_message_all_params(self): + def test_update_provider_all_params(self): """ - message() + update_provider() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/providers/testString') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a dict representation of a RuntimeIntent model - runtime_intent_model = {} - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model - # Construct a dict representation of a CaptureGroup model - capture_group_model = {} - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model - # Construct a dict representation of a RuntimeEntityInterpretation model - runtime_entity_interpretation_model = {} - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Invoke method + response = _service.update_provider( + provider_id, + specification, + private, + headers={}, + ) - # Construct a dict representation of a RuntimeEntityAlternative model - runtime_entity_alternative_model = {} - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['specification'] == provider_specification_model + assert req_body['private'] == provider_private_model - # Construct a dict representation of a RuntimeEntityRole model - runtime_entity_role_model = {} - runtime_entity_role_model['type'] = 'date_from' + def test_update_provider_all_params_with_retries(self): + # Enable retries and run test_update_provider_all_params. + _service.enable_retries() + self.test_update_provider_all_params() - # Construct a dict representation of a RuntimeEntity model - runtime_entity_model = {} - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + # Disable retries and run test_update_provider_all_params. + _service.disable_retries() + self.test_update_provider_all_params() - # Construct a dict representation of a MessageInputAttachment model - message_input_attachment_model = {} - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + @responses.activate + def test_update_provider_value_error(self): + """ + test_update_provider_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers/testString') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a dict representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model = {} - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model - # Construct a dict representation of a MessageInputOptions model - message_input_options_model = {} - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model - # Construct a dict representation of a MessageInput model - message_input_model = {} - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "provider_id": provider_id, + "specification": specification, + "private": private, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_provider(**req_copy) - # Construct a dict representation of a MessageContextGlobalSystem model - message_context_global_system_model = {} - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + def test_update_provider_value_error_with_retries(self): + # Enable retries and run test_update_provider_value_error. + _service.enable_retries() + self.test_update_provider_value_error() - # Construct a dict representation of a MessageContextGlobal model - message_context_global_model = {} - message_context_global_model['system'] = message_context_global_system_model + # Disable retries and run test_update_provider_value_error. + _service.disable_retries() + self.test_update_provider_value_error() - # Construct a dict representation of a MessageContextSkillSystem model - message_context_skill_system_model = {} - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkill model - message_context_skill_model = {} - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model +# endregion +############################################################################## +# End of Service: ConversationalSkillProviders +############################################################################## - # Construct a dict representation of a MessageContext model - message_context_model = {} - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } +############################################################################## +# Start of Service: Assistants +############################################################################## +# region + + +class TestCreateAssistant: + """ + Test Class for create_assistant + """ + + @responses.activate + def test_create_assistant_all_params(self): + """ + create_assistant() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - assistant_id = 'testString' - session_id = 'testString' - input = message_input_model - context = message_context_model - user_id = 'testString' + language = 'testString' + name = 'testString' + description = 'testString' # Invoke method - response = _service.message( - assistant_id, - session_id, - input=input, - context=context, - user_id=user_id, - headers={} + response = _service.create_assistant( + language=language, + name=name, + description=description, + headers={}, ) # Check for correct operation @@ -391,314 +648,262 @@ def test_message_all_params(self): assert response.status_code == 200 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == message_input_model - assert req_body['context'] == message_context_model - assert req_body['user_id'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' - def test_message_all_params_with_retries(self): - # Enable retries and run test_message_all_params. + def test_create_assistant_all_params_with_retries(self): + # Enable retries and run test_create_assistant_all_params. _service.enable_retries() - self.test_message_all_params() + self.test_create_assistant_all_params() - # Disable retries and run test_message_all_params. + # Disable retries and run test_create_assistant_all_params. _service.disable_retries() - self.test_message_all_params() + self.test_create_assistant_all_params() @responses.activate - def test_message_required_params(self): + def test_create_assistant_required_params(self): """ - test_message_required_params() + test_create_assistant_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - assistant_id = 'testString' - session_id = 'testString' + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method - response = _service.message( - assistant_id, - session_id, - headers={} - ) + response = _service.create_assistant() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - def test_message_required_params_with_retries(self): - # Enable retries and run test_message_required_params. + def test_create_assistant_required_params_with_retries(self): + # Enable retries and run test_create_assistant_required_params. _service.enable_retries() - self.test_message_required_params() + self.test_create_assistant_required_params() - # Disable retries and run test_message_required_params. + # Disable retries and run test_create_assistant_required_params. _service.disable_retries() - self.test_message_required_params() + self.test_create_assistant_required_params() @responses.activate - def test_message_value_error(self): + def test_create_assistant_value_error(self): """ - test_message_value_error() + test_create_assistant_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - assistant_id = 'testString' - session_id = 'testString' + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, - "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.message(**req_copy) + _service.create_assistant(**req_copy) - - def test_message_value_error_with_retries(self): - # Enable retries and run test_message_value_error. + def test_create_assistant_value_error_with_retries(self): + # Enable retries and run test_create_assistant_value_error. _service.enable_retries() - self.test_message_value_error() + self.test_create_assistant_value_error() - # Disable retries and run test_message_value_error. + # Disable retries and run test_create_assistant_value_error. _service.disable_retries() - self.test_message_value_error() + self.test_create_assistant_value_error() -class TestMessageStateless(): + +class TestListAssistants: """ - Test Class for message_stateless + Test Class for list_assistants """ @responses.activate - def test_message_stateless_all_params(self): + def test_list_assistants_all_params(self): """ - message_stateless() + list_assistants() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a RuntimeIntent model - runtime_intent_model = {} - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - # Construct a dict representation of a CaptureGroup model - capture_group_model = {} - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - # Construct a dict representation of a RuntimeEntityInterpretation model - runtime_entity_interpretation_model = {} - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - # Construct a dict representation of a RuntimeEntityAlternative model - runtime_entity_alternative_model = {} - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - # Construct a dict representation of a RuntimeEntityRole model - runtime_entity_role_model = {} - runtime_entity_role_model['type'] = 'date_from' + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a dict representation of a RuntimeEntity model - runtime_entity_model = {} - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + # Set up parameter values + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False - # Construct a dict representation of a MessageInputAttachment model - message_input_attachment_model = {} - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Invoke method + response = _service.list_assistants( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={}, + ) - # Construct a dict representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model = {} - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Construct a dict representation of a MessageInputOptionsStateless model - message_input_options_stateless_model = {} - message_input_options_stateless_model['restart'] = False - message_input_options_stateless_model['alternate_intents'] = False - message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = False - - # Construct a dict representation of a MessageInputStateless model - message_input_stateless_model = {} - message_input_stateless_model['message_type'] = 'text' - message_input_stateless_model['text'] = 'testString' - message_input_stateless_model['intents'] = [runtime_intent_model] - message_input_stateless_model['entities'] = [runtime_entity_model] - message_input_stateless_model['suggestion_id'] = 'testString' - message_input_stateless_model['attachments'] = [message_input_attachment_model] - message_input_stateless_model['options'] = message_input_options_stateless_model + def test_list_assistants_all_params_with_retries(self): + # Enable retries and run test_list_assistants_all_params. + _service.enable_retries() + self.test_list_assistants_all_params() - # Construct a dict representation of a MessageContextGlobalSystem model - message_context_global_system_model = {} - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Disable retries and run test_list_assistants_all_params. + _service.disable_retries() + self.test_list_assistants_all_params() - # Construct a dict representation of a MessageContextGlobalStateless model - message_context_global_stateless_model = {} - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + @responses.activate + def test_list_assistants_required_params(self): + """ + test_list_assistants_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a dict representation of a MessageContextSkillSystem model - message_context_skill_system_model = {} - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Invoke method + response = _service.list_assistants() - # Construct a dict representation of a MessageContextSkill model - message_context_skill_model = {} - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - # Construct a dict representation of a MessageContextStateless model - message_context_stateless_model = {} - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {} - message_context_stateless_model['integrations'] = { 'foo': 'bar' } + def test_list_assistants_required_params_with_retries(self): + # Enable retries and run test_list_assistants_required_params. + _service.enable_retries() + self.test_list_assistants_required_params() - # Set up parameter values - assistant_id = 'testString' - input = message_input_stateless_model - context = message_context_stateless_model - user_id = 'testString' + # Disable retries and run test_list_assistants_required_params. + _service.disable_retries() + self.test_list_assistants_required_params() - # Invoke method - response = _service.message_stateless( - assistant_id, - input=input, - context=context, - user_id=user_id, - headers={} + @responses.activate + def test_list_assistants_value_error(self): + """ + test_list_assistants_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, ) - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == message_input_stateless_model - assert req_body['context'] == message_context_stateless_model - assert req_body['user_id'] == 'testString' + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_assistants(**req_copy) - def test_message_stateless_all_params_with_retries(self): - # Enable retries and run test_message_stateless_all_params. + def test_list_assistants_value_error_with_retries(self): + # Enable retries and run test_list_assistants_value_error. _service.enable_retries() - self.test_message_stateless_all_params() + self.test_list_assistants_value_error() - # Disable retries and run test_message_stateless_all_params. + # Disable retries and run test_list_assistants_value_error. _service.disable_retries() - self.test_message_stateless_all_params() + self.test_list_assistants_value_error() + + +class TestDeleteAssistant: + """ + Test Class for delete_assistant + """ @responses.activate - def test_message_stateless_required_params(self): + def test_delete_assistant_all_params(self): """ - test_message_stateless_required_params() + delete_assistant() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/assistants/testString') + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' # Invoke method - response = _service.message_stateless( + response = _service.delete_assistant( assistant_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - def test_message_stateless_required_params_with_retries(self): - # Enable retries and run test_message_stateless_required_params. + def test_delete_assistant_all_params_with_retries(self): + # Enable retries and run test_delete_assistant_all_params. _service.enable_retries() - self.test_message_stateless_required_params() + self.test_delete_assistant_all_params() - # Disable retries and run test_message_stateless_required_params. + # Disable retries and run test_delete_assistant_all_params. _service.disable_retries() - self.test_message_stateless_required_params() + self.test_delete_assistant_all_params() @responses.activate - def test_message_stateless_value_error(self): + def test_delete_assistant_value_error(self): """ - test_message_stateless_value_error() + test_delete_assistant_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/assistants/testString') + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -708,434 +913,295 @@ def test_message_stateless_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.message_stateless(**req_copy) - + _service.delete_assistant(**req_copy) - def test_message_stateless_value_error_with_retries(self): - # Enable retries and run test_message_stateless_value_error. + def test_delete_assistant_value_error_with_retries(self): + # Enable retries and run test_delete_assistant_value_error. _service.enable_retries() - self.test_message_stateless_value_error() + self.test_delete_assistant_value_error() - # Disable retries and run test_message_stateless_value_error. + # Disable retries and run test_delete_assistant_value_error. _service.disable_retries() - self.test_message_stateless_value_error() + self.test_delete_assistant_value_error() + # endregion ############################################################################## -# End of Service: Message +# End of Service: Assistants ############################################################################## ############################################################################## -# Start of Service: BulkClassify +# Start of Service: Sessions ############################################################################## # region -class TestBulkClassify(): + +class TestCreateSession: """ - Test Class for bulk_classify + Test Class for create_session """ @responses.activate - def test_bulk_classify_all_params(self): + def test_create_session_all_params(self): """ - bulk_classify() + create_session() """ # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions') + mock_response = '{"session_id": "session_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' # Set up parameter values - skill_id = 'testString' - input = [bulk_classify_utterance_model] + assistant_id = 'testString' + environment_id = 'testString' + analytics = request_analytics_model # Invoke method - response = _service.bulk_classify( - skill_id, - input=input, - headers={} + response = _service.create_session( + assistant_id, + environment_id, + analytics=analytics, + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == [bulk_classify_utterance_model] + assert req_body['analytics'] == request_analytics_model - def test_bulk_classify_all_params_with_retries(self): - # Enable retries and run test_bulk_classify_all_params. + def test_create_session_all_params_with_retries(self): + # Enable retries and run test_create_session_all_params. _service.enable_retries() - self.test_bulk_classify_all_params() + self.test_create_session_all_params() - # Disable retries and run test_bulk_classify_all_params. + # Disable retries and run test_create_session_all_params. _service.disable_retries() - self.test_bulk_classify_all_params() + self.test_create_session_all_params() @responses.activate - def test_bulk_classify_required_params(self): + def test_create_session_required_params(self): """ - test_bulk_classify_required_params() + test_create_session_required_params() """ # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions') + mock_response = '{"session_id": "session_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values - skill_id = 'testString' + assistant_id = 'testString' + environment_id = 'testString' # Invoke method - response = _service.bulk_classify( - skill_id, - headers={} + response = _service.create_session( + assistant_id, + environment_id, + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 - def test_bulk_classify_required_params_with_retries(self): - # Enable retries and run test_bulk_classify_required_params. + def test_create_session_required_params_with_retries(self): + # Enable retries and run test_create_session_required_params. _service.enable_retries() - self.test_bulk_classify_required_params() + self.test_create_session_required_params() - # Disable retries and run test_bulk_classify_required_params. + # Disable retries and run test_create_session_required_params. _service.disable_retries() - self.test_bulk_classify_required_params() + self.test_create_session_required_params() @responses.activate - def test_bulk_classify_value_error(self): + def test_create_session_value_error(self): """ - test_bulk_classify_value_error() + test_create_session_value_error() """ # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions') + mock_response = '{"session_id": "session_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values - skill_id = 'testString' + assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { - "skill_id": skill_id, + "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.bulk_classify(**req_copy) - + _service.create_session(**req_copy) - def test_bulk_classify_value_error_with_retries(self): - # Enable retries and run test_bulk_classify_value_error. + def test_create_session_value_error_with_retries(self): + # Enable retries and run test_create_session_value_error. _service.enable_retries() - self.test_bulk_classify_value_error() + self.test_create_session_value_error() - # Disable retries and run test_bulk_classify_value_error. + # Disable retries and run test_create_session_value_error. _service.disable_retries() - self.test_bulk_classify_value_error() - -# endregion -############################################################################## -# End of Service: BulkClassify -############################################################################## + self.test_create_session_value_error() -############################################################################## -# Start of Service: Logs -############################################################################## -# region -class TestListLogs(): +class TestDeleteSession: """ - Test Class for list_logs + Test Class for delete_session """ @responses.activate - def test_list_logs_all_params(self): + def test_delete_session_all_params(self): """ - list_logs() + delete_session() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - assistant_id = 'testString' - sort = 'testString' - filter = 'testString' - page_limit = 38 - cursor = 'testString' - - # Invoke method - response = _service.list_logs( - assistant_id, - sort=sort, - filter=filter, - page_limit=page_limit, - cursor=cursor, - headers={} + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString') + responses.add( + responses.DELETE, + url, + status=200, ) - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'sort={}'.format(sort) in query_string - assert 'filter={}'.format(filter) in query_string - assert 'page_limit={}'.format(page_limit) in query_string - assert 'cursor={}'.format(cursor) in query_string - - def test_list_logs_all_params_with_retries(self): - # Enable retries and run test_list_logs_all_params. - _service.enable_retries() - self.test_list_logs_all_params() - - # Disable retries and run test_list_logs_all_params. - _service.disable_retries() - self.test_list_logs_all_params() - - @responses.activate - def test_list_logs_required_params(self): - """ - test_list_logs_required_params() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' # Invoke method - response = _service.list_logs( + response = _service.delete_session( assistant_id, - headers={} + environment_id, + session_id, + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - def test_list_logs_required_params_with_retries(self): - # Enable retries and run test_list_logs_required_params. + def test_delete_session_all_params_with_retries(self): + # Enable retries and run test_delete_session_all_params. _service.enable_retries() - self.test_list_logs_required_params() + self.test_delete_session_all_params() - # Disable retries and run test_list_logs_required_params. + # Disable retries and run test_delete_session_all_params. _service.disable_retries() - self.test_list_logs_required_params() + self.test_delete_session_all_params() @responses.activate - def test_list_logs_value_error(self): + def test_delete_session_value_error(self): """ - test_list_logs_value_error() + test_delete_session_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString') + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, + "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_logs(**req_copy) - + _service.delete_session(**req_copy) - def test_list_logs_value_error_with_retries(self): - # Enable retries and run test_list_logs_value_error. + def test_delete_session_value_error_with_retries(self): + # Enable retries and run test_delete_session_value_error. _service.enable_retries() - self.test_list_logs_value_error() + self.test_delete_session_value_error() - # Disable retries and run test_list_logs_value_error. + # Disable retries and run test_delete_session_value_error. _service.disable_retries() - self.test_list_logs_value_error() + self.test_delete_session_value_error() + # endregion ############################################################################## -# End of Service: Logs +# End of Service: Sessions ############################################################################## ############################################################################## -# Start of Service: UserData +# Start of Service: Message ############################################################################## # region -class TestDeleteUserData(): + +class TestMessage: """ - Test Class for delete_user_data + Test Class for message """ @responses.activate - def test_delete_user_data_all_params(self): + def test_message_all_params(self): """ - delete_user_data() + message() """ # Set up mock - url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=202) - - # Set up parameter values - customer_id = 'testString' - - # Invoke method - response = _service.delete_user_data( - customer_id, - headers={} + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, ) - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string - - def test_delete_user_data_all_params_with_retries(self): - # Enable retries and run test_delete_user_data_all_params. - _service.enable_retries() - self.test_delete_user_data_all_params() - - # Disable retries and run test_delete_user_data_all_params. - _service.disable_retries() - self.test_delete_user_data_all_params() - - @responses.activate - def test_delete_user_data_value_error(self): - """ - test_delete_user_data_value_error() - """ - # Set up mock - url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=202) - - # Set up parameter values - customer_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "customer_id": customer_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) - - - def test_delete_user_data_value_error_with_retries(self): - # Enable retries and run test_delete_user_data_value_error. - _service.enable_retries() - self.test_delete_user_data_value_error() - - # Disable retries and run test_delete_user_data_value_error. - _service.disable_retries() - self.test_delete_user_data_value_error() - -# endregion -############################################################################## -# End of Service: UserData -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_AgentAvailabilityMessage(): - """ - Test Class for AgentAvailabilityMessage - """ - - def test_agent_availability_message_serialization(self): - """ - Test serialization/deserialization for AgentAvailabilityMessage - """ - - # Construct a json representation of a AgentAvailabilityMessage model - agent_availability_message_model_json = {} - agent_availability_message_model_json['message'] = 'testString' - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) - assert agent_availability_message_model != False - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ - agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) - - # Verify the model instances are equivalent - assert agent_availability_message_model == agent_availability_message_model2 - - # Convert model instance back to dict and verify no loss of data - agent_availability_message_model_json2 = agent_availability_message_model.to_dict() - assert agent_availability_message_model_json2 == agent_availability_message_model_json - -class TestModel_BulkClassifyOutput(): - """ - Test Class for BulkClassifyOutput - """ - - def test_bulk_classify_output_serialization(self): - """ - Test serialization/deserialization for BulkClassifyOutput - """ - - # Construct dict forms of any model objects needed in order to build this model. - - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -1163,14 +1229,17 @@ def test_bulk_classify_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -1179,404 +1248,10817 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Construct a json representation of a BulkClassifyOutput model - bulk_classify_output_model_json = {} - bulk_classify_output_model_json['input'] = bulk_classify_utterance_model - bulk_classify_output_model_json['entities'] = [runtime_entity_model] - bulk_classify_output_model_json['intents'] = [runtime_intent_model] + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) - assert bulk_classify_output_model != False + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' + + # Invoke method + response = _service.message( + assistant_id, + environment_id, + session_id, + input=input, + context=context, + user_id=user_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' + + def test_message_all_params_with_retries(self): + # Enable retries and run test_message_all_params. + _service.enable_retries() + self.test_message_all_params() + + # Disable retries and run test_message_all_params. + _service.disable_retries() + self.test_message_all_params() + + @responses.activate + def test_message_required_params(self): + """ + test_message_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' + + # Invoke method + response = _service.message( + assistant_id, + environment_id, + session_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_message_required_params_with_retries(self): + # Enable retries and run test_message_required_params. + _service.enable_retries() + self.test_message_required_params() + + # Disable retries and run test_message_required_params. + _service.disable_retries() + self.test_message_required_params() + + @responses.activate + def test_message_value_error(self): + """ + test_message_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + "session_id": session_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.message(**req_copy) + + def test_message_value_error_with_retries(self): + # Enable retries and run test_message_value_error. + _service.enable_retries() + self.test_message_value_error() + + # Disable retries and run test_message_value_error. + _service.disable_retries() + self.test_message_value_error() + + +class TestMessageStateless: + """ + Test Class for message_stateless + """ + + @responses.activate + def test_message_stateless_all_params(self): + """ + message_stateless() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a StatelessMessageInputOptions model + stateless_message_input_options_model = {} + stateless_message_input_options_model['restart'] = False + stateless_message_input_options_model['alternate_intents'] = False + stateless_message_input_options_model['async_callout'] = False + stateless_message_input_options_model['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model['debug'] = False + + # Construct a dict representation of a StatelessMessageInput model + stateless_message_input_model = {} + stateless_message_input_model['message_type'] = 'text' + stateless_message_input_model['text'] = 'testString' + stateless_message_input_model['intents'] = [runtime_intent_model] + stateless_message_input_model['entities'] = [runtime_entity_model] + stateless_message_input_model['suggestion_id'] = 'testString' + stateless_message_input_model['attachments'] = [message_input_attachment_model] + stateless_message_input_model['analytics'] = request_analytics_model + stateless_message_input_model['options'] = stateless_message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a dict representation of a StatelessMessageContextGlobal model + stateless_message_context_global_model = {} + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a StatelessMessageContextSkillsActionsSkill model + stateless_message_context_skills_actions_skill_model = {} + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a StatelessMessageContextSkills model + stateless_message_context_skills_model = {} + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a dict representation of a StatelessMessageContext model + stateless_message_context_model = {} + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + input = stateless_message_input_model + context = stateless_message_context_model + user_id = 'testString' + + # Invoke method + response = _service.message_stateless( + assistant_id, + environment_id, + input=input, + context=context, + user_id=user_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == stateless_message_input_model + assert req_body['context'] == stateless_message_context_model + assert req_body['user_id'] == 'testString' + + def test_message_stateless_all_params_with_retries(self): + # Enable retries and run test_message_stateless_all_params. + _service.enable_retries() + self.test_message_stateless_all_params() + + # Disable retries and run test_message_stateless_all_params. + _service.disable_retries() + self.test_message_stateless_all_params() + + @responses.activate + def test_message_stateless_required_params(self): + """ + test_message_stateless_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Invoke method + response = _service.message_stateless( + assistant_id, + environment_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_message_stateless_required_params_with_retries(self): + # Enable retries and run test_message_stateless_required_params. + _service.enable_retries() + self.test_message_stateless_required_params() + + # Disable retries and run test_message_stateless_required_params. + _service.disable_retries() + self.test_message_stateless_required_params() + + @responses.activate + def test_message_stateless_value_error(self): + """ + test_message_stateless_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.message_stateless(**req_copy) + + def test_message_stateless_value_error_with_retries(self): + # Enable retries and run test_message_stateless_value_error. + _service.enable_retries() + self.test_message_stateless_value_error() + + # Disable retries and run test_message_stateless_value_error. + _service.disable_retries() + self.test_message_stateless_value_error() + + +# endregion +############################################################################## +# End of Service: Message +############################################################################## + +############################################################################## +# Start of Service: MessageStream +############################################################################## +# region + + +class TestMessageStream: + """ + Test Class for message_stream + """ + + @responses.activate + def test_message_stream_all_params(self): + """ + message_stream() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' + + # Invoke method + response = _service.message_stream( + assistant_id, + environment_id, + session_id, + input=input, + context=context, + user_id=user_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' + + def test_message_stream_all_params_with_retries(self): + # Enable retries and run test_message_stream_all_params. + _service.enable_retries() + self.test_message_stream_all_params() + + # Disable retries and run test_message_stream_all_params. + _service.disable_retries() + self.test_message_stream_all_params() + + @responses.activate + def test_message_stream_required_params(self): + """ + test_message_stream_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' + + # Invoke method + response = _service.message_stream( + assistant_id, + environment_id, + session_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_message_stream_required_params_with_retries(self): + # Enable retries and run test_message_stream_required_params. + _service.enable_retries() + self.test_message_stream_required_params() + + # Disable retries and run test_message_stream_required_params. + _service.disable_retries() + self.test_message_stream_required_params() + + @responses.activate + def test_message_stream_value_error(self): + """ + test_message_stream_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + "session_id": session_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.message_stream(**req_copy) + + def test_message_stream_value_error_with_retries(self): + # Enable retries and run test_message_stream_value_error. + _service.enable_retries() + self.test_message_stream_value_error() + + # Disable retries and run test_message_stream_value_error. + _service.disable_retries() + self.test_message_stream_value_error() + + +class TestMessageStreamStateless: + """ + Test Class for message_stream_stateless + """ + + @responses.activate + def test_message_stream_stateless_all_params(self): + """ + message_stream_stateless() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' + + # Invoke method + response = _service.message_stream_stateless( + assistant_id, + environment_id, + input=input, + context=context, + user_id=user_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' + + def test_message_stream_stateless_all_params_with_retries(self): + # Enable retries and run test_message_stream_stateless_all_params. + _service.enable_retries() + self.test_message_stream_stateless_all_params() + + # Disable retries and run test_message_stream_stateless_all_params. + _service.disable_retries() + self.test_message_stream_stateless_all_params() + + @responses.activate + def test_message_stream_stateless_required_params(self): + """ + test_message_stream_stateless_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Invoke method + response = _service.message_stream_stateless( + assistant_id, + environment_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_message_stream_stateless_required_params_with_retries(self): + # Enable retries and run test_message_stream_stateless_required_params. + _service.enable_retries() + self.test_message_stream_stateless_required_params() + + # Disable retries and run test_message_stream_stateless_required_params. + _service.disable_retries() + self.test_message_stream_stateless_required_params() + + @responses.activate + def test_message_stream_stateless_value_error(self): + """ + test_message_stream_stateless_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.message_stream_stateless(**req_copy) + + def test_message_stream_stateless_value_error_with_retries(self): + # Enable retries and run test_message_stream_stateless_value_error. + _service.enable_retries() + self.test_message_stream_stateless_value_error() + + # Disable retries and run test_message_stream_stateless_value_error. + _service.disable_retries() + self.test_message_stream_stateless_value_error() + + +# endregion +############################################################################## +# End of Service: MessageStream +############################################################################## + +############################################################################## +# Start of Service: BulkClassify +############################################################################## +# region + + +class TestBulkClassify: + """ + Test Class for bulk_classify + """ + + @responses.activate + def test_bulk_classify_all_params(self): + """ + bulk_classify() + """ + # Set up mock + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + + # Set up parameter values + skill_id = 'testString' + input = [bulk_classify_utterance_model] + + # Invoke method + response = _service.bulk_classify( + skill_id, + input, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] + + def test_bulk_classify_all_params_with_retries(self): + # Enable retries and run test_bulk_classify_all_params. + _service.enable_retries() + self.test_bulk_classify_all_params() + + # Disable retries and run test_bulk_classify_all_params. + _service.disable_retries() + self.test_bulk_classify_all_params() + + @responses.activate + def test_bulk_classify_value_error(self): + """ + test_bulk_classify_value_error() + """ + # Set up mock + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + + # Set up parameter values + skill_id = 'testString' + input = [bulk_classify_utterance_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "skill_id": skill_id, + "input": input, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.bulk_classify(**req_copy) + + def test_bulk_classify_value_error_with_retries(self): + # Enable retries and run test_bulk_classify_value_error. + _service.enable_retries() + self.test_bulk_classify_value_error() + + # Disable retries and run test_bulk_classify_value_error. + _service.disable_retries() + self.test_bulk_classify_value_error() + + +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + +############################################################################## +# Start of Service: Logs +############################################################################## +# region + + +class TestListLogs: + """ + Test Class for list_logs + """ + + @responses.activate + def test_list_logs_all_params(self): + """ + list_logs() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + sort = 'testString' + filter = 'testString' + page_limit = 100 + cursor = 'testString' + + # Invoke method + response = _service.list_logs( + assistant_id, + sort=sort, + filter=filter, + page_limit=page_limit, + cursor=cursor, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'sort={}'.format(sort) in query_string + assert 'filter={}'.format(filter) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string + + def test_list_logs_all_params_with_retries(self): + # Enable retries and run test_list_logs_all_params. + _service.enable_retries() + self.test_list_logs_all_params() + + # Disable retries and run test_list_logs_all_params. + _service.disable_retries() + self.test_list_logs_all_params() + + @responses.activate + def test_list_logs_required_params(self): + """ + test_list_logs_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.list_logs( + assistant_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_logs_required_params_with_retries(self): + # Enable retries and run test_list_logs_required_params. + _service.enable_retries() + self.test_list_logs_required_params() + + # Disable retries and run test_list_logs_required_params. + _service.disable_retries() + self.test_list_logs_required_params() + + @responses.activate + def test_list_logs_value_error(self): + """ + test_list_logs_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_