-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from guardrails-ai/try-generating-sdk-in-hook
Generate SDK on PR
- Loading branch information
Showing
78 changed files
with
8,424 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,68 @@ | ||
name: Build SDK | ||
|
||
on: [push, pull_request] | ||
on: | ||
pull_request: | ||
branches: [ main ] | ||
workflow_dispatch: | ||
|
||
permissions: | ||
contents: write | ||
|
||
jobs: | ||
build: | ||
runs-on: ubuntu-latest | ||
|
||
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: 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.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 | ||
author_email: ${{ github.event.pull_request.user.email }} | ||
|
||
# The message for the commit. | ||
# Default: 'Commit from GitHub Actions (name of the workflow)' | ||
message: 'update generated sdk' | ||
|
||
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
.venv | ||
.ruff_cache |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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")) | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
""" A client library for accessing GuardRails API """ | ||
from .client import AuthenticatedClient, Client | ||
|
||
__all__ = ( | ||
"AuthenticatedClient", | ||
"Client", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
""" Contains methods for accessing the API """ |
Empty file.
155 changes: 155 additions & 0 deletions
155
guard-rails-api-client/guard_rails_api_client/api/default/delete_ingested_document.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
Oops, something went wrong.