From bf5a91cdc7998390510be48bf87a19a6a2651d68 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 10:56:14 -0600 Subject: [PATCH 01/15] try out action to commit sdk build --- .github/workflows/build-sdk.yml | 58 ++++++++++++++++++++++++++++----- .gitignore.pub | 2 ++ 2 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 .gitignore.pub diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index be6f067..ec1797b 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -8,24 +8,64 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v2 - - - name: Set up Node.js - uses: actions/setup-node@v2 + uses: actions/checkout@v4 with: - node-version: 14 + repository: ${{ github.event.pull_request.head.repo.full_name }} + ref: ${{ github.event.pull_request.head.ref }} + + # - name: Set up Node.js + # uses: actions/setup-node@v2 + # with: + # node-version: 14 - - name: Execute merge.sh + - name: Merge the OpenAPI Specs run: | chmod +x merge.sh # Make the script executable ./merge.sh continue-on-error: false # Stop the workflow if merge.sh returns a non-zero exit code - - name: Execute build-sdk.sh + - name: Build SDK from OpenApi Spec run: | chmod +x build-sdk.sh # Make the script executable ./build-sdk.sh continue-on-error: false # Stop the workflow if build-sdk.sh returns a non-zero exit code - - name: Check for errors - run: exit 0 # This step is here to explicitly check the exit code of the previous step + - name: Swith to publish .gitignore + run: | + cp .gitignore .gitignore.local + cp .gitignore.pub .gitignore + continue-on-error: false + + - name: Commit SDK updates + uses: EndBug/add-and-commit@v9 + with: + # The arguments for the `git add` command (see the paragraph below for more info) + # Default: '.' + add: 'open-api-spec.yml guard-rails-api-client' + + # The name of the user that will be displayed as the author of the commit. + # Default: depends on the default_author input + author_name: ${{ github.event.sender.name }} + + # The email of the user that will be displayed as the author of the commit. + # Default: depends on the default_author input + author_email: ${{ github.event.sender.email }} + + # The message for the commit. + # Default: 'Commit from GitHub Actions (name of the workflow)' + message: 'update generated sdk' + + # If this input is set, the action will push the commit to a new branch with this name. + # Default: '' + new_branch: custom-new-branch + + # The way the action should handle pathspec errors from the add and remove commands. Three options are available: + # - ignore -> errors will be logged but the step won't fail + # - exitImmediately -> the action will stop right away, and the step will fail + # - exitAtEnd -> the action will go on, every pathspec error will be logged at the end, the step will fail. + # Default: ignore + pathspec_error_handling: exitAtEnd + + # Whether to push the commit and, if any, its tags to the repo. It can also be used to set the git push arguments (see the paragraph below for more info) + # Default: true + push: true diff --git a/.gitignore.pub b/.gitignore.pub new file mode 100644 index 0000000..99971d7 --- /dev/null +++ b/.gitignore.pub @@ -0,0 +1,2 @@ +.venv +.ruff_cache \ No newline at end of file From 6d7ef0a9b59c125d3e06f28e35c038cc24fbdb43 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 10:57:45 -0600 Subject: [PATCH 02/15] only run on PR against main --- .github/workflows/build-sdk.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index ec1797b..e548230 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -1,6 +1,9 @@ name: Build SDK -on: [push, pull_request] +on: + pull_request: + branches: [ main ] + workflow_dispatch: jobs: build: From 056ddc3f544000dae43761c4468d36889f5b9ddc Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 10:59:08 -0600 Subject: [PATCH 03/15] no new branch --- .github/workflows/build-sdk.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index e548230..a734f37 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -58,10 +58,6 @@ jobs: # Default: 'Commit from GitHub Actions (name of the workflow)' message: 'update generated sdk' - # If this input is set, the action will push the commit to a new branch with this name. - # Default: '' - new_branch: custom-new-branch - # The way the action should handle pathspec errors from the add and remove commands. Three options are available: # - ignore -> errors will be logged but the step won't fail # - exitImmediately -> the action will stop right away, and the step will fail From c985d3377f0a8bce932ec808816902777eaa0f90 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:05:40 -0600 Subject: [PATCH 04/15] debug event structure since it's not fully published anywhere --- .github/workflows/build-sdk.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index a734f37..2e07b0b 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -37,6 +37,9 @@ jobs: run: | cp .gitignore .gitignore.local cp .gitignore.pub .gitignore + + echo author_name ${{ github.event.sender.name }} + echo author_email ${{ github.event.sender.email }} continue-on-error: false - name: Commit SDK updates From 4cded44e60ac35b7354ce80e57c513c3a17c9878 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:06:46 -0600 Subject: [PATCH 05/15] try user from pull request --- .github/workflows/build-sdk.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 2e07b0b..7ca43cf 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -38,8 +38,8 @@ jobs: cp .gitignore .gitignore.local cp .gitignore.pub .gitignore - echo author_name ${{ github.event.sender.name }} - echo author_email ${{ github.event.sender.email }} + echo author_name ${{ github.event.pull_request.user.name }} + echo author_email ${{ github.event.pull_request.user.email }} continue-on-error: false - name: Commit SDK updates @@ -51,11 +51,11 @@ jobs: # The name of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - author_name: ${{ github.event.sender.name }} + author_name: ${{ github.event.pull_request.user.name }} # The email of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - author_email: ${{ github.event.sender.email }} + author_email: ${{ github.event.pull_request.user.email }} # The message for the commit. # Default: 'Commit from GitHub Actions (name of the workflow)' From 9ff928c87d638a445319081234377dafcef8e19c Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:08:00 -0600 Subject: [PATCH 06/15] try not setting author --- .github/workflows/build-sdk.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 7ca43cf..afd743f 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -51,11 +51,11 @@ jobs: # The name of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - author_name: ${{ github.event.pull_request.user.name }} + # author_name: ${{ github.event.pull_request.user.name }} # The email of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - author_email: ${{ github.event.pull_request.user.email }} + # author_email: ${{ github.event.pull_request.user.email }} # The message for the commit. # Default: 'Commit from GitHub Actions (name of the workflow)' From 060dd212f23894851fa739a9e37829326351a0fd Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:12:57 -0600 Subject: [PATCH 07/15] try accessing git config --- .github/workflows/build-sdk.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index afd743f..720086e 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -38,8 +38,7 @@ jobs: cp .gitignore .gitignore.local cp .gitignore.pub .gitignore - echo author_name ${{ github.event.pull_request.user.name }} - echo author_email ${{ github.event.pull_request.user.email }} + echo "user $(git config user.name)" continue-on-error: false - name: Commit SDK updates From f6a579a9938385364eac8e1a55d4d80080f7fa63 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:16:10 -0600 Subject: [PATCH 08/15] try to echo user --- .github/workflows/build-sdk.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 720086e..6135084 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -38,7 +38,7 @@ jobs: cp .gitignore .gitignore.local cp .gitignore.pub .gitignore - echo "user $(git config user.name)" + echo "${{ github.event.pull_request.user }}" continue-on-error: false - name: Commit SDK updates @@ -50,11 +50,11 @@ jobs: # The name of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - # author_name: ${{ github.event.pull_request.user.name }} + author_name: ${{ github.event.pull_request.user.name }} # The email of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - # author_email: ${{ github.event.pull_request.user.email }} + author_email: ${{ github.event.pull_request.user.email }} # The message for the commit. # Default: 'Commit from GitHub Actions (name of the workflow)' From 26aa824bd2469fd0512ebf96f6e0ca43b124ae12 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:19:02 -0600 Subject: [PATCH 09/15] more debugging --- .github/workflows/build-sdk.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 6135084..128bb31 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -38,7 +38,8 @@ jobs: cp .gitignore .gitignore.local cp .gitignore.pub .gitignore - echo "${{ github.event.pull_request.user }}" + echo "actor: ${{ github.actor }}" + echo "login: ${{ github.event.pull_request.user.login }}" continue-on-error: false - name: Commit SDK updates @@ -50,7 +51,7 @@ jobs: # The name of the user that will be displayed as the author of the commit. # Default: depends on the default_author input - author_name: ${{ github.event.pull_request.user.name }} + author_name: ${{ github.event.pull_request.user.login }} # The email of the user that will be displayed as the author of the commit. # Default: depends on the default_author input From d774fa4e57cb667f41fa8786f37e0d5a7e523ee0 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:26:12 -0600 Subject: [PATCH 10/15] try loggin email --- .github/workflows/build-sdk.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 128bb31..3387c6f 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -40,6 +40,7 @@ jobs: echo "actor: ${{ github.actor }}" echo "login: ${{ github.event.pull_request.user.login }}" + echo "email: ${{ github.event.pull_request.user.email }}" continue-on-error: false - name: Commit SDK updates From cc80372acbcc0d2875b5c83da4ceae22ce1416b3 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 11:49:44 -0600 Subject: [PATCH 11/15] try adding permissions to token via workflow settings --- .github/workflows/build-sdk.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 3387c6f..37ecf05 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -5,6 +5,9 @@ on: branches: [ main ] workflow_dispatch: +permissions: + contents: write + jobs: build: runs-on: ubuntu-latest @@ -37,10 +40,6 @@ jobs: run: | cp .gitignore .gitignore.local cp .gitignore.pub .gitignore - - echo "actor: ${{ github.actor }}" - echo "login: ${{ github.event.pull_request.user.login }}" - echo "email: ${{ github.event.pull_request.user.email }}" continue-on-error: false - name: Commit SDK updates From 111c90d9df02ef63353b1d523a232f557f332feb Mon Sep 17 00:00:00 2001 From: CalebCourier Date: Wed, 28 Feb 2024 17:50:16 +0000 Subject: [PATCH 12/15] update generated sdk --- guard-rails-api-client/.gitignore | 23 + guard-rails-api-client/README.md | 111 ++ .../guard_rails_api_client/__init__.py | 7 + .../guard_rails_api_client/api/__init__.py | 1 + .../api/default/__init__.py | 0 .../api/default/delete_ingested_document.py | 155 +++ .../api/default/get_ingested_document.py | 155 +++ .../get_ingested_document_by_guard_id.py | 155 +++ .../api/default/ingest.py | 180 ++++ .../api/default/update_ingested_document.py | 193 ++++ .../api/guard/__init__.py | 0 .../api/guard/create_guard.py | 155 +++ .../api/guard/delete_guard.py | 146 +++ .../api/guard/get_guard.py | 171 +++ .../api/guard/get_guards.py | 127 +++ .../api/guard/update_guard.py | 168 +++ .../api/guard/validate.py | 188 ++++ .../api/metrics/__init__.py | 0 .../api/metrics/get_guard_metrics.py | 204 ++++ .../api/metrics/get_guard_run_metrics.py | 168 +++ .../api/metrics/get_validator_metrics.py | 208 ++++ .../api/metrics/get_validator_run_metrics.py | 181 ++++ .../api/projections/__init__.py | 0 .../api/projections/get_projection.py | 176 ++++ .../api/projections/update_projection.py | 176 ++++ .../api/service_health/__init__.py | 0 .../api/service_health/get_health_check.py | 118 +++ .../guard_rails_api_client/client.py | 268 +++++ .../guard_rails_api_client/errors.py | 14 + .../guard_rails_api_client/models/__init__.py | 89 ++ .../models/any_object.py | 43 + .../models/data_type.py | 106 ++ .../models/data_type_children.py | 43 + .../guard_rails_api_client/models/document.py | 98 ++ .../models/document_metadata.py | 43 + .../models/document_pages.py | 43 + .../guard_rails_api_client/models/guard.py | 119 +++ .../models/guard_guard_config.py | 43 + .../models/guard_metrics.py | 128 +++ .../models/guard_run_metric_details.py | 92 ++ .../models/guard_run_metrics.py | 169 +++ .../models/guard_run_step.py | 80 ++ .../models/health_check.py | 66 ++ .../guard_rails_api_client/models/history.py | 74 ++ .../models/history_event.py | 146 +++ .../models/history_event_parsed_output.py | 43 + .../models/history_event_prompt.py | 58 ++ .../models/history_event_reasks_item.py | 43 + .../models/history_event_validated_output.py | 43 + .../models/http_error.py | 111 ++ .../models/http_error_fields.py | 54 + .../models/ingestion.py | 145 +++ .../models/ingestion_metadata.py | 43 + .../models/ingestion_payload.py | 98 ++ .../models/json_schema.py | 56 + .../guard_rails_api_client/models/on_fail.py | 68 ++ .../models/on_fail_options.py | 14 + .../models/projection.py | 114 ++ .../models/rail_spec.py | 109 ++ .../models/rail_spec_version.py | 8 + .../guard_rails_api_client/models/reask.py | 578 +++++++++++ .../guard_rails_api_client/models/schema.py | 88 ++ .../models/schema_element.py | 147 +++ .../guard_rails_api_client/models/status.py | 9 + .../models/validate_payload.py | 107 ++ .../models/validate_payload_llm_api.py | 11 + .../models/validate_payload_prompt_params.py | 43 + .../models/validation_output.py | 103 ++ .../models/validator_metrics.py | 145 +++ .../models/validator_run_metric_details.py | 90 ++ ...validator_run_metric_details_parameters.py | 43 + .../models/validator_run_metrics.py | 184 ++++ .../guard_rails_api_client/py.typed | 1 + .../guard_rails_api_client/types.py | 44 + guard-rails-api-client/pyproject.toml | 6 + guard-rails-api-client/setup.py | 18 + open-api-spec.yml | 981 ++++++++++++++++++ 77 files changed, 8435 insertions(+) create mode 100644 guard-rails-api-client/.gitignore create mode 100644 guard-rails-api-client/README.md create mode 100644 guard-rails-api-client/guard_rails_api_client/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/default/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/default/delete_ingested_document.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document_by_guard_id.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/default/ingest.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/default/update_ingested_document.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/create_guard.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/delete_guard.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/get_guard.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/get_guards.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/update_guard.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/guard/validate.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/metrics/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_run_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_run_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/projections/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/projections/get_projection.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/projections/update_projection.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/service_health/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/api/service_health/get_health_check.py create mode 100644 guard-rails-api-client/guard_rails_api_client/client.py create mode 100644 guard-rails-api-client/guard_rails_api_client/errors.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/__init__.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/any_object.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/data_type.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/data_type_children.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/document.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/document_metadata.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/document_pages.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/guard.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/guard_guard_config.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/guard_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/guard_run_metric_details.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/guard_run_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/guard_run_step.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/health_check.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/history.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event_prompt.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event_reasks_item.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/http_error.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/http_error_fields.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/ingestion.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/ingestion_metadata.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/ingestion_payload.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/json_schema.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/on_fail.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/on_fail_options.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/projection.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/rail_spec.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/rail_spec_version.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/reask.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/schema.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/schema_element.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/status.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validate_payload.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validate_payload_llm_api.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validate_payload_prompt_params.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validation_output.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validator_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details_parameters.py create mode 100644 guard-rails-api-client/guard_rails_api_client/models/validator_run_metrics.py create mode 100644 guard-rails-api-client/guard_rails_api_client/py.typed create mode 100644 guard-rails-api-client/guard_rails_api_client/types.py create mode 100644 guard-rails-api-client/pyproject.toml create mode 100644 guard-rails-api-client/setup.py create mode 100644 open-api-spec.yml diff --git a/guard-rails-api-client/.gitignore b/guard-rails-api-client/.gitignore new file mode 100644 index 0000000..79a2c3d --- /dev/null +++ b/guard-rails-api-client/.gitignore @@ -0,0 +1,23 @@ +__pycache__/ +build/ +dist/ +*.egg-info/ +.pytest_cache/ + +# pyenv +.python-version + +# Environments +.env +.venv + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# JetBrains +.idea/ + +/coverage.xml +/.coverage diff --git a/guard-rails-api-client/README.md b/guard-rails-api-client/README.md new file mode 100644 index 0000000..7ed6adb --- /dev/null +++ b/guard-rails-api-client/README.md @@ -0,0 +1,111 @@ +# guard-rails-api-client +A client library for accessing GuardRails API + +## Usage +First, create a client: + +```python +from guard_rails_api_client import Client + +client = Client(base_url="https://api.example.com") +``` + +If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead: + +```python +from guard_rails_api_client import AuthenticatedClient + +client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken") +``` + +Now call your endpoint and use your models: + +```python +from guard_rails_api_client.models import MyDataModel +from guard_rails_api_client.api.my_tag import get_my_data_model +from guard_rails_api_client.types import Response + +with client as client: + my_data: MyDataModel = get_my_data_model.sync(client=client) + # or if you need more info (e.g. status_code) + response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client) +``` + +Or do the same thing with an async version: + +```python +from guard_rails_api_client.models import MyDataModel +from guard_rails_api_client.api.my_tag import get_my_data_model +from guard_rails_api_client.types import Response + +async with client as client: + my_data: MyDataModel = await get_my_data_model.asyncio(client=client) + response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client) +``` + +By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle. + +```python +client = AuthenticatedClient( + base_url="https://internal_api.example.com", + token="SuperSecretToken", + verify_ssl="/path/to/certificate_bundle.pem", +) +``` + +You can also disable certificate validation altogether, but beware that **this is a security risk**. + +```python +client = AuthenticatedClient( + base_url="https://internal_api.example.com", + token="SuperSecretToken", + verify_ssl=False +) +``` + +Things to know: +1. Every path/method combo becomes a Python module with four functions: + 1. `sync`: Blocking request that returns parsed data (if successful) or `None` + 1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful. + 1. `asyncio`: Like `sync` but async instead of blocking + 1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking + +1. All path/query params, and bodies become method arguments. +1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above) +1. Any endpoint which did not have a tag will be in `guard_rails_api_client.api.default` + +## Advanced customizations + +There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case): + +```python +from guard_rails_api_client import Client + +def log_request(request): + print(f"Request event hook: {request.method} {request.url} - Waiting for response") + +def log_response(response): + request = response.request + print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") + +client = Client( + base_url="https://api.example.com", + httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}}, +) + +# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client() +``` + +You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url): + +```python +import httpx +from guard_rails_api_client import Client + +client = Client( + base_url="https://api.example.com", +) +# Note that base_url needs to be re-set, as would any shared cookies, headers, etc. +client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030")) +``` + diff --git a/guard-rails-api-client/guard_rails_api_client/__init__.py b/guard-rails-api-client/guard_rails_api_client/__init__.py new file mode 100644 index 0000000..3da9abc --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/__init__.py @@ -0,0 +1,7 @@ +""" A client library for accessing GuardRails API """ +from .client import AuthenticatedClient, Client + +__all__ = ( + "AuthenticatedClient", + "Client", +) diff --git a/guard-rails-api-client/guard_rails_api_client/api/__init__.py b/guard-rails-api-client/guard_rails_api_client/api/__init__.py new file mode 100644 index 0000000..dc035f4 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/__init__.py @@ -0,0 +1 @@ +""" Contains methods for accessing the API """ diff --git a/guard-rails-api-client/guard_rails_api_client/api/default/__init__.py b/guard-rails-api-client/guard_rails_api_client/api/default/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/guard-rails-api-client/guard_rails_api_client/api/default/delete_ingested_document.py b/guard-rails-api-client/guard_rails_api_client/api/default/delete_ingested_document.py new file mode 100644 index 0000000..d6d117c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/default/delete_ingested_document.py @@ -0,0 +1,155 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.ingestion import Ingestion +from ...types import Response + + +def _get_kwargs( + document_id: str, +) -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "delete", + "url": f"/embeddings/{document_id}", + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Ingestion"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Ingestion.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Ingestion"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Response[List["Ingestion"]]: + """Deletes embeddings for a given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + document_id=document_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Optional[List["Ingestion"]]: + """Deletes embeddings for a given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return sync_detailed( + document_id=document_id, + client=client, + ).parsed + + +async def asyncio_detailed( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Response[List["Ingestion"]]: + """Deletes embeddings for a given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + document_id=document_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Optional[List["Ingestion"]]: + """Deletes embeddings for a given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return ( + await asyncio_detailed( + document_id=document_id, + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document.py b/guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document.py new file mode 100644 index 0000000..caf8557 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document.py @@ -0,0 +1,155 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.ingestion import Ingestion +from ...types import Response + + +def _get_kwargs( + document_id: str, +) -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "get", + "url": f"/embeddings/{document_id}", + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Ingestion"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Ingestion.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Ingestion"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Response[List["Ingestion"]]: + """Returns a list of ingestion items for given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + document_id=document_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Optional[List["Ingestion"]]: + """Returns a list of ingestion items for given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return sync_detailed( + document_id=document_id, + client=client, + ).parsed + + +async def asyncio_detailed( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Response[List["Ingestion"]]: + """Returns a list of ingestion items for given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + document_id=document_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Optional[List["Ingestion"]]: + """Returns a list of ingestion items for given documentId + + Args: + document_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return ( + await asyncio_detailed( + document_id=document_id, + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document_by_guard_id.py b/guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document_by_guard_id.py new file mode 100644 index 0000000..f22a97c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/default/get_ingested_document_by_guard_id.py @@ -0,0 +1,155 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.ingestion import Ingestion +from ...types import Response + + +def _get_kwargs( + guard_name: str, +) -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "get", + "url": f"/guards/{guard_name}/embeddings", + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Ingestion"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Ingestion.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Ingestion"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Response[List["Ingestion"]]: + """Returns a list of ingestion items for a guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Optional[List["Ingestion"]]: + """Returns a list of ingestion items for a guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Response[List["Ingestion"]]: + """Returns a list of ingestion items for a guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], +) -> Optional[List["Ingestion"]]: + """Returns a list of ingestion items for a guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/default/ingest.py b/guard-rails-api-client/guard_rails_api_client/api/default/ingest.py new file mode 100644 index 0000000..a3563b2 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/default/ingest.py @@ -0,0 +1,180 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.ingestion import Ingestion +from ...models.ingestion_payload import IngestionPayload +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Dict[str, Any]: + headers: Dict[str, Any] = {} + if not isinstance(x_openai_api_key, Unset): + headers["x-openai-api-key"] = x_openai_api_key + + _kwargs: Dict[str, Any] = { + "method": "post", + "url": "/ingest", + } + + _body = body.to_dict() + + _kwargs["json"] = _body + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Ingestion"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Ingestion.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Ingestion"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Response[List["Ingestion"]]: + """Creates and ingests embeddings for a document + + Args: + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + body=body, + x_openai_api_key=x_openai_api_key, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Optional[List["Ingestion"]]: + """Creates and ingests embeddings for a document + + Args: + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return sync_detailed( + client=client, + body=body, + x_openai_api_key=x_openai_api_key, + ).parsed + + +async def asyncio_detailed( + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Response[List["Ingestion"]]: + """Creates and ingests embeddings for a document + + Args: + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + body=body, + x_openai_api_key=x_openai_api_key, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Optional[List["Ingestion"]]: + """Creates and ingests embeddings for a document + + Args: + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + x_openai_api_key=x_openai_api_key, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/default/update_ingested_document.py b/guard-rails-api-client/guard_rails_api_client/api/default/update_ingested_document.py new file mode 100644 index 0000000..9199369 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/default/update_ingested_document.py @@ -0,0 +1,193 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.ingestion import Ingestion +from ...models.ingestion_payload import IngestionPayload +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + document_id: str, + *, + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Dict[str, Any]: + headers: Dict[str, Any] = {} + if not isinstance(x_openai_api_key, Unset): + headers["x-openai-api-key"] = x_openai_api_key + + _kwargs: Dict[str, Any] = { + "method": "put", + "url": f"/embeddings/{document_id}", + } + + _body = body.to_dict() + + _kwargs["json"] = _body + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Ingestion"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Ingestion.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Ingestion"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Response[List["Ingestion"]]: + """Updates embeddings for a given documentId + + Args: + document_id (str): + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + document_id=document_id, + body=body, + x_openai_api_key=x_openai_api_key, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Optional[List["Ingestion"]]: + """Updates embeddings for a given documentId + + Args: + document_id (str): + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return sync_detailed( + document_id=document_id, + client=client, + body=body, + x_openai_api_key=x_openai_api_key, + ).parsed + + +async def asyncio_detailed( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Response[List["Ingestion"]]: + """Updates embeddings for a given documentId + + Args: + document_id (str): + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Ingestion']] + """ + + kwargs = _get_kwargs( + document_id=document_id, + body=body, + x_openai_api_key=x_openai_api_key, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + document_id: str, + *, + client: Union[AuthenticatedClient, Client], + body: IngestionPayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Optional[List["Ingestion"]]: + """Updates embeddings for a given documentId + + Args: + document_id (str): + x_openai_api_key (Union[Unset, str]): + body (IngestionPayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Ingestion'] + """ + + return ( + await asyncio_detailed( + document_id=document_id, + client=client, + body=body, + x_openai_api_key=x_openai_api_key, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/__init__.py b/guard-rails-api-client/guard_rails_api_client/api/guard/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/create_guard.py b/guard-rails-api-client/guard_rails_api_client/api/guard/create_guard.py new file mode 100644 index 0000000..f906605 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/guard/create_guard.py @@ -0,0 +1,155 @@ +from http import HTTPStatus +from typing import Any, Dict, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard import Guard +from ...types import Response + + +def _get_kwargs( + *, + body: Guard, +) -> Dict[str, Any]: + headers: Dict[str, Any] = {} + + _kwargs: Dict[str, Any] = { + "method": "post", + "url": "/guards", + } + + _body = body.to_dict() + + _kwargs["json"] = _body + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Guard]: + if response.status_code == HTTPStatus.OK: + response_200 = Guard.from_dict(response.json()) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Guard]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: Guard, +) -> Response[Guard]: + """Creates a Guard + + Args: + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: Guard, +) -> Optional[Guard]: + """Creates a Guard + + Args: + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: Guard, +) -> Response[Guard]: + """Creates a Guard + + Args: + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: Guard, +) -> Optional[Guard]: + """Creates a Guard + + Args: + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/delete_guard.py b/guard-rails-api-client/guard_rails_api_client/api/guard/delete_guard.py new file mode 100644 index 0000000..eaec374 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/guard/delete_guard.py @@ -0,0 +1,146 @@ +from http import HTTPStatus +from typing import Any, Dict, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard import Guard +from ...types import Response + + +def _get_kwargs( + guard_name: str, +) -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "delete", + "url": f"/guards/{guard_name}", + } + + return _kwargs + + +def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Guard]: + if response.status_code == HTTPStatus.OK: + response_200 = Guard.from_dict(response.json()) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Guard]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: AuthenticatedClient, +) -> Response[Guard]: + """Deletes a Guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: AuthenticatedClient, +) -> Optional[Guard]: + """Deletes a Guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: AuthenticatedClient, +) -> Response[Guard]: + """Deletes a Guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: AuthenticatedClient, +) -> Optional[Guard]: + """Deletes a Guard + + Args: + guard_name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/get_guard.py b/guard-rails-api-client/guard_rails_api_client/api/guard/get_guard.py new file mode 100644 index 0000000..36ecb5a --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/guard/get_guard.py @@ -0,0 +1,171 @@ +import datetime +from http import HTTPStatus +from typing import Any, Dict, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard import Guard +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + guard_name: str, + *, + as_of: Union[Unset, datetime.datetime] = UNSET, +) -> Dict[str, Any]: + params: Dict[str, Any] = {} + + json_as_of: Union[Unset, str] = UNSET + if not isinstance(as_of, Unset): + json_as_of = as_of.isoformat() + params["asOf"] = json_as_of + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: Dict[str, Any] = { + "method": "get", + "url": f"/guards/{guard_name}", + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Guard]: + if response.status_code == HTTPStatus.OK: + response_200 = Guard.from_dict(response.json()) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Guard]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: AuthenticatedClient, + as_of: Union[Unset, datetime.datetime] = UNSET, +) -> Response[Guard]: + """Fetches a specific Guard + + Args: + guard_name (str): + as_of (Union[Unset, datetime.datetime]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + as_of=as_of, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: AuthenticatedClient, + as_of: Union[Unset, datetime.datetime] = UNSET, +) -> Optional[Guard]: + """Fetches a specific Guard + + Args: + guard_name (str): + as_of (Union[Unset, datetime.datetime]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + as_of=as_of, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: AuthenticatedClient, + as_of: Union[Unset, datetime.datetime] = UNSET, +) -> Response[Guard]: + """Fetches a specific Guard + + Args: + guard_name (str): + as_of (Union[Unset, datetime.datetime]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + as_of=as_of, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: AuthenticatedClient, + as_of: Union[Unset, datetime.datetime] = UNSET, +) -> Optional[Guard]: + """Fetches a specific Guard + + Args: + guard_name (str): + as_of (Union[Unset, datetime.datetime]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + as_of=as_of, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/get_guards.py b/guard-rails-api-client/guard_rails_api_client/api/guard/get_guards.py new file mode 100644 index 0000000..8cc7e3c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/guard/get_guards.py @@ -0,0 +1,127 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard import Guard +from ...types import Response + + +def _get_kwargs() -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "get", + "url": "/guards", + } + + return _kwargs + + +def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[List["Guard"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Guard.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[List["Guard"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[List["Guard"]]: + """Fetches the configuration for all Guards the user has access to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Guard']] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Optional[List["Guard"]]: + """Fetches the configuration for all Guards the user has access to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Guard'] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[List["Guard"]]: + """Fetches the configuration for all Guards the user has access to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Guard']] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Optional[List["Guard"]]: + """Fetches the configuration for all Guards the user has access to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Guard'] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/update_guard.py b/guard-rails-api-client/guard_rails_api_client/api/guard/update_guard.py new file mode 100644 index 0000000..3934927 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/guard/update_guard.py @@ -0,0 +1,168 @@ +from http import HTTPStatus +from typing import Any, Dict, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard import Guard +from ...types import Response + + +def _get_kwargs( + guard_name: str, + *, + body: Guard, +) -> Dict[str, Any]: + headers: Dict[str, Any] = {} + + _kwargs: Dict[str, Any] = { + "method": "put", + "url": f"/guards/{guard_name}", + } + + _body = body.to_dict() + + _kwargs["json"] = _body + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Guard]: + if response.status_code == HTTPStatus.OK: + response_200 = Guard.from_dict(response.json()) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Guard]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: AuthenticatedClient, + body: Guard, +) -> Response[Guard]: + """Updates a Guard + + Args: + guard_name (str): + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: AuthenticatedClient, + body: Guard, +) -> Optional[Guard]: + """Updates a Guard + + Args: + guard_name (str): + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: AuthenticatedClient, + body: Guard, +) -> Response[Guard]: + """Updates a Guard + + Args: + guard_name (str): + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Guard] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: AuthenticatedClient, + body: Guard, +) -> Optional[Guard]: + """Updates a Guard + + Args: + guard_name (str): + body (Guard): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Guard + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + body=body, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/guard/validate.py b/guard-rails-api-client/guard_rails_api_client/api/guard/validate.py new file mode 100644 index 0000000..3d3029c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/guard/validate.py @@ -0,0 +1,188 @@ +from http import HTTPStatus +from typing import Any, Dict, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.validate_payload import ValidatePayload +from ...models.validation_output import ValidationOutput +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + guard_name: str, + *, + body: ValidatePayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Dict[str, Any]: + headers: Dict[str, Any] = {} + if not isinstance(x_openai_api_key, Unset): + headers["x-openai-api-key"] = x_openai_api_key + + _kwargs: Dict[str, Any] = { + "method": "post", + "url": f"/guards/{guard_name}/validate", + } + + _body = body.to_dict() + + _kwargs["json"] = _body + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[ValidationOutput]: + if response.status_code == HTTPStatus.OK: + response_200 = ValidationOutput.from_dict(response.json()) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[ValidationOutput]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: AuthenticatedClient, + body: ValidatePayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Response[ValidationOutput]: + """Runs the validations specified in a Guard + + Args: + guard_name (str): + x_openai_api_key (Union[Unset, str]): + body (ValidatePayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ValidationOutput] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + body=body, + x_openai_api_key=x_openai_api_key, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: AuthenticatedClient, + body: ValidatePayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Optional[ValidationOutput]: + """Runs the validations specified in a Guard + + Args: + guard_name (str): + x_openai_api_key (Union[Unset, str]): + body (ValidatePayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ValidationOutput + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + body=body, + x_openai_api_key=x_openai_api_key, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: AuthenticatedClient, + body: ValidatePayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Response[ValidationOutput]: + """Runs the validations specified in a Guard + + Args: + guard_name (str): + x_openai_api_key (Union[Unset, str]): + body (ValidatePayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ValidationOutput] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + body=body, + x_openai_api_key=x_openai_api_key, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: AuthenticatedClient, + body: ValidatePayload, + x_openai_api_key: Union[Unset, str] = UNSET, +) -> Optional[ValidationOutput]: + """Runs the validations specified in a Guard + + Args: + guard_name (str): + x_openai_api_key (Union[Unset, str]): + body (ValidatePayload): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ValidationOutput + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + body=body, + x_openai_api_key=x_openai_api_key, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/metrics/__init__.py b/guard-rails-api-client/guard_rails_api_client/api/metrics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_metrics.py b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_metrics.py new file mode 100644 index 0000000..549cc2c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_metrics.py @@ -0,0 +1,204 @@ +import datetime +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard_metrics import GuardMetrics +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Dict[str, Any]: + params: Dict[str, Any] = {} + + json_start_time: Union[Unset, str] = UNSET + if not isinstance(start_time, Unset): + json_start_time = start_time.isoformat() + params["startTime"] = json_start_time + + json_end_time: Union[Unset, str] = UNSET + if not isinstance(end_time, Unset): + json_end_time = end_time.isoformat() + params["endTime"] = json_end_time + + params["page"] = page + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: Dict[str, Any] = { + "method": "get", + "url": "/guards/metrics", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["GuardMetrics"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = GuardMetrics.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["GuardMetrics"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Response[List["GuardMetrics"]]: + """Returns an array of GuardMetrics for a given time range. If startTime or endTime are ommitted, a + five minute duration is used by default. Default page size is 10. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['GuardMetrics']] + """ + + kwargs = _get_kwargs( + start_time=start_time, + end_time=end_time, + page=page, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Optional[List["GuardMetrics"]]: + """Returns an array of GuardMetrics for a given time range. If startTime or endTime are ommitted, a + five minute duration is used by default. Default page size is 10. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['GuardMetrics'] + """ + + return sync_detailed( + client=client, + start_time=start_time, + end_time=end_time, + page=page, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Response[List["GuardMetrics"]]: + """Returns an array of GuardMetrics for a given time range. If startTime or endTime are ommitted, a + five minute duration is used by default. Default page size is 10. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['GuardMetrics']] + """ + + kwargs = _get_kwargs( + start_time=start_time, + end_time=end_time, + page=page, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Optional[List["GuardMetrics"]]: + """Returns an array of GuardMetrics for a given time range. If startTime or endTime are ommitted, a + five minute duration is used by default. Default page size is 10. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['GuardMetrics'] + """ + + return ( + await asyncio_detailed( + client=client, + start_time=start_time, + end_time=end_time, + page=page, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_run_metrics.py b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_run_metrics.py new file mode 100644 index 0000000..9b887fc --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_guard_run_metrics.py @@ -0,0 +1,168 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.guard_run_metrics import GuardRunMetrics +from ...types import Response + + +def _get_kwargs( + guard_name: str, + request_id: str, +) -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "get", + "url": f"/guards/{guard_name}/runs/{request_id}/metrics", + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["GuardRunMetrics"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = GuardRunMetrics.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["GuardRunMetrics"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + request_id: str, + *, + client: AuthenticatedClient, +) -> Response[List["GuardRunMetrics"]]: + """Returns an instance of GuardRunMetrics for a given request. + + Args: + guard_name (str): + request_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['GuardRunMetrics']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + request_id=request_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + request_id: str, + *, + client: AuthenticatedClient, +) -> Optional[List["GuardRunMetrics"]]: + """Returns an instance of GuardRunMetrics for a given request. + + Args: + guard_name (str): + request_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['GuardRunMetrics'] + """ + + return sync_detailed( + guard_name=guard_name, + request_id=request_id, + client=client, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + request_id: str, + *, + client: AuthenticatedClient, +) -> Response[List["GuardRunMetrics"]]: + """Returns an instance of GuardRunMetrics for a given request. + + Args: + guard_name (str): + request_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['GuardRunMetrics']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + request_id=request_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + request_id: str, + *, + client: AuthenticatedClient, +) -> Optional[List["GuardRunMetrics"]]: + """Returns an instance of GuardRunMetrics for a given request. + + Args: + guard_name (str): + request_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['GuardRunMetrics'] + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + request_id=request_id, + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_metrics.py b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_metrics.py new file mode 100644 index 0000000..f1e878a --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_metrics.py @@ -0,0 +1,208 @@ +import datetime +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.validator_metrics import ValidatorMetrics +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Dict[str, Any]: + params: Dict[str, Any] = {} + + json_start_time: Union[Unset, str] = UNSET + if not isinstance(start_time, Unset): + json_start_time = start_time.isoformat() + params["startTime"] = json_start_time + + json_end_time: Union[Unset, str] = UNSET + if not isinstance(end_time, Unset): + json_end_time = end_time.isoformat() + params["endTime"] = json_end_time + + params["page"] = page + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: Dict[str, Any] = { + "method": "get", + "url": "/validators/metrics", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["ValidatorMetrics"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = ValidatorMetrics.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["ValidatorMetrics"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Response[List["ValidatorMetrics"]]: + """Returns an array of ValidatorMetrics for a given time range. If startTime or endTime are ommitted, + a five minute duration is used by default. Default page size is 10, but this page size applied to + guard steps not validator metrics. Have to think this one out a little more. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['ValidatorMetrics']] + """ + + kwargs = _get_kwargs( + start_time=start_time, + end_time=end_time, + page=page, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Optional[List["ValidatorMetrics"]]: + """Returns an array of ValidatorMetrics for a given time range. If startTime or endTime are ommitted, + a five minute duration is used by default. Default page size is 10, but this page size applied to + guard steps not validator metrics. Have to think this one out a little more. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['ValidatorMetrics'] + """ + + return sync_detailed( + client=client, + start_time=start_time, + end_time=end_time, + page=page, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Response[List["ValidatorMetrics"]]: + """Returns an array of ValidatorMetrics for a given time range. If startTime or endTime are ommitted, + a five minute duration is used by default. Default page size is 10, but this page size applied to + guard steps not validator metrics. Have to think this one out a little more. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['ValidatorMetrics']] + """ + + kwargs = _get_kwargs( + start_time=start_time, + end_time=end_time, + page=page, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + start_time: Union[Unset, datetime.datetime] = UNSET, + end_time: Union[Unset, datetime.datetime] = UNSET, + page: Union[Unset, int] = 0, +) -> Optional[List["ValidatorMetrics"]]: + """Returns an array of ValidatorMetrics for a given time range. If startTime or endTime are ommitted, + a five minute duration is used by default. Default page size is 10, but this page size applied to + guard steps not validator metrics. Have to think this one out a little more. + + Args: + start_time (Union[Unset, datetime.datetime]): + end_time (Union[Unset, datetime.datetime]): + page (Union[Unset, int]): Default: 0. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['ValidatorMetrics'] + """ + + return ( + await asyncio_detailed( + client=client, + start_time=start_time, + end_time=end_time, + page=page, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_run_metrics.py b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_run_metrics.py new file mode 100644 index 0000000..79c8f0a --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/metrics/get_validator_run_metrics.py @@ -0,0 +1,181 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.validator_run_metrics import ValidatorRunMetrics +from ...types import Response + + +def _get_kwargs( + validator_name: str, + request_id: str, + validator_instance_id: str, +) -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "get", + "url": f"/validators/{validator_name}/runs/{request_id}/instances/{validator_instance_id}/metrics", + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["ValidatorRunMetrics"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = ValidatorRunMetrics.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["ValidatorRunMetrics"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + validator_name: str, + request_id: str, + validator_instance_id: str, + *, + client: AuthenticatedClient, +) -> Response[List["ValidatorRunMetrics"]]: + """Returns an arary of ValidatorRunMetrics for a given request. + + Args: + validator_name (str): + request_id (str): + validator_instance_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['ValidatorRunMetrics']] + """ + + kwargs = _get_kwargs( + validator_name=validator_name, + request_id=request_id, + validator_instance_id=validator_instance_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + validator_name: str, + request_id: str, + validator_instance_id: str, + *, + client: AuthenticatedClient, +) -> Optional[List["ValidatorRunMetrics"]]: + """Returns an arary of ValidatorRunMetrics for a given request. + + Args: + validator_name (str): + request_id (str): + validator_instance_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['ValidatorRunMetrics'] + """ + + return sync_detailed( + validator_name=validator_name, + request_id=request_id, + validator_instance_id=validator_instance_id, + client=client, + ).parsed + + +async def asyncio_detailed( + validator_name: str, + request_id: str, + validator_instance_id: str, + *, + client: AuthenticatedClient, +) -> Response[List["ValidatorRunMetrics"]]: + """Returns an arary of ValidatorRunMetrics for a given request. + + Args: + validator_name (str): + request_id (str): + validator_instance_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['ValidatorRunMetrics']] + """ + + kwargs = _get_kwargs( + validator_name=validator_name, + request_id=request_id, + validator_instance_id=validator_instance_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + validator_name: str, + request_id: str, + validator_instance_id: str, + *, + client: AuthenticatedClient, +) -> Optional[List["ValidatorRunMetrics"]]: + """Returns an arary of ValidatorRunMetrics for a given request. + + Args: + validator_name (str): + request_id (str): + validator_instance_id (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['ValidatorRunMetrics'] + """ + + return ( + await asyncio_detailed( + validator_name=validator_name, + request_id=request_id, + validator_instance_id=validator_instance_id, + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/projections/__init__.py b/guard-rails-api-client/guard_rails_api_client/api/projections/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/guard-rails-api-client/guard_rails_api_client/api/projections/get_projection.py b/guard-rails-api-client/guard_rails_api_client/api/projections/get_projection.py new file mode 100644 index 0000000..9e01906 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/projections/get_projection.py @@ -0,0 +1,176 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.projection import Projection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + guard_name: str, + *, + validator_id: Union[Unset, str] = UNSET, +) -> Dict[str, Any]: + params: Dict[str, Any] = {} + + params["validatorId"] = validator_id + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: Dict[str, Any] = { + "method": "get", + "url": f"/embeddings/{guard_name}/projections", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Projection"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Projection.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Projection"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Response[List["Projection"]]: + """Returns the T-SNE projection for the given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Projection']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + validator_id=validator_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Optional[List["Projection"]]: + """Returns the T-SNE projection for the given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Projection'] + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + validator_id=validator_id, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Response[List["Projection"]]: + """Returns the T-SNE projection for the given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Projection']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + validator_id=validator_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Optional[List["Projection"]]: + """Returns the T-SNE projection for the given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Projection'] + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + validator_id=validator_id, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/projections/update_projection.py b/guard-rails-api-client/guard_rails_api_client/api/projections/update_projection.py new file mode 100644 index 0000000..caf4422 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/projections/update_projection.py @@ -0,0 +1,176 @@ +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.projection import Projection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + guard_name: str, + *, + validator_id: Union[Unset, str] = UNSET, +) -> Dict[str, Any]: + params: Dict[str, Any] = {} + + params["validatorId"] = validator_id + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: Dict[str, Any] = { + "method": "put", + "url": f"/embeddings/{guard_name}/projections", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[List["Projection"]]: + if response.status_code == HTTPStatus.OK: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = Projection.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[List["Projection"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Response[List["Projection"]]: + """Creates of updates projection for a given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Projection']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + validator_id=validator_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Optional[List["Projection"]]: + """Creates of updates projection for a given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Projection'] + """ + + return sync_detailed( + guard_name=guard_name, + client=client, + validator_id=validator_id, + ).parsed + + +async def asyncio_detailed( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Response[List["Projection"]]: + """Creates of updates projection for a given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[List['Projection']] + """ + + kwargs = _get_kwargs( + guard_name=guard_name, + validator_id=validator_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + guard_name: str, + *, + client: Union[AuthenticatedClient, Client], + validator_id: Union[Unset, str] = UNSET, +) -> Optional[List["Projection"]]: + """Creates of updates projection for a given Guard id + + Args: + guard_name (str): + validator_id (Union[Unset, str]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + List['Projection'] + """ + + return ( + await asyncio_detailed( + guard_name=guard_name, + client=client, + validator_id=validator_id, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/api/service_health/__init__.py b/guard-rails-api-client/guard_rails_api_client/api/service_health/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/guard-rails-api-client/guard_rails_api_client/api/service_health/get_health_check.py b/guard-rails-api-client/guard_rails_api_client/api/service_health/get_health_check.py new file mode 100644 index 0000000..09f5484 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/api/service_health/get_health_check.py @@ -0,0 +1,118 @@ +from http import HTTPStatus +from typing import Any, Dict, Optional, Union + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.health_check import HealthCheck +from ...types import Response + + +def _get_kwargs() -> Dict[str, Any]: + _kwargs: Dict[str, Any] = { + "method": "get", + "url": "/health-check", + } + + return _kwargs + + +def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[HealthCheck]: + if response.status_code == HTTPStatus.OK: + response_200 = HealthCheck.from_dict(response.json()) + + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[HealthCheck]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[HealthCheck]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[HealthCheck] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Optional[HealthCheck]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + HealthCheck + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[HealthCheck]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[HealthCheck] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Optional[HealthCheck]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + HealthCheck + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/guard-rails-api-client/guard_rails_api_client/client.py b/guard-rails-api-client/guard_rails_api_client/client.py new file mode 100644 index 0000000..74b476c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/client.py @@ -0,0 +1,268 @@ +import ssl +from typing import Any, Dict, Optional, Union + +import httpx +from attrs import define, evolve, field + + +@define +class Client: + """A class for keeping track of data related to the API + + The following are accepted as keyword arguments and will be used to construct httpx Clients internally: + + ``base_url``: The base URL for the API, all requests are made to a relative path to this URL + + ``cookies``: A dictionary of cookies to be sent with every request + + ``headers``: A dictionary of headers to be sent with every request + + ``timeout``: The maximum amount of a time a request can take. API functions will raise + httpx.TimeoutException if this is exceeded. + + ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production, + but can be set to False for testing purposes. + + ``follow_redirects``: Whether or not to follow redirects. Default value is False. + + ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor. + + + Attributes: + raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a + status code that was not documented in the source OpenAPI document. Can also be provided as a keyword + argument to the constructor. + """ + + raise_on_unexpected_status: bool = field(default=False, kw_only=True) + _base_url: str + _cookies: Dict[str, str] = field(factory=dict, kw_only=True) + _headers: Dict[str, str] = field(factory=dict, kw_only=True) + _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True) + _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True) + _follow_redirects: bool = field(default=False, kw_only=True) + _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True) + _client: Optional[httpx.Client] = field(default=None, init=False) + _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False) + + def with_headers(self, headers: Dict[str, str]) -> "Client": + """Get a new client matching this one with additional headers""" + if self._client is not None: + self._client.headers.update(headers) + if self._async_client is not None: + self._async_client.headers.update(headers) + return evolve(self, headers={**self._headers, **headers}) + + def with_cookies(self, cookies: Dict[str, str]) -> "Client": + """Get a new client matching this one with additional cookies""" + if self._client is not None: + self._client.cookies.update(cookies) + if self._async_client is not None: + self._async_client.cookies.update(cookies) + return evolve(self, cookies={**self._cookies, **cookies}) + + def with_timeout(self, timeout: httpx.Timeout) -> "Client": + """Get a new client matching this one with a new timeout (in seconds)""" + if self._client is not None: + self._client.timeout = timeout + if self._async_client is not None: + self._async_client.timeout = timeout + return evolve(self, timeout=timeout) + + def set_httpx_client(self, client: httpx.Client) -> "Client": + """Manually the underlying httpx.Client + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._client = client + return self + + def get_httpx_client(self) -> httpx.Client: + """Get the underlying httpx.Client, constructing a new one if not previously set""" + if self._client is None: + self._client = httpx.Client( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._client + + def __enter__(self) -> "Client": + """Enter a context manager for self.client—you cannot enter twice (see httpx docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx.Client (see httpx docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client": + """Manually the underlying httpx.AsyncClient + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._async_client = async_client + return self + + def get_async_httpx_client(self) -> httpx.AsyncClient: + """Get the underlying httpx.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._async_client = httpx.AsyncClient( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._async_client + + async def __aenter__(self) -> "Client": + """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)""" + await self.get_async_httpx_client().__aenter__() + return self + + async def __aexit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) + + +@define +class AuthenticatedClient: + """A Client which has been authenticated for use on secured endpoints + + The following are accepted as keyword arguments and will be used to construct httpx Clients internally: + + ``base_url``: The base URL for the API, all requests are made to a relative path to this URL + + ``cookies``: A dictionary of cookies to be sent with every request + + ``headers``: A dictionary of headers to be sent with every request + + ``timeout``: The maximum amount of a time a request can take. API functions will raise + httpx.TimeoutException if this is exceeded. + + ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production, + but can be set to False for testing purposes. + + ``follow_redirects``: Whether or not to follow redirects. Default value is False. + + ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor. + + + Attributes: + raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a + status code that was not documented in the source OpenAPI document. Can also be provided as a keyword + argument to the constructor. + token: The token to use for authentication + prefix: The prefix to use for the Authorization header + auth_header_name: The name of the Authorization header + """ + + raise_on_unexpected_status: bool = field(default=False, kw_only=True) + _base_url: str + _cookies: Dict[str, str] = field(factory=dict, kw_only=True) + _headers: Dict[str, str] = field(factory=dict, kw_only=True) + _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True) + _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True) + _follow_redirects: bool = field(default=False, kw_only=True) + _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True) + _client: Optional[httpx.Client] = field(default=None, init=False) + _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False) + + token: str + prefix: str = "Bearer" + auth_header_name: str = "Authorization" + + def with_headers(self, headers: Dict[str, str]) -> "AuthenticatedClient": + """Get a new client matching this one with additional headers""" + if self._client is not None: + self._client.headers.update(headers) + if self._async_client is not None: + self._async_client.headers.update(headers) + return evolve(self, headers={**self._headers, **headers}) + + def with_cookies(self, cookies: Dict[str, str]) -> "AuthenticatedClient": + """Get a new client matching this one with additional cookies""" + if self._client is not None: + self._client.cookies.update(cookies) + if self._async_client is not None: + self._async_client.cookies.update(cookies) + return evolve(self, cookies={**self._cookies, **cookies}) + + def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient": + """Get a new client matching this one with a new timeout (in seconds)""" + if self._client is not None: + self._client.timeout = timeout + if self._async_client is not None: + self._async_client.timeout = timeout + return evolve(self, timeout=timeout) + + def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient": + """Manually the underlying httpx.Client + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._client = client + return self + + def get_httpx_client(self) -> httpx.Client: + """Get the underlying httpx.Client, constructing a new one if not previously set""" + if self._client is None: + self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token + self._client = httpx.Client( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._client + + def __enter__(self) -> "AuthenticatedClient": + """Enter a context manager for self.client—you cannot enter twice (see httpx docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx.Client (see httpx docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient": + """Manually the underlying httpx.AsyncClient + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._async_client = async_client + return self + + def get_async_httpx_client(self) -> httpx.AsyncClient: + """Get the underlying httpx.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token + self._async_client = httpx.AsyncClient( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._async_client + + async def __aenter__(self) -> "AuthenticatedClient": + """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)""" + await self.get_async_httpx_client().__aenter__() + return self + + async def __aexit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) diff --git a/guard-rails-api-client/guard_rails_api_client/errors.py b/guard-rails-api-client/guard_rails_api_client/errors.py new file mode 100644 index 0000000..426f8a2 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/errors.py @@ -0,0 +1,14 @@ +""" Contains shared errors types that can be raised from API functions """ + + +class UnexpectedStatus(Exception): + """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True""" + + def __init__(self, status_code: int, content: bytes): + self.status_code = status_code + self.content = content + + super().__init__(f"Unexpected status code: {status_code}") + + +__all__ = ["UnexpectedStatus"] diff --git a/guard-rails-api-client/guard_rails_api_client/models/__init__.py b/guard-rails-api-client/guard_rails_api_client/models/__init__.py new file mode 100644 index 0000000..d8863a3 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/__init__.py @@ -0,0 +1,89 @@ +""" Contains all the data models used in inputs/outputs """ + +from .any_object import AnyObject +from .data_type import DataType +from .data_type_children import DataTypeChildren +from .document import Document +from .document_metadata import DocumentMetadata +from .document_pages import DocumentPages +from .guard import Guard +from .guard_guard_config import GuardGuardConfig +from .guard_metrics import GuardMetrics +from .guard_run_metric_details import GuardRunMetricDetails +from .guard_run_metrics import GuardRunMetrics +from .guard_run_step import GuardRunStep +from .health_check import HealthCheck +from .history import History +from .history_event import HistoryEvent +from .history_event_parsed_output import HistoryEventParsedOutput +from .history_event_prompt import HistoryEventPrompt +from .history_event_reasks_item import HistoryEventReasksItem +from .history_event_validated_output import HistoryEventValidatedOutput +from .http_error import HttpError +from .http_error_fields import HttpErrorFields +from .ingestion import Ingestion +from .ingestion_metadata import IngestionMetadata +from .ingestion_payload import IngestionPayload +from .json_schema import JsonSchema +from .on_fail import OnFail +from .on_fail_options import OnFailOptions +from .projection import Projection +from .rail_spec import RailSpec +from .rail_spec_version import RailSpecVersion +from .reask import Reask +from .schema import Schema +from .schema_element import SchemaElement +from .status import Status +from .validate_payload import ValidatePayload +from .validate_payload_llm_api import ValidatePayloadLlmApi +from .validate_payload_prompt_params import ValidatePayloadPromptParams +from .validation_output import ValidationOutput +from .validator_metrics import ValidatorMetrics +from .validator_run_metric_details import ValidatorRunMetricDetails +from .validator_run_metric_details_parameters import ValidatorRunMetricDetailsParameters +from .validator_run_metrics import ValidatorRunMetrics + +__all__ = ( + "AnyObject", + "DataType", + "DataTypeChildren", + "Document", + "DocumentMetadata", + "DocumentPages", + "Guard", + "GuardGuardConfig", + "GuardMetrics", + "GuardRunMetricDetails", + "GuardRunMetrics", + "GuardRunStep", + "HealthCheck", + "History", + "HistoryEvent", + "HistoryEventParsedOutput", + "HistoryEventPrompt", + "HistoryEventReasksItem", + "HistoryEventValidatedOutput", + "HttpError", + "HttpErrorFields", + "Ingestion", + "IngestionMetadata", + "IngestionPayload", + "JsonSchema", + "OnFail", + "OnFailOptions", + "Projection", + "RailSpec", + "RailSpecVersion", + "Reask", + "Schema", + "SchemaElement", + "Status", + "ValidatePayload", + "ValidatePayloadLlmApi", + "ValidatePayloadPromptParams", + "ValidationOutput", + "ValidatorMetrics", + "ValidatorRunMetricDetails", + "ValidatorRunMetricDetailsParameters", + "ValidatorRunMetrics", +) diff --git a/guard-rails-api-client/guard_rails_api_client/models/any_object.py b/guard-rails-api-client/guard_rails_api_client/models/any_object.py new file mode 100644 index 0000000..82ad2d8 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/any_object.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AnyObject") + + +@_attrs_define +class AnyObject: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + any_object = cls() + + any_object.additional_properties = d + return any_object + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/data_type.py b/guard-rails-api-client/guard_rails_api_client/models/data_type.py new file mode 100644 index 0000000..fbd4af7 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/data_type.py @@ -0,0 +1,106 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.data_type_children import DataTypeChildren + from ..models.schema_element import SchemaElement + + +T = TypeVar("T", bound="DataType") + + +@_attrs_define +class DataType: + """ + Attributes: + element (SchemaElement): + children (Union[Unset, DataTypeChildren]): + formatters (Union[Unset, List[str]]): + plugins (Union[Unset, List[str]]): + """ + + element: "SchemaElement" + children: Union[Unset, "DataTypeChildren"] = UNSET + formatters: Union[Unset, List[str]] = UNSET + plugins: Union[Unset, List[str]] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + element = self.element.to_dict() + + children: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.children, Unset): + children = self.children.to_dict() + + formatters: Union[Unset, List[str]] = UNSET + if not isinstance(self.formatters, Unset): + formatters = self.formatters + + plugins: Union[Unset, List[str]] = UNSET + if not isinstance(self.plugins, Unset): + plugins = self.plugins + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "element": element, + } + ) + if children is not UNSET: + field_dict["children"] = children + if formatters is not UNSET: + field_dict["formatters"] = formatters + if plugins is not UNSET: + field_dict["plugins"] = plugins + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.data_type_children import DataTypeChildren + from ..models.schema_element import SchemaElement + + d = src_dict.copy() + element = SchemaElement.from_dict(d.pop("element")) + + _children = d.pop("children", UNSET) + children: Union[Unset, DataTypeChildren] + if isinstance(_children, Unset): + children = UNSET + else: + children = DataTypeChildren.from_dict(_children) + + formatters = cast(List[str], d.pop("formatters", UNSET)) + + plugins = cast(List[str], d.pop("plugins", UNSET)) + + data_type = cls( + element=element, + children=children, + formatters=formatters, + plugins=plugins, + ) + + data_type.additional_properties = d + return data_type + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/data_type_children.py b/guard-rails-api-client/guard_rails_api_client/models/data_type_children.py new file mode 100644 index 0000000..24b6f01 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/data_type_children.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="DataTypeChildren") + + +@_attrs_define +class DataTypeChildren: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + data_type_children = cls() + + data_type_children.additional_properties = d + return data_type_children + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/document.py b/guard-rails-api-client/guard_rails_api_client/models/document.py new file mode 100644 index 0000000..84ea9a7 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/document.py @@ -0,0 +1,98 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.document_metadata import DocumentMetadata + from ..models.document_pages import DocumentPages + + +T = TypeVar("T", bound="Document") + + +@_attrs_define +class Document: + """ + Attributes: + id (Union[Unset, str]): + pages (Union[Unset, DocumentPages]): + metadata (Union[Unset, DocumentMetadata]): + """ + + id: Union[Unset, str] = UNSET + pages: Union[Unset, "DocumentPages"] = UNSET + metadata: Union[Unset, "DocumentMetadata"] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + id = self.id + + pages: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.pages, Unset): + pages = self.pages.to_dict() + + metadata: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.metadata, Unset): + metadata = self.metadata.to_dict() + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if id is not UNSET: + field_dict["id"] = id + if pages is not UNSET: + field_dict["pages"] = pages + if metadata is not UNSET: + field_dict["metadata"] = metadata + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.document_metadata import DocumentMetadata + from ..models.document_pages import DocumentPages + + d = src_dict.copy() + id = d.pop("id", UNSET) + + _pages = d.pop("pages", UNSET) + pages: Union[Unset, DocumentPages] + if isinstance(_pages, Unset): + pages = UNSET + else: + pages = DocumentPages.from_dict(_pages) + + _metadata = d.pop("metadata", UNSET) + metadata: Union[Unset, DocumentMetadata] + if isinstance(_metadata, Unset): + metadata = UNSET + else: + metadata = DocumentMetadata.from_dict(_metadata) + + document = cls( + id=id, + pages=pages, + metadata=metadata, + ) + + document.additional_properties = d + return document + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/document_metadata.py b/guard-rails-api-client/guard_rails_api_client/models/document_metadata.py new file mode 100644 index 0000000..8a3e57f --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/document_metadata.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="DocumentMetadata") + + +@_attrs_define +class DocumentMetadata: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + document_metadata = cls() + + document_metadata.additional_properties = d + return document_metadata + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/document_pages.py b/guard-rails-api-client/guard_rails_api_client/models/document_pages.py new file mode 100644 index 0000000..bb9bf31 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/document_pages.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="DocumentPages") + + +@_attrs_define +class DocumentPages: + """ """ + + additional_properties: Dict[str, str] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + document_pages = cls() + + document_pages.additional_properties = d + return document_pages + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> str: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: str) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/guard.py b/guard-rails-api-client/guard_rails_api_client/models/guard.py new file mode 100644 index 0000000..1fcb3dd --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/guard.py @@ -0,0 +1,119 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.guard_guard_config import GuardGuardConfig + from ..models.rail_spec import RailSpec + + +T = TypeVar("T", bound="Guard") + + +@_attrs_define +class Guard: + """ + Attributes: + name (str): A unique name for this guard. + railspec (RailSpec): A JSONified version of the user provided railspec. + description (Union[Unset, str]): A description of this guard. + num_reasks (Union[Unset, int]): The number of re-asks to perform during validation when a validation fails. + guard_config (Union[Unset, GuardGuardConfig]): Addtional guard configuration attributes. + llm_endpoint (Union[Unset, str]): The endpoint for the targetted LLM. + """ + + name: str + railspec: "RailSpec" + description: Union[Unset, str] = UNSET + num_reasks: Union[Unset, int] = UNSET + guard_config: Union[Unset, "GuardGuardConfig"] = UNSET + llm_endpoint: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + name = self.name + + railspec = self.railspec.to_dict() + + description = self.description + + num_reasks = self.num_reasks + + guard_config: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.guard_config, Unset): + guard_config = self.guard_config.to_dict() + + llm_endpoint = self.llm_endpoint + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "railspec": railspec, + } + ) + if description is not UNSET: + field_dict["description"] = description + if num_reasks is not UNSET: + field_dict["numReasks"] = num_reasks + if guard_config is not UNSET: + field_dict["guardConfig"] = guard_config + if llm_endpoint is not UNSET: + field_dict["llmEndpoint"] = llm_endpoint + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.guard_guard_config import GuardGuardConfig + from ..models.rail_spec import RailSpec + + d = src_dict.copy() + name = d.pop("name") + + railspec = RailSpec.from_dict(d.pop("railspec")) + + description = d.pop("description", UNSET) + + num_reasks = d.pop("numReasks", UNSET) + + _guard_config = d.pop("guardConfig", UNSET) + guard_config: Union[Unset, GuardGuardConfig] + if isinstance(_guard_config, Unset): + guard_config = UNSET + else: + guard_config = GuardGuardConfig.from_dict(_guard_config) + + llm_endpoint = d.pop("llmEndpoint", UNSET) + + guard = cls( + name=name, + railspec=railspec, + description=description, + num_reasks=num_reasks, + guard_config=guard_config, + llm_endpoint=llm_endpoint, + ) + + guard.additional_properties = d + return guard + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/guard_guard_config.py b/guard-rails-api-client/guard_rails_api_client/models/guard_guard_config.py new file mode 100644 index 0000000..5f35b3e --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/guard_guard_config.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="GuardGuardConfig") + + +@_attrs_define +class GuardGuardConfig: + """Addtional guard configuration attributes.""" + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + guard_guard_config = cls() + + guard_guard_config.additional_properties = d + return guard_guard_config + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/guard_metrics.py b/guard-rails-api-client/guard_rails_api_client/models/guard_metrics.py new file mode 100644 index 0000000..1d53c00 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/guard_metrics.py @@ -0,0 +1,128 @@ +import datetime +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from dateutil.parser import isoparse + +from ..models.status import Status + +T = TypeVar("T", bound="GuardMetrics") + + +@_attrs_define +class GuardMetrics: + """ + Attributes: + request_id (str): The id of the request this metric entry is for (i.e. the specific call to + /guards/{guardName}/validate) + guard_name (str): The name of the Guard + timestamp (datetime.datetime): The start time of the span the metrics were captured within (ISO 8601 format; See + https://www.rfc-editor.org/rfc/rfc3339#section-5.6) + run_duration (float): The total span duration of the guard run in seconds + status (Status): + reasks (float): The number of times the LLM was reasked + tokens (float): The number of tokens used + raw_llm_ouput (str): The unaltered output from the LLM + validated_output (str): The potentially altered output from validation + """ + + request_id: str + guard_name: str + timestamp: datetime.datetime + run_duration: float + status: Status + reasks: float + tokens: float + raw_llm_ouput: str + validated_output: str + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + request_id = self.request_id + + guard_name = self.guard_name + + timestamp = self.timestamp.isoformat() + + run_duration = self.run_duration + + status = self.status.value + + reasks = self.reasks + + tokens = self.tokens + + raw_llm_ouput = self.raw_llm_ouput + + validated_output = self.validated_output + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "requestId": request_id, + "guardName": guard_name, + "timestamp": timestamp, + "runDuration": run_duration, + "status": status, + "reasks": reasks, + "tokens": tokens, + "rawLlmOuput": raw_llm_ouput, + "validatedOutput": validated_output, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + request_id = d.pop("requestId") + + guard_name = d.pop("guardName") + + timestamp = isoparse(d.pop("timestamp")) + + run_duration = d.pop("runDuration") + + status = Status(d.pop("status")) + + reasks = d.pop("reasks") + + tokens = d.pop("tokens") + + raw_llm_ouput = d.pop("rawLlmOuput") + + validated_output = d.pop("validatedOutput") + + guard_metrics = cls( + request_id=request_id, + guard_name=guard_name, + timestamp=timestamp, + run_duration=run_duration, + status=status, + reasks=reasks, + tokens=tokens, + raw_llm_ouput=raw_llm_ouput, + validated_output=validated_output, + ) + + guard_metrics.additional_properties = d + return guard_metrics + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/guard_run_metric_details.py b/guard-rails-api-client/guard_rails_api_client/models/guard_run_metric_details.py new file mode 100644 index 0000000..58434f2 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/guard_run_metric_details.py @@ -0,0 +1,92 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.guard_run_step import GuardRunStep + + +T = TypeVar("T", bound="GuardRunMetricDetails") + + +@_attrs_define +class GuardRunMetricDetails: + """ + Attributes: + steps (List['GuardRunStep']): + prompt (Union[Unset, str]): + instructions (Union[Unset, str]): + """ + + steps: List["GuardRunStep"] + prompt: Union[Unset, str] = UNSET + instructions: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + steps = [] + for steps_item_data in self.steps: + steps_item = steps_item_data.to_dict() + steps.append(steps_item) + + prompt = self.prompt + + instructions = self.instructions + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "steps": steps, + } + ) + if prompt is not UNSET: + field_dict["prompt"] = prompt + if instructions is not UNSET: + field_dict["instructions"] = instructions + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.guard_run_step import GuardRunStep + + d = src_dict.copy() + steps = [] + _steps = d.pop("steps") + for steps_item_data in _steps: + steps_item = GuardRunStep.from_dict(steps_item_data) + + steps.append(steps_item) + + prompt = d.pop("prompt", UNSET) + + instructions = d.pop("instructions", UNSET) + + guard_run_metric_details = cls( + steps=steps, + prompt=prompt, + instructions=instructions, + ) + + guard_run_metric_details.additional_properties = d + return guard_run_metric_details + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/guard_run_metrics.py b/guard-rails-api-client/guard_rails_api_client/models/guard_run_metrics.py new file mode 100644 index 0000000..6d095ac --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/guard_run_metrics.py @@ -0,0 +1,169 @@ +import datetime +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from dateutil.parser import isoparse + +from ..models.status import Status +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.guard_run_step import GuardRunStep + + +T = TypeVar("T", bound="GuardRunMetrics") + + +@_attrs_define +class GuardRunMetrics: + """ + Attributes: + request_id (str): The id of the request this metric entry is for (i.e. the specific call to + /guards/{guardName}/validate) + guard_name (str): The name of the Guard + timestamp (datetime.datetime): The start time of the span the metrics were captured within (ISO 8601 format; See + https://www.rfc-editor.org/rfc/rfc3339#section-5.6) + run_duration (float): The total span duration of the guard run in seconds + status (Status): + reasks (float): The number of times the LLM was reasked + tokens (float): The number of tokens used + raw_llm_ouput (str): The unaltered output from the LLM + validated_output (str): The potentially altered output from validation + steps (List['GuardRunStep']): + prompt (Union[Unset, str]): + instructions (Union[Unset, str]): + """ + + request_id: str + guard_name: str + timestamp: datetime.datetime + run_duration: float + status: Status + reasks: float + tokens: float + raw_llm_ouput: str + validated_output: str + steps: List["GuardRunStep"] + prompt: Union[Unset, str] = UNSET + instructions: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + request_id = self.request_id + + guard_name = self.guard_name + + timestamp = self.timestamp.isoformat() + + run_duration = self.run_duration + + status = self.status.value + + reasks = self.reasks + + tokens = self.tokens + + raw_llm_ouput = self.raw_llm_ouput + + validated_output = self.validated_output + + steps = [] + for steps_item_data in self.steps: + steps_item = steps_item_data.to_dict() + steps.append(steps_item) + + prompt = self.prompt + + instructions = self.instructions + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "requestId": request_id, + "guardName": guard_name, + "timestamp": timestamp, + "runDuration": run_duration, + "status": status, + "reasks": reasks, + "tokens": tokens, + "rawLlmOuput": raw_llm_ouput, + "validatedOutput": validated_output, + "steps": steps, + } + ) + if prompt is not UNSET: + field_dict["prompt"] = prompt + if instructions is not UNSET: + field_dict["instructions"] = instructions + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.guard_run_step import GuardRunStep + + d = src_dict.copy() + request_id = d.pop("requestId") + + guard_name = d.pop("guardName") + + timestamp = isoparse(d.pop("timestamp")) + + run_duration = d.pop("runDuration") + + status = Status(d.pop("status")) + + reasks = d.pop("reasks") + + tokens = d.pop("tokens") + + raw_llm_ouput = d.pop("rawLlmOuput") + + validated_output = d.pop("validatedOutput") + + steps = [] + _steps = d.pop("steps") + for steps_item_data in _steps: + steps_item = GuardRunStep.from_dict(steps_item_data) + + steps.append(steps_item) + + prompt = d.pop("prompt", UNSET) + + instructions = d.pop("instructions", UNSET) + + guard_run_metrics = cls( + request_id=request_id, + guard_name=guard_name, + timestamp=timestamp, + run_duration=run_duration, + status=status, + reasks=reasks, + tokens=tokens, + raw_llm_ouput=raw_llm_ouput, + validated_output=validated_output, + steps=steps, + prompt=prompt, + instructions=instructions, + ) + + guard_run_metrics.additional_properties = d + return guard_run_metrics + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/guard_run_step.py b/guard-rails-api-client/guard_rails_api_client/models/guard_run_step.py new file mode 100644 index 0000000..3fbb577 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/guard_run_step.py @@ -0,0 +1,80 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.validator_metrics import ValidatorMetrics + + +T = TypeVar("T", bound="GuardRunStep") + + +@_attrs_define +class GuardRunStep: + """ + Attributes: + step_number (float): + validator_metrics (List['ValidatorMetrics']): + """ + + step_number: float + validator_metrics: List["ValidatorMetrics"] + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + step_number = self.step_number + + validator_metrics = [] + for validator_metrics_item_data in self.validator_metrics: + validator_metrics_item = validator_metrics_item_data.to_dict() + validator_metrics.append(validator_metrics_item) + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "stepNumber": step_number, + "validatorMetrics": validator_metrics, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.validator_metrics import ValidatorMetrics + + d = src_dict.copy() + step_number = d.pop("stepNumber") + + validator_metrics = [] + _validator_metrics = d.pop("validatorMetrics") + for validator_metrics_item_data in _validator_metrics: + validator_metrics_item = ValidatorMetrics.from_dict(validator_metrics_item_data) + + validator_metrics.append(validator_metrics_item) + + guard_run_step = cls( + step_number=step_number, + validator_metrics=validator_metrics, + ) + + guard_run_step.additional_properties = d + return guard_run_step + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/health_check.py b/guard-rails-api-client/guard_rails_api_client/models/health_check.py new file mode 100644 index 0000000..21e0841 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/health_check.py @@ -0,0 +1,66 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HealthCheck") + + +@_attrs_define +class HealthCheck: + """ + Attributes: + status (int): A valid http status code + message (str): A message explaining the status + """ + + status: int + message: str + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + status = self.status + + message = self.message + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "status": status, + "message": message, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + status = d.pop("status") + + message = d.pop("message") + + health_check = cls( + status=status, + message=message, + ) + + health_check.additional_properties = d + return health_check + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history.py b/guard-rails-api-client/guard_rails_api_client/models/history.py new file mode 100644 index 0000000..5090d1a --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/history.py @@ -0,0 +1,74 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.history_event import HistoryEvent + + +T = TypeVar("T", bound="History") + + +@_attrs_define +class History: + """ + Attributes: + history (Union[Unset, List['HistoryEvent']]): + """ + + history: Union[Unset, List["HistoryEvent"]] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + history: Union[Unset, List[Dict[str, Any]]] = UNSET + if not isinstance(self.history, Unset): + history = [] + for history_item_data in self.history: + history_item = history_item_data.to_dict() + history.append(history_item) + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if history is not UNSET: + field_dict["history"] = history + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.history_event import HistoryEvent + + d = src_dict.copy() + history = [] + _history = d.pop("history", UNSET) + for history_item_data in _history or []: + history_item = HistoryEvent.from_dict(history_item_data) + + history.append(history_item) + + history = cls( + history=history, + ) + + history.additional_properties = d + return history + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event.py b/guard-rails-api-client/guard_rails_api_client/models/history_event.py new file mode 100644 index 0000000..2795cb1 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/history_event.py @@ -0,0 +1,146 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.history_event_parsed_output import HistoryEventParsedOutput + from ..models.history_event_prompt import HistoryEventPrompt + from ..models.history_event_reasks_item import HistoryEventReasksItem + from ..models.history_event_validated_output import HistoryEventValidatedOutput + + +T = TypeVar("T", bound="HistoryEvent") + + +@_attrs_define +class HistoryEvent: + """ + Attributes: + instructions (Union[Unset, str]): + output (Union[Unset, str]): + parsed_output (Union[Unset, HistoryEventParsedOutput]): + prompt (Union[Unset, HistoryEventPrompt]): + reasks (Union[Unset, List['HistoryEventReasksItem']]): + validated_output (Union[Unset, HistoryEventValidatedOutput]): + """ + + instructions: Union[Unset, str] = UNSET + output: Union[Unset, str] = UNSET + parsed_output: Union[Unset, "HistoryEventParsedOutput"] = UNSET + prompt: Union[Unset, "HistoryEventPrompt"] = UNSET + reasks: Union[Unset, List["HistoryEventReasksItem"]] = UNSET + validated_output: Union[Unset, "HistoryEventValidatedOutput"] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + instructions = self.instructions + + output = self.output + + parsed_output: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.parsed_output, Unset): + parsed_output = self.parsed_output.to_dict() + + prompt: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.prompt, Unset): + prompt = self.prompt.to_dict() + + reasks: Union[Unset, List[Dict[str, Any]]] = UNSET + if not isinstance(self.reasks, Unset): + reasks = [] + for reasks_item_data in self.reasks: + reasks_item = reasks_item_data.to_dict() + reasks.append(reasks_item) + + validated_output: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.validated_output, Unset): + validated_output = self.validated_output.to_dict() + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if instructions is not UNSET: + field_dict["instructions"] = instructions + if output is not UNSET: + field_dict["output"] = output + if parsed_output is not UNSET: + field_dict["parsedOutput"] = parsed_output + if prompt is not UNSET: + field_dict["prompt"] = prompt + if reasks is not UNSET: + field_dict["reasks"] = reasks + if validated_output is not UNSET: + field_dict["validatedOutput"] = validated_output + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.history_event_parsed_output import HistoryEventParsedOutput + from ..models.history_event_prompt import HistoryEventPrompt + from ..models.history_event_reasks_item import HistoryEventReasksItem + from ..models.history_event_validated_output import HistoryEventValidatedOutput + + d = src_dict.copy() + instructions = d.pop("instructions", UNSET) + + output = d.pop("output", UNSET) + + _parsed_output = d.pop("parsedOutput", UNSET) + parsed_output: Union[Unset, HistoryEventParsedOutput] + if isinstance(_parsed_output, Unset): + parsed_output = UNSET + else: + parsed_output = HistoryEventParsedOutput.from_dict(_parsed_output) + + _prompt = d.pop("prompt", UNSET) + prompt: Union[Unset, HistoryEventPrompt] + if isinstance(_prompt, Unset): + prompt = UNSET + else: + prompt = HistoryEventPrompt.from_dict(_prompt) + + reasks = [] + _reasks = d.pop("reasks", UNSET) + for reasks_item_data in _reasks or []: + reasks_item = HistoryEventReasksItem.from_dict(reasks_item_data) + + reasks.append(reasks_item) + + _validated_output = d.pop("validatedOutput", UNSET) + validated_output: Union[Unset, HistoryEventValidatedOutput] + if isinstance(_validated_output, Unset): + validated_output = UNSET + else: + validated_output = HistoryEventValidatedOutput.from_dict(_validated_output) + + history_event = cls( + instructions=instructions, + output=output, + parsed_output=parsed_output, + prompt=prompt, + reasks=reasks, + validated_output=validated_output, + ) + + history_event.additional_properties = d + return history_event + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py b/guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py new file mode 100644 index 0000000..8e009d8 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HistoryEventParsedOutput") + + +@_attrs_define +class HistoryEventParsedOutput: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + history_event_parsed_output = cls() + + history_event_parsed_output.additional_properties = d + return history_event_parsed_output + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event_prompt.py b/guard-rails-api-client/guard_rails_api_client/models/history_event_prompt.py new file mode 100644 index 0000000..da6cccf --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/history_event_prompt.py @@ -0,0 +1,58 @@ +from typing import Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="HistoryEventPrompt") + + +@_attrs_define +class HistoryEventPrompt: + """ + Attributes: + source (Union[Unset, str]): + """ + + source: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + source = self.source + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if source is not UNSET: + field_dict["source"] = source + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + source = d.pop("source", UNSET) + + history_event_prompt = cls( + source=source, + ) + + history_event_prompt.additional_properties = d + return history_event_prompt + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event_reasks_item.py b/guard-rails-api-client/guard_rails_api_client/models/history_event_reasks_item.py new file mode 100644 index 0000000..ca979c0 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/history_event_reasks_item.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HistoryEventReasksItem") + + +@_attrs_define +class HistoryEventReasksItem: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + history_event_reasks_item = cls() + + history_event_reasks_item.additional_properties = d + return history_event_reasks_item + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py b/guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py new file mode 100644 index 0000000..4e882a5 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HistoryEventValidatedOutput") + + +@_attrs_define +class HistoryEventValidatedOutput: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + history_event_validated_output = cls() + + history_event_validated_output.additional_properties = d + return history_event_validated_output + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/http_error.py b/guard-rails-api-client/guard_rails_api_client/models/http_error.py new file mode 100644 index 0000000..575061c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/http_error.py @@ -0,0 +1,111 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.http_error_fields import HttpErrorFields + + +T = TypeVar("T", bound="HttpError") + + +@_attrs_define +class HttpError: + """ + Attributes: + status (int): A valid http status code + message (str): A message explaining the status + cause (Union[Unset, str]): Used to describe the origin of an error if that original error has meaning to the + client. This field should add specificity to 'message'. + fields (Union[Unset, HttpErrorFields]): Used to identify specific fields in a JSON body that caused the error. + Typically only used for 4xx type responses. The key should be the json path to the invalid property and the + value should be a list of error messages specific to that property. + context (Union[Unset, str]): Used to identify what part of the request caused the error for non-JSON payloads. + """ + + status: int + message: str + cause: Union[Unset, str] = UNSET + fields: Union[Unset, "HttpErrorFields"] = UNSET + context: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + status = self.status + + message = self.message + + cause = self.cause + + fields: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.fields, Unset): + fields = self.fields.to_dict() + + context = self.context + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "status": status, + "message": message, + } + ) + if cause is not UNSET: + field_dict["cause"] = cause + if fields is not UNSET: + field_dict["fields"] = fields + if context is not UNSET: + field_dict["context"] = context + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.http_error_fields import HttpErrorFields + + d = src_dict.copy() + status = d.pop("status") + + message = d.pop("message") + + cause = d.pop("cause", UNSET) + + _fields = d.pop("fields", UNSET) + fields: Union[Unset, HttpErrorFields] + if isinstance(_fields, Unset): + fields = UNSET + else: + fields = HttpErrorFields.from_dict(_fields) + + context = d.pop("context", UNSET) + + http_error = cls( + status=status, + message=message, + cause=cause, + fields=fields, + context=context, + ) + + http_error.additional_properties = d + return http_error + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/http_error_fields.py b/guard-rails-api-client/guard_rails_api_client/models/http_error_fields.py new file mode 100644 index 0000000..ff3e8d0 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/http_error_fields.py @@ -0,0 +1,54 @@ +from typing import Any, Dict, List, Type, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HttpErrorFields") + + +@_attrs_define +class HttpErrorFields: + """Used to identify specific fields in a JSON body that caused the error. Typically only used for 4xx type responses. + The key should be the json path to the invalid property and the value should be a list of error messages specific to + that property. + + """ + + additional_properties: Dict[str, List[str]] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + for prop_name, prop in self.additional_properties.items(): + field_dict[prop_name] = prop + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + http_error_fields = cls() + + additional_properties = {} + for prop_name, prop_dict in d.items(): + additional_property = cast(List[str], prop_dict) + + additional_properties[prop_name] = additional_property + + http_error_fields.additional_properties = additional_properties + return http_error_fields + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> List[str]: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: List[str]) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/ingestion.py b/guard-rails-api-client/guard_rails_api_client/models/ingestion.py new file mode 100644 index 0000000..6e92114 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/ingestion.py @@ -0,0 +1,145 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.ingestion_metadata import IngestionMetadata + + +T = TypeVar("T", bound="Ingestion") + + +@_attrs_define +class Ingestion: + """ + Attributes: + id (Union[Unset, str]): + guard_id (Union[Unset, str]): + embeddings (Union[Unset, List[List[float]]]): + document_id (Union[Unset, str]): + metadata (Union[Unset, IngestionMetadata]): + validator_id (Union[Unset, str]): + page_id (Union[Unset, str]): + chunk_id (Union[Unset, str]): + """ + + id: Union[Unset, str] = UNSET + guard_id: Union[Unset, str] = UNSET + embeddings: Union[Unset, List[List[float]]] = UNSET + document_id: Union[Unset, str] = UNSET + metadata: Union[Unset, "IngestionMetadata"] = UNSET + validator_id: Union[Unset, str] = UNSET + page_id: Union[Unset, str] = UNSET + chunk_id: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + id = self.id + + guard_id = self.guard_id + + embeddings: Union[Unset, List[List[float]]] = UNSET + if not isinstance(self.embeddings, Unset): + embeddings = [] + for embeddings_item_data in self.embeddings: + embeddings_item = embeddings_item_data + + embeddings.append(embeddings_item) + + document_id = self.document_id + + metadata: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.metadata, Unset): + metadata = self.metadata.to_dict() + + validator_id = self.validator_id + + page_id = self.page_id + + chunk_id = self.chunk_id + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if id is not UNSET: + field_dict["id"] = id + if guard_id is not UNSET: + field_dict["guardId"] = guard_id + if embeddings is not UNSET: + field_dict["embeddings"] = embeddings + if document_id is not UNSET: + field_dict["documentId"] = document_id + if metadata is not UNSET: + field_dict["metadata"] = metadata + if validator_id is not UNSET: + field_dict["validatorId"] = validator_id + if page_id is not UNSET: + field_dict["pageId"] = page_id + if chunk_id is not UNSET: + field_dict["chunkId"] = chunk_id + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.ingestion_metadata import IngestionMetadata + + d = src_dict.copy() + id = d.pop("id", UNSET) + + guard_id = d.pop("guardId", UNSET) + + embeddings = [] + _embeddings = d.pop("embeddings", UNSET) + for embeddings_item_data in _embeddings or []: + embeddings_item = cast(List[float], embeddings_item_data) + + embeddings.append(embeddings_item) + + document_id = d.pop("documentId", UNSET) + + _metadata = d.pop("metadata", UNSET) + metadata: Union[Unset, IngestionMetadata] + if isinstance(_metadata, Unset): + metadata = UNSET + else: + metadata = IngestionMetadata.from_dict(_metadata) + + validator_id = d.pop("validatorId", UNSET) + + page_id = d.pop("pageId", UNSET) + + chunk_id = d.pop("chunkId", UNSET) + + ingestion = cls( + id=id, + guard_id=guard_id, + embeddings=embeddings, + document_id=document_id, + metadata=metadata, + validator_id=validator_id, + page_id=page_id, + chunk_id=chunk_id, + ) + + ingestion.additional_properties = d + return ingestion + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/ingestion_metadata.py b/guard-rails-api-client/guard_rails_api_client/models/ingestion_metadata.py new file mode 100644 index 0000000..28b146d --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/ingestion_metadata.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="IngestionMetadata") + + +@_attrs_define +class IngestionMetadata: + """ """ + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + ingestion_metadata = cls() + + ingestion_metadata.additional_properties = d + return ingestion_metadata + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/ingestion_payload.py b/guard-rails-api-client/guard_rails_api_client/models/ingestion_payload.py new file mode 100644 index 0000000..0ae9044 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/ingestion_payload.py @@ -0,0 +1,98 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.document import Document + + +T = TypeVar("T", bound="IngestionPayload") + + +@_attrs_define +class IngestionPayload: + """ + Attributes: + articles (Union[Unset, Document]): + guard_id (Union[Unset, str]): + validator_id (Union[Unset, str]): + chunk_id (Union[Unset, str]): + """ + + articles: Union[Unset, "Document"] = UNSET + guard_id: Union[Unset, str] = UNSET + validator_id: Union[Unset, str] = UNSET + chunk_id: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + articles: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.articles, Unset): + articles = self.articles.to_dict() + + guard_id = self.guard_id + + validator_id = self.validator_id + + chunk_id = self.chunk_id + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if articles is not UNSET: + field_dict["articles"] = articles + if guard_id is not UNSET: + field_dict["guardId"] = guard_id + if validator_id is not UNSET: + field_dict["validatorId"] = validator_id + if chunk_id is not UNSET: + field_dict["chunkId"] = chunk_id + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.document import Document + + d = src_dict.copy() + _articles = d.pop("articles", UNSET) + articles: Union[Unset, Document] + if isinstance(_articles, Unset): + articles = UNSET + else: + articles = Document.from_dict(_articles) + + guard_id = d.pop("guardId", UNSET) + + validator_id = d.pop("validatorId", UNSET) + + chunk_id = d.pop("chunkId", UNSET) + + ingestion_payload = cls( + articles=articles, + guard_id=guard_id, + validator_id=validator_id, + chunk_id=chunk_id, + ) + + ingestion_payload.additional_properties = d + return ingestion_payload + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/json_schema.py b/guard-rails-api-client/guard_rails_api_client/models/json_schema.py new file mode 100644 index 0000000..d1b4f4e --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/json_schema.py @@ -0,0 +1,56 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.data_type import DataType + + +T = TypeVar("T", bound="JsonSchema") + + +@_attrs_define +class JsonSchema: + """ """ + + additional_properties: Dict[str, "DataType"] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + for prop_name, prop in self.additional_properties.items(): + field_dict[prop_name] = prop.to_dict() + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.data_type import DataType + + d = src_dict.copy() + json_schema = cls() + + additional_properties = {} + for prop_name, prop_dict in d.items(): + additional_property = DataType.from_dict(prop_dict) + + additional_properties[prop_name] = additional_property + + json_schema.additional_properties = additional_properties + return json_schema + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> "DataType": + return self.additional_properties[key] + + def __setitem__(self, key: str, value: "DataType") -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/on_fail.py b/guard-rails-api-client/guard_rails_api_client/models/on_fail.py new file mode 100644 index 0000000..6fb6fae --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/on_fail.py @@ -0,0 +1,68 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.on_fail_options import OnFailOptions + +T = TypeVar("T", bound="OnFail") + + +@_attrs_define +class OnFail: + """ + Attributes: + validator_tag (str): + method (OnFailOptions): + """ + + validator_tag: str + method: OnFailOptions + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + validator_tag = self.validator_tag + + method = self.method.value + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "validatorTag": validator_tag, + "method": method, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + validator_tag = d.pop("validatorTag") + + method = OnFailOptions(d.pop("method")) + + on_fail = cls( + validator_tag=validator_tag, + method=method, + ) + + on_fail.additional_properties = d + return on_fail + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/on_fail_options.py b/guard-rails-api-client/guard_rails_api_client/models/on_fail_options.py new file mode 100644 index 0000000..93c2420 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/on_fail_options.py @@ -0,0 +1,14 @@ +from enum import Enum + + +class OnFailOptions(str, Enum): + EXCEPTION = "exception" + FILTER = "filter" + FIX = "fix" + FIX_REASK = "fix_reask" + NOOP = "noop" + REASK = "reask" + REFRAIN = "refrain" + + def __str__(self) -> str: + return str(self.value) diff --git a/guard-rails-api-client/guard_rails_api_client/models/projection.py b/guard-rails-api-client/guard_rails_api_client/models/projection.py new file mode 100644 index 0000000..e11d6de --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/projection.py @@ -0,0 +1,114 @@ +from typing import Any, Dict, List, Type, TypeVar, Union, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="Projection") + + +@_attrs_define +class Projection: + """ + Attributes: + id (Union[Unset, str]): + guard_id (Union[Unset, str]): + validator_id (Union[Unset, str]): + document_id (Union[Unset, str]): + page_id (Union[Unset, str]): + chunk_id (Union[Unset, str]): + projection (Union[Unset, List[float]]): + """ + + id: Union[Unset, str] = UNSET + guard_id: Union[Unset, str] = UNSET + validator_id: Union[Unset, str] = UNSET + document_id: Union[Unset, str] = UNSET + page_id: Union[Unset, str] = UNSET + chunk_id: Union[Unset, str] = UNSET + projection: Union[Unset, List[float]] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + id = self.id + + guard_id = self.guard_id + + validator_id = self.validator_id + + document_id = self.document_id + + page_id = self.page_id + + chunk_id = self.chunk_id + + projection: Union[Unset, List[float]] = UNSET + if not isinstance(self.projection, Unset): + projection = self.projection + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if id is not UNSET: + field_dict["id"] = id + if guard_id is not UNSET: + field_dict["guardId"] = guard_id + if validator_id is not UNSET: + field_dict["validatorId"] = validator_id + if document_id is not UNSET: + field_dict["documentId"] = document_id + if page_id is not UNSET: + field_dict["pageId"] = page_id + if chunk_id is not UNSET: + field_dict["chunkId"] = chunk_id + if projection is not UNSET: + field_dict["projection"] = projection + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + id = d.pop("id", UNSET) + + guard_id = d.pop("guardId", UNSET) + + validator_id = d.pop("validatorId", UNSET) + + document_id = d.pop("documentId", UNSET) + + page_id = d.pop("pageId", UNSET) + + chunk_id = d.pop("chunkId", UNSET) + + projection = cast(List[float], d.pop("projection", UNSET)) + + projection = cls( + id=id, + guard_id=guard_id, + validator_id=validator_id, + document_id=document_id, + page_id=page_id, + chunk_id=chunk_id, + projection=projection, + ) + + projection.additional_properties = d + return projection + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/rail_spec.py b/guard-rails-api-client/guard_rails_api_client/models/rail_spec.py new file mode 100644 index 0000000..7903190 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/rail_spec.py @@ -0,0 +1,109 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.rail_spec_version import RailSpecVersion +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.schema import Schema + + +T = TypeVar("T", bound="RailSpec") + + +@_attrs_define +class RailSpec: + """A JSONified version of the user provided railspec. + + Attributes: + output_schema (Schema): + prompt (str): + version (RailSpecVersion): Default: RailSpecVersion.VALUE_0. + input_schema (Union[Unset, Schema]): + instructions (Union[Unset, str]): + """ + + output_schema: "Schema" + prompt: str + version: RailSpecVersion = RailSpecVersion.VALUE_0 + input_schema: Union[Unset, "Schema"] = UNSET + instructions: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + output_schema = self.output_schema.to_dict() + + prompt = self.prompt + + version = self.version.value + + input_schema: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.input_schema, Unset): + input_schema = self.input_schema.to_dict() + + instructions = self.instructions + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "outputSchema": output_schema, + "prompt": prompt, + "version": version, + } + ) + if input_schema is not UNSET: + field_dict["inputSchema"] = input_schema + if instructions is not UNSET: + field_dict["instructions"] = instructions + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.schema import Schema + + d = src_dict.copy() + output_schema = Schema.from_dict(d.pop("outputSchema")) + + prompt = d.pop("prompt") + + version = RailSpecVersion(d.pop("version")) + + _input_schema = d.pop("inputSchema", UNSET) + input_schema: Union[Unset, Schema] + if isinstance(_input_schema, Unset): + input_schema = UNSET + else: + input_schema = Schema.from_dict(_input_schema) + + instructions = d.pop("instructions", UNSET) + + rail_spec = cls( + output_schema=output_schema, + prompt=prompt, + version=version, + input_schema=input_schema, + instructions=instructions, + ) + + rail_spec.additional_properties = d + return rail_spec + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/rail_spec_version.py b/guard-rails-api-client/guard_rails_api_client/models/rail_spec_version.py new file mode 100644 index 0000000..f8eaa4c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/rail_spec_version.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class RailSpecVersion(str, Enum): + VALUE_0 = "0.1" + + def __str__(self) -> str: + return str(self.value) diff --git a/guard-rails-api-client/guard_rails_api_client/models/reask.py b/guard-rails-api-client/guard_rails_api_client/models/reask.py new file mode 100644 index 0000000..3ba83de --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/reask.py @@ -0,0 +1,578 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.any_object import AnyObject + + +T = TypeVar("T", bound="Reask") + + +@_attrs_define +class Reask: + """ + Attributes: + incorrect_value (Union['AnyObject', List[Union['AnyObject', List[Union['AnyObject', bool, float, int, str]], + bool, float, int, str]], Unset, bool, float, int, str]): + error_message (Union[Unset, str]): + fix_value (Union['AnyObject', List[Union['AnyObject', List[Union['AnyObject', bool, float, int, str]], bool, + float, int, str]], Unset, bool, float, int, str]): + path (Union[Unset, List[Union['AnyObject', List[Union['AnyObject', List[Union['AnyObject', bool, float, int, + str]], bool, float, int, str]], bool, float, int, str]]]): + """ + + incorrect_value: Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ] = UNSET + error_message: Union[Unset, str] = UNSET + fix_value: Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ] = UNSET + path: Union[ + Unset, + List[ + Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + bool, + float, + int, + str, + ] + ], + ] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + from ..models.any_object import AnyObject + + incorrect_value: Union[ + Dict[str, Any], + List[Union[Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ] + if isinstance(self.incorrect_value, Unset): + incorrect_value = UNSET + elif isinstance(self.incorrect_value, list): + incorrect_value = [] + for componentsschemas_any_array_item_data in self.incorrect_value: + componentsschemas_any_array_item: Union[ + Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str + ] + if isinstance(componentsschemas_any_array_item_data, AnyObject): + componentsschemas_any_array_item = componentsschemas_any_array_item_data.to_dict() + elif isinstance(componentsschemas_any_array_item_data, list): + componentsschemas_any_array_item = [] + for componentsschemas_any_array_item_type_2_item_data in componentsschemas_any_array_item_data: + componentsschemas_any_array_item_type_2_item: Union[Dict[str, Any], bool, float, int, str] + if isinstance(componentsschemas_any_array_item_type_2_item_data, AnyObject): + componentsschemas_any_array_item_type_2_item = ( + componentsschemas_any_array_item_type_2_item_data.to_dict() + ) + else: + componentsschemas_any_array_item_type_2_item = ( + componentsschemas_any_array_item_type_2_item_data + ) + componentsschemas_any_array_item.append(componentsschemas_any_array_item_type_2_item) + + else: + componentsschemas_any_array_item = componentsschemas_any_array_item_data + incorrect_value.append(componentsschemas_any_array_item) + + elif isinstance(self.incorrect_value, AnyObject): + incorrect_value = self.incorrect_value.to_dict() + else: + incorrect_value = self.incorrect_value + + error_message = self.error_message + + fix_value: Union[ + Dict[str, Any], + List[Union[Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ] + if isinstance(self.fix_value, Unset): + fix_value = UNSET + elif isinstance(self.fix_value, list): + fix_value = [] + for componentsschemas_any_array_item_data in self.fix_value: + componentsschemas_any_array_item: Union[ + Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str + ] + if isinstance(componentsschemas_any_array_item_data, AnyObject): + componentsschemas_any_array_item = componentsschemas_any_array_item_data.to_dict() + elif isinstance(componentsschemas_any_array_item_data, list): + componentsschemas_any_array_item = [] + for componentsschemas_any_array_item_type_2_item_data in componentsschemas_any_array_item_data: + componentsschemas_any_array_item_type_2_item: Union[Dict[str, Any], bool, float, int, str] + if isinstance(componentsschemas_any_array_item_type_2_item_data, AnyObject): + componentsschemas_any_array_item_type_2_item = ( + componentsschemas_any_array_item_type_2_item_data.to_dict() + ) + else: + componentsschemas_any_array_item_type_2_item = ( + componentsschemas_any_array_item_type_2_item_data + ) + componentsschemas_any_array_item.append(componentsschemas_any_array_item_type_2_item) + + else: + componentsschemas_any_array_item = componentsschemas_any_array_item_data + fix_value.append(componentsschemas_any_array_item) + + elif isinstance(self.fix_value, AnyObject): + fix_value = self.fix_value.to_dict() + else: + fix_value = self.fix_value + + path: Union[ + Unset, + List[ + Union[ + Dict[str, Any], + List[ + Union[Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str] + ], + bool, + float, + int, + str, + ] + ], + ] = UNSET + if not isinstance(self.path, Unset): + path = [] + for path_item_data in self.path: + path_item: Union[ + Dict[str, Any], + List[ + Union[Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str] + ], + bool, + float, + int, + str, + ] + if isinstance(path_item_data, list): + path_item = [] + for componentsschemas_any_array_item_data in path_item_data: + componentsschemas_any_array_item: Union[ + Dict[str, Any], List[Union[Dict[str, Any], bool, float, int, str]], bool, float, int, str + ] + if isinstance(componentsschemas_any_array_item_data, AnyObject): + componentsschemas_any_array_item = componentsschemas_any_array_item_data.to_dict() + elif isinstance(componentsschemas_any_array_item_data, list): + componentsschemas_any_array_item = [] + for ( + componentsschemas_any_array_item_type_2_item_data + ) in componentsschemas_any_array_item_data: + componentsschemas_any_array_item_type_2_item: Union[ + Dict[str, Any], bool, float, int, str + ] + if isinstance(componentsschemas_any_array_item_type_2_item_data, AnyObject): + componentsschemas_any_array_item_type_2_item = ( + componentsschemas_any_array_item_type_2_item_data.to_dict() + ) + else: + componentsschemas_any_array_item_type_2_item = ( + componentsschemas_any_array_item_type_2_item_data + ) + componentsschemas_any_array_item.append(componentsschemas_any_array_item_type_2_item) + + else: + componentsschemas_any_array_item = componentsschemas_any_array_item_data + path_item.append(componentsschemas_any_array_item) + + elif isinstance(path_item_data, AnyObject): + path_item = path_item_data.to_dict() + else: + path_item = path_item_data + path.append(path_item) + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if incorrect_value is not UNSET: + field_dict["incorrect_value"] = incorrect_value + if error_message is not UNSET: + field_dict["error_message"] = error_message + if fix_value is not UNSET: + field_dict["fix_value"] = fix_value + if path is not UNSET: + field_dict["path"] = path + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.any_object import AnyObject + + d = src_dict.copy() + + def _parse_incorrect_value( + data: object, + ) -> Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ]: + if isinstance(data, Unset): + return data + try: + if not isinstance(data, list): + raise TypeError() + componentsschemas_any_type_0 = [] + _componentsschemas_any_type_0 = data + for componentsschemas_any_array_item_data in _componentsschemas_any_type_0: + + def _parse_componentsschemas_any_array_item( + data: object, + ) -> Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]: + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_array_item_type_0 = AnyObject.from_dict(data) + + return componentsschemas_any_array_item_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, list): + raise TypeError() + componentsschemas_any_array_item_type_2 = [] + _componentsschemas_any_array_item_type_2 = data + for ( + componentsschemas_any_array_item_type_2_item_data + ) in _componentsschemas_any_array_item_type_2: + + def _parse_componentsschemas_any_array_item_type_2_item( + data: object, + ) -> Union["AnyObject", bool, float, int, str]: + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_array_item_type_2_item_type_0 = AnyObject.from_dict(data) + + return componentsschemas_any_array_item_type_2_item_type_0 + except: # noqa: E722 + pass + return cast(Union["AnyObject", bool, float, int, str], data) + + componentsschemas_any_array_item_type_2_item = ( + _parse_componentsschemas_any_array_item_type_2_item( + componentsschemas_any_array_item_type_2_item_data + ) + ) + + componentsschemas_any_array_item_type_2.append( + componentsschemas_any_array_item_type_2_item + ) + + return componentsschemas_any_array_item_type_2 + except: # noqa: E722 + pass + return cast( + Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str], + data, + ) + + componentsschemas_any_array_item = _parse_componentsschemas_any_array_item( + componentsschemas_any_array_item_data + ) + + componentsschemas_any_type_0.append(componentsschemas_any_array_item) + + return componentsschemas_any_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_type_1 = AnyObject.from_dict(data) + + return componentsschemas_any_type_1 + except: # noqa: E722 + pass + return cast( + Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ], + data, + ) + + incorrect_value = _parse_incorrect_value(d.pop("incorrect_value", UNSET)) + + error_message = d.pop("error_message", UNSET) + + def _parse_fix_value( + data: object, + ) -> Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ]: + if isinstance(data, Unset): + return data + try: + if not isinstance(data, list): + raise TypeError() + componentsschemas_any_type_0 = [] + _componentsschemas_any_type_0 = data + for componentsschemas_any_array_item_data in _componentsschemas_any_type_0: + + def _parse_componentsschemas_any_array_item( + data: object, + ) -> Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]: + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_array_item_type_0 = AnyObject.from_dict(data) + + return componentsschemas_any_array_item_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, list): + raise TypeError() + componentsschemas_any_array_item_type_2 = [] + _componentsschemas_any_array_item_type_2 = data + for ( + componentsschemas_any_array_item_type_2_item_data + ) in _componentsschemas_any_array_item_type_2: + + def _parse_componentsschemas_any_array_item_type_2_item( + data: object, + ) -> Union["AnyObject", bool, float, int, str]: + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_array_item_type_2_item_type_0 = AnyObject.from_dict(data) + + return componentsschemas_any_array_item_type_2_item_type_0 + except: # noqa: E722 + pass + return cast(Union["AnyObject", bool, float, int, str], data) + + componentsschemas_any_array_item_type_2_item = ( + _parse_componentsschemas_any_array_item_type_2_item( + componentsschemas_any_array_item_type_2_item_data + ) + ) + + componentsschemas_any_array_item_type_2.append( + componentsschemas_any_array_item_type_2_item + ) + + return componentsschemas_any_array_item_type_2 + except: # noqa: E722 + pass + return cast( + Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str], + data, + ) + + componentsschemas_any_array_item = _parse_componentsschemas_any_array_item( + componentsschemas_any_array_item_data + ) + + componentsschemas_any_type_0.append(componentsschemas_any_array_item) + + return componentsschemas_any_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_type_1 = AnyObject.from_dict(data) + + return componentsschemas_any_type_1 + except: # noqa: E722 + pass + return cast( + Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + Unset, + bool, + float, + int, + str, + ], + data, + ) + + fix_value = _parse_fix_value(d.pop("fix_value", UNSET)) + + path = [] + _path = d.pop("path", UNSET) + for path_item_data in _path or []: + + def _parse_path_item( + data: object, + ) -> Union[ + "AnyObject", + List[Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]], + bool, + float, + int, + str, + ]: + try: + if not isinstance(data, list): + raise TypeError() + componentsschemas_any_type_0 = [] + _componentsschemas_any_type_0 = data + for componentsschemas_any_array_item_data in _componentsschemas_any_type_0: + + def _parse_componentsschemas_any_array_item( + data: object, + ) -> Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str]: + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_array_item_type_0 = AnyObject.from_dict(data) + + return componentsschemas_any_array_item_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, list): + raise TypeError() + componentsschemas_any_array_item_type_2 = [] + _componentsschemas_any_array_item_type_2 = data + for ( + componentsschemas_any_array_item_type_2_item_data + ) in _componentsschemas_any_array_item_type_2: + + def _parse_componentsschemas_any_array_item_type_2_item( + data: object, + ) -> Union["AnyObject", bool, float, int, str]: + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_array_item_type_2_item_type_0 = AnyObject.from_dict( + data + ) + + return componentsschemas_any_array_item_type_2_item_type_0 + except: # noqa: E722 + pass + return cast(Union["AnyObject", bool, float, int, str], data) + + componentsschemas_any_array_item_type_2_item = ( + _parse_componentsschemas_any_array_item_type_2_item( + componentsschemas_any_array_item_type_2_item_data + ) + ) + + componentsschemas_any_array_item_type_2.append( + componentsschemas_any_array_item_type_2_item + ) + + return componentsschemas_any_array_item_type_2 + except: # noqa: E722 + pass + return cast( + Union[ + "AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str + ], + data, + ) + + componentsschemas_any_array_item = _parse_componentsschemas_any_array_item( + componentsschemas_any_array_item_data + ) + + componentsschemas_any_type_0.append(componentsschemas_any_array_item) + + return componentsschemas_any_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_any_type_1 = AnyObject.from_dict(data) + + return componentsschemas_any_type_1 + except: # noqa: E722 + pass + return cast( + Union[ + "AnyObject", + List[ + Union["AnyObject", List[Union["AnyObject", bool, float, int, str]], bool, float, int, str] + ], + bool, + float, + int, + str, + ], + data, + ) + + path_item = _parse_path_item(path_item_data) + + path.append(path_item) + + reask = cls( + incorrect_value=incorrect_value, + error_message=error_message, + fix_value=fix_value, + path=path, + ) + + reask.additional_properties = d + return reask + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/schema.py b/guard-rails-api-client/guard_rails_api_client/models/schema.py new file mode 100644 index 0000000..29359da --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/schema.py @@ -0,0 +1,88 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.data_type import DataType + from ..models.json_schema import JsonSchema + + +T = TypeVar("T", bound="Schema") + + +@_attrs_define +class Schema: + """ + Attributes: + schema (Union['DataType', 'JsonSchema']): + """ + + schema: Union["DataType", "JsonSchema"] + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + from ..models.json_schema import JsonSchema + + schema: Dict[str, Any] + if isinstance(self.schema, JsonSchema): + schema = self.schema.to_dict() + else: + schema = self.schema.to_dict() + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "schema": schema, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.data_type import DataType + from ..models.json_schema import JsonSchema + + d = src_dict.copy() + + def _parse_schema(data: object) -> Union["DataType", "JsonSchema"]: + try: + if not isinstance(data, dict): + raise TypeError() + schema_type_0 = JsonSchema.from_dict(data) + + return schema_type_0 + except: # noqa: E722 + pass + if not isinstance(data, dict): + raise TypeError() + schema_type_1 = DataType.from_dict(data) + + return schema_type_1 + + schema = _parse_schema(d.pop("schema")) + + schema = cls( + schema=schema, + ) + + schema.additional_properties = d + return schema + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/schema_element.py b/guard-rails-api-client/guard_rails_api_client/models/schema_element.py new file mode 100644 index 0000000..e0de8be --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/schema_element.py @@ -0,0 +1,147 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.on_fail import OnFail + + +T = TypeVar("T", bound="SchemaElement") + + +@_attrs_define +class SchemaElement: + """ + Attributes: + type (str): + name (str): + description (Union[Unset, str]): + strict (Union[Unset, bool]): + date_format (Union[Unset, str]): + time_format (Union[Unset, str]): + on_fail (Union[Unset, str]): + on_fails (Union[Unset, List['OnFail']]): + model (Union[Unset, str]): + """ + + type: str + name: str + description: Union[Unset, str] = UNSET + strict: Union[Unset, bool] = UNSET + date_format: Union[Unset, str] = UNSET + time_format: Union[Unset, str] = UNSET + on_fail: Union[Unset, str] = UNSET + on_fails: Union[Unset, List["OnFail"]] = UNSET + model: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + type = self.type + + name = self.name + + description = self.description + + strict = self.strict + + date_format = self.date_format + + time_format = self.time_format + + on_fail = self.on_fail + + on_fails: Union[Unset, List[Dict[str, Any]]] = UNSET + if not isinstance(self.on_fails, Unset): + on_fails = [] + for on_fails_item_data in self.on_fails: + on_fails_item = on_fails_item_data.to_dict() + on_fails.append(on_fails_item) + + model = self.model + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "type": type, + "name": name, + } + ) + if description is not UNSET: + field_dict["description"] = description + if strict is not UNSET: + field_dict["strict"] = strict + if date_format is not UNSET: + field_dict["dateFormat"] = date_format + if time_format is not UNSET: + field_dict["timeFormat"] = time_format + if on_fail is not UNSET: + field_dict["onFail"] = on_fail + if on_fails is not UNSET: + field_dict["onFails"] = on_fails + if model is not UNSET: + field_dict["model"] = model + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.on_fail import OnFail + + d = src_dict.copy() + type = d.pop("type") + + name = d.pop("name") + + description = d.pop("description", UNSET) + + strict = d.pop("strict", UNSET) + + date_format = d.pop("dateFormat", UNSET) + + time_format = d.pop("timeFormat", UNSET) + + on_fail = d.pop("onFail", UNSET) + + on_fails = [] + _on_fails = d.pop("onFails", UNSET) + for on_fails_item_data in _on_fails or []: + on_fails_item = OnFail.from_dict(on_fails_item_data) + + on_fails.append(on_fails_item) + + model = d.pop("model", UNSET) + + schema_element = cls( + type=type, + name=name, + description=description, + strict=strict, + date_format=date_format, + time_format=time_format, + on_fail=on_fail, + on_fails=on_fails, + model=model, + ) + + schema_element.additional_properties = d + return schema_element + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/status.py b/guard-rails-api-client/guard_rails_api_client/models/status.py new file mode 100644 index 0000000..77fbb51 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/status.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class Status(str, Enum): + FAIL = "fail" + PASS = "pass" + + def __str__(self) -> str: + return str(self.value) diff --git a/guard-rails-api-client/guard_rails_api_client/models/validate_payload.py b/guard-rails-api-client/guard_rails_api_client/models/validate_payload.py new file mode 100644 index 0000000..108baf7 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validate_payload.py @@ -0,0 +1,107 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.validate_payload_llm_api import ValidatePayloadLlmApi +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.validate_payload_prompt_params import ValidatePayloadPromptParams + + +T = TypeVar("T", bound="ValidatePayload") + + +@_attrs_define +class ValidatePayload: + """ + Attributes: + llm_output (Union[Unset, str]): The LLM output as a string or the input prompts for the LLM Example: stubbed llm + output. + num_reasks (Union[Unset, int]): An override for the number of re-asks to perform + prompt_params (Union[Unset, ValidatePayloadPromptParams]): additional params for llm prompts + llm_api (Union[Unset, ValidatePayloadLlmApi]): + """ + + llm_output: Union[Unset, str] = UNSET + num_reasks: Union[Unset, int] = UNSET + prompt_params: Union[Unset, "ValidatePayloadPromptParams"] = UNSET + llm_api: Union[Unset, ValidatePayloadLlmApi] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + llm_output = self.llm_output + + num_reasks = self.num_reasks + + prompt_params: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.prompt_params, Unset): + prompt_params = self.prompt_params.to_dict() + + llm_api: Union[Unset, str] = UNSET + if not isinstance(self.llm_api, Unset): + llm_api = self.llm_api.value + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if llm_output is not UNSET: + field_dict["llmOutput"] = llm_output + if num_reasks is not UNSET: + field_dict["numReasks"] = num_reasks + if prompt_params is not UNSET: + field_dict["promptParams"] = prompt_params + if llm_api is not UNSET: + field_dict["llmApi"] = llm_api + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.validate_payload_prompt_params import ValidatePayloadPromptParams + + d = src_dict.copy() + llm_output = d.pop("llmOutput", UNSET) + + num_reasks = d.pop("numReasks", UNSET) + + _prompt_params = d.pop("promptParams", UNSET) + prompt_params: Union[Unset, ValidatePayloadPromptParams] + if isinstance(_prompt_params, Unset): + prompt_params = UNSET + else: + prompt_params = ValidatePayloadPromptParams.from_dict(_prompt_params) + + _llm_api = d.pop("llmApi", UNSET) + llm_api: Union[Unset, ValidatePayloadLlmApi] + if isinstance(_llm_api, Unset): + llm_api = UNSET + else: + llm_api = ValidatePayloadLlmApi(_llm_api) + + validate_payload = cls( + llm_output=llm_output, + num_reasks=num_reasks, + prompt_params=prompt_params, + llm_api=llm_api, + ) + + validate_payload.additional_properties = d + return validate_payload + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/validate_payload_llm_api.py b/guard-rails-api-client/guard_rails_api_client/models/validate_payload_llm_api.py new file mode 100644 index 0000000..560092a --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validate_payload_llm_api.py @@ -0,0 +1,11 @@ +from enum import Enum + + +class ValidatePayloadLlmApi(str, Enum): + OPENAI_CHATCOMPLETION_ACREATE = "openai.ChatCompletion.acreate" + OPENAI_CHATCOMPLETION_CREATE = "openai.ChatCompletion.create" + OPENAI_COMPLETION_ACREATE = "openai.Completion.acreate" + OPENAI_COMPLETION_CREATE = "openai.Completion.create" + + def __str__(self) -> str: + return str(self.value) diff --git a/guard-rails-api-client/guard_rails_api_client/models/validate_payload_prompt_params.py b/guard-rails-api-client/guard_rails_api_client/models/validate_payload_prompt_params.py new file mode 100644 index 0000000..f3c0439 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validate_payload_prompt_params.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ValidatePayloadPromptParams") + + +@_attrs_define +class ValidatePayloadPromptParams: + """additional params for llm prompts""" + + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + validate_payload_prompt_params = cls() + + validate_payload_prompt_params.additional_properties = d + return validate_payload_prompt_params + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/validation_output.py b/guard-rails-api-client/guard_rails_api_client/models/validation_output.py new file mode 100644 index 0000000..3c3c034 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validation_output.py @@ -0,0 +1,103 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.history import History + + +T = TypeVar("T", bound="ValidationOutput") + + +@_attrs_define +class ValidationOutput: + """ + Attributes: + result (bool): Whether the validation passed or failed + validated_output (Union[Unset, str]): + session_history (Union[Unset, List['History']]): + raw_llm_response (Union[Unset, str]): + """ + + result: bool + validated_output: Union[Unset, str] = UNSET + session_history: Union[Unset, List["History"]] = UNSET + raw_llm_response: Union[Unset, str] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + result = self.result + + validated_output = self.validated_output + + session_history: Union[Unset, List[Dict[str, Any]]] = UNSET + if not isinstance(self.session_history, Unset): + session_history = [] + for session_history_item_data in self.session_history: + session_history_item = session_history_item_data.to_dict() + session_history.append(session_history_item) + + raw_llm_response = self.raw_llm_response + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "result": result, + } + ) + if validated_output is not UNSET: + field_dict["validatedOutput"] = validated_output + if session_history is not UNSET: + field_dict["sessionHistory"] = session_history + if raw_llm_response is not UNSET: + field_dict["rawLlmResponse"] = raw_llm_response + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.history import History + + d = src_dict.copy() + result = d.pop("result") + + validated_output = d.pop("validatedOutput", UNSET) + + session_history = [] + _session_history = d.pop("sessionHistory", UNSET) + for session_history_item_data in _session_history or []: + session_history_item = History.from_dict(session_history_item_data) + + session_history.append(session_history_item) + + raw_llm_response = d.pop("rawLlmResponse", UNSET) + + validation_output = cls( + result=result, + validated_output=validated_output, + session_history=session_history, + raw_llm_response=raw_llm_response, + ) + + validation_output.additional_properties = d + return validation_output + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/validator_metrics.py b/guard-rails-api-client/guard_rails_api_client/models/validator_metrics.py new file mode 100644 index 0000000..a886539 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validator_metrics.py @@ -0,0 +1,145 @@ +import datetime +from typing import Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from dateutil.parser import isoparse + +from ..models.status import Status +from ..types import UNSET, Unset + +T = TypeVar("T", bound="ValidatorMetrics") + + +@_attrs_define +class ValidatorMetrics: + """ + Attributes: + instance_id (str): + name (str): + request_id (str): + guard_name (str): + start_time (datetime.datetime): + end_time (datetime.datetime): + duration_in_millis (float): + input_ (str): + output (str): + status (Status): + tokens (Union[Unset, float]): The number of tokens consumed if the validator calls an LLM. Only applies to + validators that call LLMs. + """ + + instance_id: str + name: str + request_id: str + guard_name: str + start_time: datetime.datetime + end_time: datetime.datetime + duration_in_millis: float + input_: str + output: str + status: Status + tokens: Union[Unset, float] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + instance_id = self.instance_id + + name = self.name + + request_id = self.request_id + + guard_name = self.guard_name + + start_time = self.start_time.isoformat() + + end_time = self.end_time.isoformat() + + duration_in_millis = self.duration_in_millis + + input_ = self.input_ + + output = self.output + + status = self.status.value + + tokens = self.tokens + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "instanceId": instance_id, + "name": name, + "requestId": request_id, + "guardName": guard_name, + "startTime": start_time, + "endTime": end_time, + "durationInMillis": duration_in_millis, + "input": input_, + "output": output, + "status": status, + } + ) + if tokens is not UNSET: + field_dict["tokens"] = tokens + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + instance_id = d.pop("instanceId") + + name = d.pop("name") + + request_id = d.pop("requestId") + + guard_name = d.pop("guardName") + + start_time = isoparse(d.pop("startTime")) + + end_time = isoparse(d.pop("endTime")) + + duration_in_millis = d.pop("durationInMillis") + + input_ = d.pop("input") + + output = d.pop("output") + + status = Status(d.pop("status")) + + tokens = d.pop("tokens", UNSET) + + validator_metrics = cls( + instance_id=instance_id, + name=name, + request_id=request_id, + guard_name=guard_name, + start_time=start_time, + end_time=end_time, + duration_in_millis=duration_in_millis, + input_=input_, + output=output, + status=status, + tokens=tokens, + ) + + validator_metrics.additional_properties = d + return validator_metrics + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details.py b/guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details.py new file mode 100644 index 0000000..3ae043c --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details.py @@ -0,0 +1,90 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.on_fail_options import OnFailOptions + +if TYPE_CHECKING: + from ..models.validator_run_metric_details_parameters import ValidatorRunMetricDetailsParameters + + +T = TypeVar("T", bound="ValidatorRunMetricDetails") + + +@_attrs_define +class ValidatorRunMetricDetails: + """ + Attributes: + step_number (int): + result_type (str): + fail_action (OnFailOptions): + parameters (ValidatorRunMetricDetailsParameters): + """ + + step_number: int + result_type: str + fail_action: OnFailOptions + parameters: "ValidatorRunMetricDetailsParameters" + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + step_number = self.step_number + + result_type = self.result_type + + fail_action = self.fail_action.value + + parameters = self.parameters.to_dict() + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "stepNumber": step_number, + "resultType": result_type, + "failAction": fail_action, + "parameters": parameters, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.validator_run_metric_details_parameters import ValidatorRunMetricDetailsParameters + + d = src_dict.copy() + step_number = d.pop("stepNumber") + + result_type = d.pop("resultType") + + fail_action = OnFailOptions(d.pop("failAction")) + + parameters = ValidatorRunMetricDetailsParameters.from_dict(d.pop("parameters")) + + validator_run_metric_details = cls( + step_number=step_number, + result_type=result_type, + fail_action=fail_action, + parameters=parameters, + ) + + validator_run_metric_details.additional_properties = d + return validator_run_metric_details + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details_parameters.py b/guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details_parameters.py new file mode 100644 index 0000000..48ed680 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validator_run_metric_details_parameters.py @@ -0,0 +1,43 @@ +from typing import Any, Dict, List, Type, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ValidatorRunMetricDetailsParameters") + + +@_attrs_define +class ValidatorRunMetricDetailsParameters: + """ """ + + additional_properties: Dict[str, str] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + validator_run_metric_details_parameters = cls() + + validator_run_metric_details_parameters.additional_properties = d + return validator_run_metric_details_parameters + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> str: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: str) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/validator_run_metrics.py b/guard-rails-api-client/guard_rails_api_client/models/validator_run_metrics.py new file mode 100644 index 0000000..94c08e5 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/models/validator_run_metrics.py @@ -0,0 +1,184 @@ +import datetime +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from dateutil.parser import isoparse + +from ..models.on_fail_options import OnFailOptions +from ..models.status import Status +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.validator_run_metric_details_parameters import ValidatorRunMetricDetailsParameters + + +T = TypeVar("T", bound="ValidatorRunMetrics") + + +@_attrs_define +class ValidatorRunMetrics: + """ + Attributes: + instance_id (str): + name (str): + request_id (str): + guard_name (str): + start_time (datetime.datetime): + end_time (datetime.datetime): + duration_in_millis (float): + input_ (str): + output (str): + status (Status): + step_number (int): + result_type (str): + fail_action (OnFailOptions): + parameters (ValidatorRunMetricDetailsParameters): + tokens (Union[Unset, float]): The number of tokens consumed if the validator calls an LLM. Only applies to + validators that call LLMs. + """ + + instance_id: str + name: str + request_id: str + guard_name: str + start_time: datetime.datetime + end_time: datetime.datetime + duration_in_millis: float + input_: str + output: str + status: Status + step_number: int + result_type: str + fail_action: OnFailOptions + parameters: "ValidatorRunMetricDetailsParameters" + tokens: Union[Unset, float] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + instance_id = self.instance_id + + name = self.name + + request_id = self.request_id + + guard_name = self.guard_name + + start_time = self.start_time.isoformat() + + end_time = self.end_time.isoformat() + + duration_in_millis = self.duration_in_millis + + input_ = self.input_ + + output = self.output + + status = self.status.value + + step_number = self.step_number + + result_type = self.result_type + + fail_action = self.fail_action.value + + parameters = self.parameters.to_dict() + + tokens = self.tokens + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "instanceId": instance_id, + "name": name, + "requestId": request_id, + "guardName": guard_name, + "startTime": start_time, + "endTime": end_time, + "durationInMillis": duration_in_millis, + "input": input_, + "output": output, + "status": status, + "stepNumber": step_number, + "resultType": result_type, + "failAction": fail_action, + "parameters": parameters, + } + ) + if tokens is not UNSET: + field_dict["tokens"] = tokens + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.validator_run_metric_details_parameters import ValidatorRunMetricDetailsParameters + + d = src_dict.copy() + instance_id = d.pop("instanceId") + + name = d.pop("name") + + request_id = d.pop("requestId") + + guard_name = d.pop("guardName") + + start_time = isoparse(d.pop("startTime")) + + end_time = isoparse(d.pop("endTime")) + + duration_in_millis = d.pop("durationInMillis") + + input_ = d.pop("input") + + output = d.pop("output") + + status = Status(d.pop("status")) + + step_number = d.pop("stepNumber") + + result_type = d.pop("resultType") + + fail_action = OnFailOptions(d.pop("failAction")) + + parameters = ValidatorRunMetricDetailsParameters.from_dict(d.pop("parameters")) + + tokens = d.pop("tokens", UNSET) + + validator_run_metrics = cls( + instance_id=instance_id, + name=name, + request_id=request_id, + guard_name=guard_name, + start_time=start_time, + end_time=end_time, + duration_in_millis=duration_in_millis, + input_=input_, + output=output, + status=status, + step_number=step_number, + result_type=result_type, + fail_action=fail_action, + parameters=parameters, + tokens=tokens, + ) + + validator_run_metrics.additional_properties = d + return validator_run_metrics + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/py.typed b/guard-rails-api-client/guard_rails_api_client/py.typed new file mode 100644 index 0000000..1aad327 --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561 \ No newline at end of file diff --git a/guard-rails-api-client/guard_rails_api_client/types.py b/guard-rails-api-client/guard_rails_api_client/types.py new file mode 100644 index 0000000..dbdcc5d --- /dev/null +++ b/guard-rails-api-client/guard_rails_api_client/types.py @@ -0,0 +1,44 @@ +""" Contains some shared types for properties """ +from http import HTTPStatus +from typing import BinaryIO, Generic, Literal, MutableMapping, Optional, Tuple, TypeVar + +from attrs import define + + +class Unset: + def __bool__(self) -> Literal[False]: + return False + + +UNSET: Unset = Unset() + +FileJsonType = Tuple[Optional[str], BinaryIO, Optional[str]] + + +@define +class File: + """Contains information for file uploads""" + + payload: BinaryIO + file_name: Optional[str] = None + mime_type: Optional[str] = None + + def to_tuple(self) -> FileJsonType: + """Return a tuple representation that httpx will accept for multipart/form-data""" + return self.file_name, self.payload, self.mime_type + + +T = TypeVar("T") + + +@define +class Response(Generic[T]): + """A response from an endpoint""" + + status_code: HTTPStatus + content: bytes + headers: MutableMapping[str, str] + parsed: Optional[T] + + +__all__ = ["File", "Response", "FileJsonType", "Unset", "UNSET"] diff --git a/guard-rails-api-client/pyproject.toml b/guard-rails-api-client/pyproject.toml new file mode 100644 index 0000000..9fb8112 --- /dev/null +++ b/guard-rails-api-client/pyproject.toml @@ -0,0 +1,6 @@ + +[tool.ruff] +line-length = 120 + +[tool.ruff.lint] +select = ["F", "I", "UP"] diff --git a/guard-rails-api-client/setup.py b/guard-rails-api-client/setup.py new file mode 100644 index 0000000..10cce11 --- /dev/null +++ b/guard-rails-api-client/setup.py @@ -0,0 +1,18 @@ +import pathlib + +from setuptools import find_packages, setup + +here = pathlib.Path(__file__).parent.resolve() +long_description = (here / "README.md").read_text(encoding="utf-8") + +setup( + name="guard-rails-api-client", + version="0.0.0", + description="A client library for accessing GuardRails API", + long_description=long_description, + long_description_content_type="text/markdown", + packages=find_packages(), + python_requires=">=3.8, <4", + install_requires=["httpx >= 0.20.0, < 0.28.0", "attrs >= 21.3.0", "python-dateutil >= 2.8.0, < 3"], + package_data={"guard_rails_api_client": ["py.typed"]}, +) diff --git a/open-api-spec.yml b/open-api-spec.yml new file mode 100644 index 0000000..2e1f059 --- /dev/null +++ b/open-api-spec.yml @@ -0,0 +1,981 @@ +openapi: "3.0.0" +info: + title: GuardRails API + version: "0.0.0" + description: GuardRails CRUD API +paths: + /health-check: + get: + tags: + - Service Health + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: Returns the status of the server + content: + application/json: + schema: + $ref: "#/components/schemas/HealthCheck" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /guards: + get: + operationId: getGuards + tags: + - guard + summary: Fetches the configuration for all Guards the user has access to. + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: A list of Guards. + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Guard" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + post: + operationId: createGuard + tags: + - guard + summary: Creates a Guard + security: + - apiKeyAuth: [] + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/Guard" + responses: + "200": + description: the new Guard + content: + application/json: + schema: + $ref: "#/components/schemas/Guard" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /guards/{guardName}: + get: + operationId: getGuard + tags: + - guard + summary: Fetches a specific Guard + parameters: + - $ref: "#/components/parameters/GuardName" + - $ref: "#/components/parameters/AsOf" + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: the fetched Guard + content: + application/json: + schema: + $ref: "#/components/schemas/Guard" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + put: + operationId: updateGuard + tags: + - guard + summary: Updates a Guard + parameters: + - $ref: "#/components/parameters/GuardName" + security: + - apiKeyAuth: [] + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/Guard" + responses: + "200": + description: the updated Guard + content: + application/json: + schema: + $ref: "#/components/schemas/Guard" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + delete: + operationId: deleteGuard + tags: + - guard + summary: Deletes a Guard + parameters: + - $ref: "#/components/parameters/GuardName" + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: the deleted Guard + content: + application/json: + schema: + $ref: "#/components/schemas/Guard" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /guards/{guardName}/validate: + post: + operationId: validate + tags: + - guard + - validate + summary: Runs the validations specified in a Guard + security: + - apiKeyAuth: [] + - bearerAuth: [] + parameters: + - $ref: "#/components/parameters/GuardName" + - $ref: "#/components/parameters/OpenAiApiKey" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ValidatePayload" + responses: + "200": + description: The output of the validation + content: + application/json: + schema: + $ref: "#/components/schemas/ValidationOutput" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /ingest: + post: + operationId: ingest + summary: Creates and ingests embeddings for a document + parameters: + - $ref: '#/components/parameters/OpenAiApiKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/IngestionPayload' + responses: + '200': # status code + description: uniqie id for the created ingestion object + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Ingestion' + /embeddings/{documentId}: + get: + operationId: getIngestedDocument + summary: Returns a list of ingestion items for given documentId + parameters: + - $ref: '#/components/parameters/documentId' + responses: + '200': # status code + description: ingestion objects + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Ingestion' + put: + operationId: updateIngestedDocument + summary: Updates embeddings for a given documentId + parameters: + - $ref: '#/components/parameters/documentId' + - $ref: '#/components/parameters/OpenAiApiKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/IngestionPayload' + responses: + '200': # status code + description: The updated ingestion object + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Ingestion' + delete: + operationId: deleteIngestedDocument + summary: Deletes embeddings for a given documentId + parameters: + - $ref: '#/components/parameters/documentId' + responses: + '200': # status code + description: The deleted ingestion + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Ingestion' + /guards/{guardName}/embeddings: + get: + operationId: getIngestedDocumentByGuardId + summary: Returns a list of ingestion items for a guard + parameters: + - $ref: "#/components/parameters/GuardName" + responses: + "200": # status code + description: ingestion objects + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Ingestion" + /embeddings/{guardName}/projections: + get: + operationId: getProjection + tags: + - projections + summary: Returns the T-SNE projection for the given Guard id + parameters: + - $ref: "#/components/parameters/GuardName" + - $ref: "#/components/parameters/ValidatorId" + responses: + "200": # status code + description: the projections + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Projection" + put: + operationId: updateProjection + tags: + - projections + summary: Creates of updates projection for a given Guard id + parameters: + - $ref: "#/components/parameters/GuardName" + - $ref: "#/components/parameters/ValidatorId" + responses: + "200": # status code + description: The updated projections + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Projection" + /guards/metrics: + get: + operationId: getGuardMetrics + summary: Returns an array of GuardMetrics for a given time range. If startTime or endTime are ommitted, a five minute duration is used by default. Default page size is 10. + parameters: + - $ref: "#/components/parameters/StartTime" + - $ref: "#/components/parameters/EndTime" + - $ref: "#/components/parameters/PageNumber" + tags: + - Metrics + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: Returns metrics for Guards + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/GuardMetrics" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /guards/{guardName}/runs/{requestId}/metrics: + get: + operationId: getGuardRunMetrics + summary: Returns an instance of GuardRunMetrics for a given request. + parameters: + - $ref: "#/components/parameters/GuardName" + - $ref: "#/components/parameters/RequestId" + tags: + - Metrics + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: Returns metrics for Guard request + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/GuardRunMetrics" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /validators/metrics: + get: + operationId: getValidatorMetrics + summary: Returns an array of ValidatorMetrics for a given time range. If startTime or endTime are ommitted, a five minute duration is used by default. Default page size is 10, but this page size applied to guard steps not validator metrics. Have to think this one out a little more. + parameters: + - $ref: "#/components/parameters/StartTime" + - $ref: "#/components/parameters/EndTime" + - $ref: "#/components/parameters/PageNumber" + tags: + - Metrics + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: Returns metrics for Guards + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/ValidatorMetrics" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" + /validators/{validatorName}/runs/{requestId}/instances/{validatorInstanceId}/metrics: + get: + operationId: getValidatorRunMetrics + summary: Returns an arary of ValidatorRunMetrics for a given request. + parameters: + - $ref: "#/components/parameters/ValidatorName" + - $ref: "#/components/parameters/RequestId" + - $ref: "#/components/parameters/ValidatorInstanceId" + tags: + - Metrics + security: + - apiKeyAuth: [] + - bearerAuth: [] + responses: + "200": + description: Returns metrics for Guard request + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/ValidatorRunMetrics" + default: + description: Unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/HttpError" +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT + apiKeyAuth: + type: apiKey + in: header + name: authorization + description: JWT token + parameters: + GuardName: + name: guardName + in: path + description: Guard name + required: true + schema: + type: string + AsOf: + name: asOf + in: query + description: Used to query for data as it existed at this date and time + required: false + schema: + type: string + format: date-time + OpenAiApiKey: + name: x-openai-api-key + in: header + description: A valid OpenAI API Key for calling LLM's on your behalf + required: false + schema: + type: string + format: password + documentId: + name: documentId + in: path + description: unqiue document id + required: true + schema: + type: string + ValidatorId: + name: validatorId + in: query + description: Id for a specific validator. Used for querying metrics and projections + required: false + schema: + type: string + uuid: + name: uuid + in: path + description: unqiue id for embeddings + required: true + schema: + type: string + StartTime: + name: startTime + in: query + description: Used to specify the start of a time range + required: false + schema: + type: string + format: date-time + EndTime: + name: endTime + in: query + description: Used to specify the end of a time range + required: false + schema: + type: string + format: date-time + PageNumber: + name: page + in: query + description: Used to specify the page number for paginated endpoints. Pages are zero-indexed. + required: false + schema: + type: integer + default: 0 + RequestId: + name: requestId + in: path + description: Request id aka trace id for a validate-{guard-name} span + required: true + schema: + type: string + ValidatorName: + name: validatorName + in: path + description: the validator's registered name + required: true + schema: + type: string + ValidatorInstanceId: + name: validatorInstanceId + in: path + description: the instanceId from ValidatorMetrics + required: true + schema: + type: string + schemas: + HttpError: + type: object + properties: + status: + type: integer + description: A valid http status code + message: + type: string + description: A message explaining the status + cause: + type: string + description: Used to describe the origin of an error if that original error has meaning to the client. This field should add specificity to 'message'. + fields: + type: object + description: Used to identify specific fields in a JSON body that caused the error. Typically only used for 4xx type responses. The key should be the json path to the invalid property and the value should be a list of error messages specific to that property. + additionalProperties: + type: array + items: + type: string + context: + type: string + description: Used to identify what part of the request caused the error for non-JSON payloads. + required: + - status + - message + HealthCheck: + type: object + properties: + status: + type: integer + description: A valid http status code + message: + type: string + description: A message explaining the status + required: + - status + - message + Guard: + type: object + properties: + name: + type: string + description: A unique name for this guard. + description: + type: string + description: A description of this guard. + railspec: + $ref: "#/components/schemas/RailSpec" + numReasks: + type: integer + description: The number of re-asks to perform during validation when a validation fails. + # The below might belong in the /validate endpoint payload + guardConfig: + type: object + description: Addtional guard configuration attributes. + additionalProperties: {} + llmEndpoint: + type: string + description: The endpoint for the targetted LLM. + required: + - name + - railspec + RailSpec: + type: object + description: A JSONified version of the user provided railspec. + properties: + inputSchema: + $ref: "#/components/schemas/Schema" + outputSchema: + $ref: "#/components/schemas/Schema" + instructions: + type: string + prompt: + type: string + version: + type: string + default: "0.1" + enum: + - "0.1" + required: + - outputSchema + - prompt + - version + Schema: + type: object + properties: + schema: + oneOf: + - $ref: "#/components/schemas/JsonSchema" + - $ref: "#/components/schemas/DataType" + required: + - schema + JsonSchema: + type: object + additionalProperties: + $ref: "#/components/schemas/DataType" + DataType: + type: object + properties: + children: + type: object + additionalProperties: {} + formatters: + type: array + items: + type: string + plugins: + type: array + items: + type: string + element: + $ref: "#/components/schemas/SchemaElement" + required: + - element + SchemaElement: + type: object + properties: + type: + type: string + name: + type: string + description: + type: string + strict: + type: boolean + dateFormat: + type: string + timeFormat: + type: string + onFail: + type: string + onFails: + type: array + items: + $ref: "#/components/schemas/OnFail" + model: + type: string + required: + - name + - type + OnFail: + type: object + properties: + validatorTag: + type: string + method: + $ref: "#/components/schemas/OnFailOptions" + required: + - validatorTag + - method + OnFailOptions: + type: string + enum: ["exception", "filter", "fix", "fix_reask", "noop", "reask", "refrain"] + ValidationOutput: + type: object + properties: + result: + type: boolean + description: Whether the validation passed or failed + validatedOutput: + type: string + sessionHistory: + type: array + items: + $ref: "#/components/schemas/History" + rawLlmResponse: + type: string + additionalProperties: {} + required: + - result + History: + type: object + properties: + history: + type: array + items: + $ref: "#/components/schemas/HistoryEvent" + HistoryEvent: + type: object + properties: + instructions: + type: string + output: + type: string + parsedOutput: + type: object + properties: {} + additionalProperties: {} + prompt: + type: object + properties: + source: + type: string + reasks: + type: array + items: + type: object + properties: {} + additionalProperties: {} + validatedOutput: + type: object + properties: {} + additionalProperties: {} + additionalProperties: {} + Reask: + type: object + properties: + incorrect_value: + $ref: "#/components/schemas/Any" + error_message: + type: string + fix_value: + $ref: "#/components/schemas/Any" + path: + type: array + items: + $ref: "#/components/schemas/Any" + Any: + oneOf: + - $ref: "#/components/schemas/AnyArray" + - $ref: "#/components/schemas/AnyObject" + - $ref: "#/components/schemas/AnyPrimitive" + AnyPrimitive: + oneOf: + - type: boolean + - type: integer + - type: number + - type: string + AnyObject: + type: object + properties: {} + additionalProperties: {} + # Cannot generate clients for recursive references + AnyArray: + type: array + items: + oneOf: + - $ref: "#/components/schemas/AnyObject" + - $ref: "#/components/schemas/AnyPrimitive" + - type: array + items: + oneOf: + - $ref: "#/components/schemas/AnyObject" + - $ref: "#/components/schemas/AnyPrimitive" + ValidatePayload: + type: object + properties: + llmOutput: + type: string + description: The LLM output as a string or the input prompts for the LLM + example: stubbed llm output + numReasks: + type: integer + description: An override for the number of re-asks to perform + promptParams: + type: object + description: additional params for llm prompts + properties: {} + additionalProperties: {} + llmApi: + type: string + enum: ["openai.Completion.create", "openai.ChatCompletion.create", "openai.Completion.acreate", "openai.ChatCompletion.acreate"] + additionalProperties: {} + Ingestion: + type: object + properties: + id: + type: string + guardId: + type: string + embeddings: + type: array + items: + type: array + items: + type: number + documentId: + type: string + metadata: + type: object + validatorId: + type: string + pageId: + type: string + chunkId: + type: string + IngestionPayload: + type: object + properties: + articles: + $ref: '#/components/schemas/Document' + guardId: + type: string + validatorId: + type: string + chunkId: + type: string + Document: + type: object + properties: + id: + type: string + pages: + type: object + additionalProperties: + type: string + metadata: + type: object + Projection: + type: object + properties: + id: + type: string + guardId: + type: string + validatorId: + type: string + documentId: + type: string + pageId: + type: string + chunkId: + type: string + projection: + type: array + items: + type: number + GuardMetrics: + type: object + properties: + requestId: + type: string + description: The id of the request this metric entry is for (i.e. the specific call to /guards/{guardName}/validate) + guardName: + type: string + description: The name of the Guard + timestamp: + type: string + format: date-time + description: The start time of the span the metrics were captured within (ISO 8601 format; See https://www.rfc-editor.org/rfc/rfc3339#section-5.6) + runDuration: + type: number + description: The total span duration of the guard run in seconds + status: + $ref: "#/components/schemas/Status" + reasks: + type: number + description: The number of times the LLM was reasked + tokens: + type: number + description: The number of tokens used + rawLlmOuput: + type: string + description: The unaltered output from the LLM + validatedOutput: + type: string + description: The potentially altered output from validation + required: + - requestId + - guardName + - timestamp + - runDuration + - status + - reasks + - tokens + - rawLlmOuput + - validatedOutput + Status: + type: string + enum: ["pass", "fail"] + GuardRunMetrics: + allOf: + - $ref: '#/components/schemas/GuardMetrics' + - $ref: '#/components/schemas/GuardRunMetricDetails' + GuardRunMetricDetails: + type: object + properties: + prompt: + type: string + instructions: + type: string + steps: + type: array + items: + $ref: '#/components/schemas/GuardRunStep' + required: + - steps + GuardRunStep: + type: object + properties: + stepNumber: + type: number + validatorMetrics: + type: array + items: + $ref: '#/components/schemas/ValidatorMetrics' + required: + - stepNumber + - validatorMetrics + ValidatorMetrics: + type: object + properties: + instanceId: + type: string + name: + type: string + requestId: + type: string + guardName: + type: string + startTime: + type: string + format: date-time + endTime: + type: string + format: date-time + durationInMillis: + type: number + input: + type: string + output: + type: string + status: + $ref: "#/components/schemas/Status" + tokens: + type: number + description: The number of tokens consumed if the validator calls an LLM. Only applies to validators that call LLMs. + required: + - instanceId + - name + - requestId + - guardName + - startTime + - endTime + - durationInMillis + - input + - output + - status + ValidatorRunMetrics: + allOf: + - $ref: '#/components/schemas/ValidatorMetrics' + - $ref: '#/components/schemas/ValidatorRunMetricDetails' + ValidatorRunMetricDetails: + type: object + properties: + stepNumber: + type: integer + resultType: + type: string + failAction: + $ref: '#/components/schemas/OnFailOptions' + parameters: + type: object + properties: {} + additionalProperties: + type: string + required: + - stepNumber + - resultType + - failAction + - parameters From 92ba657b7a57176a00176e7b4ef8c7a24994ef7d Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Wed, 28 Feb 2024 12:06:52 -0600 Subject: [PATCH 13/15] remove commented step --- .github/workflows/build-sdk.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/build-sdk.yml b/.github/workflows/build-sdk.yml index 37ecf05..e1dc3a9 100644 --- a/.github/workflows/build-sdk.yml +++ b/.github/workflows/build-sdk.yml @@ -19,11 +19,6 @@ jobs: repository: ${{ github.event.pull_request.head.repo.full_name }} ref: ${{ github.event.pull_request.head.ref }} - # - name: Set up Node.js - # uses: actions/setup-node@v2 - # with: - # node-version: 14 - - name: Merge the OpenAPI Specs run: | chmod +x merge.sh # Make the script executable From f20a0b4eaed709144e83a96f26f2ea2af19856f3 Mon Sep 17 00:00:00 2001 From: Caleb Courier Date: Thu, 29 Feb 2024 13:09:42 -0600 Subject: [PATCH 14/15] make output a string or an object --- service-specs/guardrails-service-spec.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/service-specs/guardrails-service-spec.yml b/service-specs/guardrails-service-spec.yml index 63a4b3f..80b3dcc 100644 --- a/service-specs/guardrails-service-spec.yml +++ b/service-specs/guardrails-service-spec.yml @@ -413,9 +413,9 @@ components: output: type: string parsedOutput: - type: object - properties: {} - additionalProperties: {} + oneOf: + - $ref: "#/components/schemas/AnyObject" + - type: string prompt: type: object properties: @@ -428,9 +428,9 @@ components: properties: {} additionalProperties: {} validatedOutput: - type: object - properties: {} - additionalProperties: {} + oneOf: + - $ref: "#/components/schemas/AnyObject" + - type: string additionalProperties: {} Reask: type: object From c3d8a6d370b56992fb20b588b18c3ea8de53c89e Mon Sep 17 00:00:00 2001 From: CalebCourier Date: Thu, 29 Feb 2024 19:10:09 +0000 Subject: [PATCH 15/15] update generated sdk --- .../guard_rails_api_client/models/__init__.py | 4 - .../models/history_event.py | 74 ++++++++++++------- .../models/history_event_parsed_output.py | 43 ----------- .../models/history_event_validated_output.py | 43 ----------- open-api-spec.yml | 12 +-- 5 files changed, 55 insertions(+), 121 deletions(-) delete mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py delete mode 100644 guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py diff --git a/guard-rails-api-client/guard_rails_api_client/models/__init__.py b/guard-rails-api-client/guard_rails_api_client/models/__init__.py index d8863a3..3822d96 100644 --- a/guard-rails-api-client/guard_rails_api_client/models/__init__.py +++ b/guard-rails-api-client/guard_rails_api_client/models/__init__.py @@ -15,10 +15,8 @@ from .health_check import HealthCheck from .history import History from .history_event import HistoryEvent -from .history_event_parsed_output import HistoryEventParsedOutput from .history_event_prompt import HistoryEventPrompt from .history_event_reasks_item import HistoryEventReasksItem -from .history_event_validated_output import HistoryEventValidatedOutput from .http_error import HttpError from .http_error_fields import HttpErrorFields from .ingestion import Ingestion @@ -59,10 +57,8 @@ "HealthCheck", "History", "HistoryEvent", - "HistoryEventParsedOutput", "HistoryEventPrompt", "HistoryEventReasksItem", - "HistoryEventValidatedOutput", "HttpError", "HttpErrorFields", "Ingestion", diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event.py b/guard-rails-api-client/guard_rails_api_client/models/history_event.py index 2795cb1..5329478 100644 --- a/guard-rails-api-client/guard_rails_api_client/models/history_event.py +++ b/guard-rails-api-client/guard_rails_api_client/models/history_event.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union, cast from attrs import define as _attrs_define from attrs import field as _attrs_field @@ -6,10 +6,9 @@ from ..types import UNSET, Unset if TYPE_CHECKING: - from ..models.history_event_parsed_output import HistoryEventParsedOutput + from ..models.any_object import AnyObject from ..models.history_event_prompt import HistoryEventPrompt from ..models.history_event_reasks_item import HistoryEventReasksItem - from ..models.history_event_validated_output import HistoryEventValidatedOutput T = TypeVar("T", bound="HistoryEvent") @@ -21,28 +20,34 @@ class HistoryEvent: Attributes: instructions (Union[Unset, str]): output (Union[Unset, str]): - parsed_output (Union[Unset, HistoryEventParsedOutput]): + parsed_output (Union['AnyObject', Unset, str]): prompt (Union[Unset, HistoryEventPrompt]): reasks (Union[Unset, List['HistoryEventReasksItem']]): - validated_output (Union[Unset, HistoryEventValidatedOutput]): + validated_output (Union['AnyObject', Unset, str]): """ instructions: Union[Unset, str] = UNSET output: Union[Unset, str] = UNSET - parsed_output: Union[Unset, "HistoryEventParsedOutput"] = UNSET + parsed_output: Union["AnyObject", Unset, str] = UNSET prompt: Union[Unset, "HistoryEventPrompt"] = UNSET reasks: Union[Unset, List["HistoryEventReasksItem"]] = UNSET - validated_output: Union[Unset, "HistoryEventValidatedOutput"] = UNSET + validated_output: Union["AnyObject", Unset, str] = UNSET additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: + from ..models.any_object import AnyObject + instructions = self.instructions output = self.output - parsed_output: Union[Unset, Dict[str, Any]] = UNSET - if not isinstance(self.parsed_output, Unset): + parsed_output: Union[Dict[str, Any], Unset, str] + if isinstance(self.parsed_output, Unset): + parsed_output = UNSET + elif isinstance(self.parsed_output, AnyObject): parsed_output = self.parsed_output.to_dict() + else: + parsed_output = self.parsed_output prompt: Union[Unset, Dict[str, Any]] = UNSET if not isinstance(self.prompt, Unset): @@ -55,9 +60,13 @@ def to_dict(self) -> Dict[str, Any]: reasks_item = reasks_item_data.to_dict() reasks.append(reasks_item) - validated_output: Union[Unset, Dict[str, Any]] = UNSET - if not isinstance(self.validated_output, Unset): + validated_output: Union[Dict[str, Any], Unset, str] + if isinstance(self.validated_output, Unset): + validated_output = UNSET + elif isinstance(self.validated_output, AnyObject): validated_output = self.validated_output.to_dict() + else: + validated_output = self.validated_output field_dict: Dict[str, Any] = {} field_dict.update(self.additional_properties) @@ -79,22 +88,29 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: - from ..models.history_event_parsed_output import HistoryEventParsedOutput + from ..models.any_object import AnyObject from ..models.history_event_prompt import HistoryEventPrompt from ..models.history_event_reasks_item import HistoryEventReasksItem - from ..models.history_event_validated_output import HistoryEventValidatedOutput d = src_dict.copy() instructions = d.pop("instructions", UNSET) output = d.pop("output", UNSET) - _parsed_output = d.pop("parsedOutput", UNSET) - parsed_output: Union[Unset, HistoryEventParsedOutput] - if isinstance(_parsed_output, Unset): - parsed_output = UNSET - else: - parsed_output = HistoryEventParsedOutput.from_dict(_parsed_output) + def _parse_parsed_output(data: object) -> Union["AnyObject", Unset, str]: + if isinstance(data, Unset): + return data + try: + if not isinstance(data, dict): + raise TypeError() + parsed_output_type_0 = AnyObject.from_dict(data) + + return parsed_output_type_0 + except: # noqa: E722 + pass + return cast(Union["AnyObject", Unset, str], data) + + parsed_output = _parse_parsed_output(d.pop("parsedOutput", UNSET)) _prompt = d.pop("prompt", UNSET) prompt: Union[Unset, HistoryEventPrompt] @@ -110,12 +126,20 @@ def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: reasks.append(reasks_item) - _validated_output = d.pop("validatedOutput", UNSET) - validated_output: Union[Unset, HistoryEventValidatedOutput] - if isinstance(_validated_output, Unset): - validated_output = UNSET - else: - validated_output = HistoryEventValidatedOutput.from_dict(_validated_output) + def _parse_validated_output(data: object) -> Union["AnyObject", Unset, str]: + if isinstance(data, Unset): + return data + try: + if not isinstance(data, dict): + raise TypeError() + validated_output_type_0 = AnyObject.from_dict(data) + + return validated_output_type_0 + except: # noqa: E722 + pass + return cast(Union["AnyObject", Unset, str], data) + + validated_output = _parse_validated_output(d.pop("validatedOutput", UNSET)) history_event = cls( instructions=instructions, diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py b/guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py deleted file mode 100644 index 8e009d8..0000000 --- a/guard-rails-api-client/guard_rails_api_client/models/history_event_parsed_output.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Any, Dict, List, Type, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="HistoryEventParsedOutput") - - -@_attrs_define -class HistoryEventParsedOutput: - """ """ - - additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> Dict[str, Any]: - field_dict: Dict[str, Any] = {} - field_dict.update(self.additional_properties) - - return field_dict - - @classmethod - def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: - d = src_dict.copy() - history_event_parsed_output = cls() - - history_event_parsed_output.additional_properties = d - return history_event_parsed_output - - @property - def additional_keys(self) -> List[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py b/guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py deleted file mode 100644 index 4e882a5..0000000 --- a/guard-rails-api-client/guard_rails_api_client/models/history_event_validated_output.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Any, Dict, List, Type, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="HistoryEventValidatedOutput") - - -@_attrs_define -class HistoryEventValidatedOutput: - """ """ - - additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> Dict[str, Any]: - field_dict: Dict[str, Any] = {} - field_dict.update(self.additional_properties) - - return field_dict - - @classmethod - def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: - d = src_dict.copy() - history_event_validated_output = cls() - - history_event_validated_output.additional_properties = d - return history_event_validated_output - - @property - def additional_keys(self) -> List[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/open-api-spec.yml b/open-api-spec.yml index 2e1f059..9b883c2 100644 --- a/open-api-spec.yml +++ b/open-api-spec.yml @@ -703,9 +703,9 @@ components: output: type: string parsedOutput: - type: object - properties: {} - additionalProperties: {} + oneOf: + - $ref: "#/components/schemas/AnyObject" + - type: string prompt: type: object properties: @@ -718,9 +718,9 @@ components: properties: {} additionalProperties: {} validatedOutput: - type: object - properties: {} - additionalProperties: {} + oneOf: + - $ref: "#/components/schemas/AnyObject" + - type: string additionalProperties: {} Reask: type: object