Skip to content

Commit 8b1932a

Browse files
authored
Merge pull request #6 from guardrails-ai/try-generating-sdk-in-hook
Generate SDK on PR
2 parents 3f4fa9e + c3d8a6d commit 8b1932a

File tree

78 files changed

+8424
-16
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

78 files changed

+8424
-16
lines changed

.github/workflows/build-sdk.yml

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,68 @@
11
name: Build SDK
22

3-
on: [push, pull_request]
3+
on:
4+
pull_request:
5+
branches: [ main ]
6+
workflow_dispatch:
7+
8+
permissions:
9+
contents: write
410

511
jobs:
612
build:
713
runs-on: ubuntu-latest
814

915
steps:
1016
- name: Checkout code
11-
uses: actions/checkout@v2
12-
13-
- name: Set up Node.js
14-
uses: actions/setup-node@v2
17+
uses: actions/checkout@v4
1518
with:
16-
node-version: 14
19+
repository: ${{ github.event.pull_request.head.repo.full_name }}
20+
ref: ${{ github.event.pull_request.head.ref }}
1721

18-
- name: Execute merge.sh
22+
- name: Merge the OpenAPI Specs
1923
run: |
2024
chmod +x merge.sh # Make the script executable
2125
./merge.sh
2226
continue-on-error: false # Stop the workflow if merge.sh returns a non-zero exit code
2327

24-
- name: Execute build-sdk.sh
28+
- name: Build SDK from OpenApi Spec
2529
run: |
2630
chmod +x build-sdk.sh # Make the script executable
2731
./build-sdk.sh
2832
continue-on-error: false # Stop the workflow if build-sdk.sh returns a non-zero exit code
2933

30-
- name: Check for errors
31-
run: exit 0 # This step is here to explicitly check the exit code of the previous step
34+
- name: Swith to publish .gitignore
35+
run: |
36+
cp .gitignore .gitignore.local
37+
cp .gitignore.pub .gitignore
38+
continue-on-error: false
39+
40+
- name: Commit SDK updates
41+
uses: EndBug/add-and-commit@v9
42+
with:
43+
# The arguments for the `git add` command (see the paragraph below for more info)
44+
# Default: '.'
45+
add: 'open-api-spec.yml guard-rails-api-client'
46+
47+
# The name of the user that will be displayed as the author of the commit.
48+
# Default: depends on the default_author input
49+
author_name: ${{ github.event.pull_request.user.login }}
50+
51+
# The email of the user that will be displayed as the author of the commit.
52+
# Default: depends on the default_author input
53+
author_email: ${{ github.event.pull_request.user.email }}
54+
55+
# The message for the commit.
56+
# Default: 'Commit from GitHub Actions (name of the workflow)'
57+
message: 'update generated sdk'
58+
59+
# The way the action should handle pathspec errors from the add and remove commands. Three options are available:
60+
# - ignore -> errors will be logged but the step won't fail
61+
# - exitImmediately -> the action will stop right away, and the step will fail
62+
# - exitAtEnd -> the action will go on, every pathspec error will be logged at the end, the step will fail.
63+
# Default: ignore
64+
pathspec_error_handling: exitAtEnd
65+
66+
# 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)
67+
# Default: true
68+
push: true

.gitignore.pub

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.venv
2+
.ruff_cache

guard-rails-api-client/.gitignore

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
__pycache__/
2+
build/
3+
dist/
4+
*.egg-info/
5+
.pytest_cache/
6+
7+
# pyenv
8+
.python-version
9+
10+
# Environments
11+
.env
12+
.venv
13+
14+
# mypy
15+
.mypy_cache/
16+
.dmypy.json
17+
dmypy.json
18+
19+
# JetBrains
20+
.idea/
21+
22+
/coverage.xml
23+
/.coverage

guard-rails-api-client/README.md

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# guard-rails-api-client
2+
A client library for accessing GuardRails API
3+
4+
## Usage
5+
First, create a client:
6+
7+
```python
8+
from guard_rails_api_client import Client
9+
10+
client = Client(base_url="https://api.example.com")
11+
```
12+
13+
If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead:
14+
15+
```python
16+
from guard_rails_api_client import AuthenticatedClient
17+
18+
client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken")
19+
```
20+
21+
Now call your endpoint and use your models:
22+
23+
```python
24+
from guard_rails_api_client.models import MyDataModel
25+
from guard_rails_api_client.api.my_tag import get_my_data_model
26+
from guard_rails_api_client.types import Response
27+
28+
with client as client:
29+
my_data: MyDataModel = get_my_data_model.sync(client=client)
30+
# or if you need more info (e.g. status_code)
31+
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
32+
```
33+
34+
Or do the same thing with an async version:
35+
36+
```python
37+
from guard_rails_api_client.models import MyDataModel
38+
from guard_rails_api_client.api.my_tag import get_my_data_model
39+
from guard_rails_api_client.types import Response
40+
41+
async with client as client:
42+
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
43+
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
44+
```
45+
46+
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.
47+
48+
```python
49+
client = AuthenticatedClient(
50+
base_url="https://internal_api.example.com",
51+
token="SuperSecretToken",
52+
verify_ssl="/path/to/certificate_bundle.pem",
53+
)
54+
```
55+
56+
You can also disable certificate validation altogether, but beware that **this is a security risk**.
57+
58+
```python
59+
client = AuthenticatedClient(
60+
base_url="https://internal_api.example.com",
61+
token="SuperSecretToken",
62+
verify_ssl=False
63+
)
64+
```
65+
66+
Things to know:
67+
1. Every path/method combo becomes a Python module with four functions:
68+
1. `sync`: Blocking request that returns parsed data (if successful) or `None`
69+
1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful.
70+
1. `asyncio`: Like `sync` but async instead of blocking
71+
1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking
72+
73+
1. All path/query params, and bodies become method arguments.
74+
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)
75+
1. Any endpoint which did not have a tag will be in `guard_rails_api_client.api.default`
76+
77+
## Advanced customizations
78+
79+
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):
80+
81+
```python
82+
from guard_rails_api_client import Client
83+
84+
def log_request(request):
85+
print(f"Request event hook: {request.method} {request.url} - Waiting for response")
86+
87+
def log_response(response):
88+
request = response.request
89+
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
90+
91+
client = Client(
92+
base_url="https://api.example.com",
93+
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
94+
)
95+
96+
# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
97+
```
98+
99+
You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):
100+
101+
```python
102+
import httpx
103+
from guard_rails_api_client import Client
104+
105+
client = Client(
106+
base_url="https://api.example.com",
107+
)
108+
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
109+
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
110+
```
111+
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
""" A client library for accessing GuardRails API """
2+
from .client import AuthenticatedClient, Client
3+
4+
__all__ = (
5+
"AuthenticatedClient",
6+
"Client",
7+
)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
""" Contains methods for accessing the API """

guard-rails-api-client/guard_rails_api_client/api/default/__init__.py

Whitespace-only changes.
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
from http import HTTPStatus
2+
from typing import Any, Dict, List, Optional, Union
3+
4+
import httpx
5+
6+
from ... import errors
7+
from ...client import AuthenticatedClient, Client
8+
from ...models.ingestion import Ingestion
9+
from ...types import Response
10+
11+
12+
def _get_kwargs(
13+
document_id: str,
14+
) -> Dict[str, Any]:
15+
_kwargs: Dict[str, Any] = {
16+
"method": "delete",
17+
"url": f"/embeddings/{document_id}",
18+
}
19+
20+
return _kwargs
21+
22+
23+
def _parse_response(
24+
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
25+
) -> Optional[List["Ingestion"]]:
26+
if response.status_code == HTTPStatus.OK:
27+
response_200 = []
28+
_response_200 = response.json()
29+
for response_200_item_data in _response_200:
30+
response_200_item = Ingestion.from_dict(response_200_item_data)
31+
32+
response_200.append(response_200_item)
33+
34+
return response_200
35+
if client.raise_on_unexpected_status:
36+
raise errors.UnexpectedStatus(response.status_code, response.content)
37+
else:
38+
return None
39+
40+
41+
def _build_response(
42+
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
43+
) -> Response[List["Ingestion"]]:
44+
return Response(
45+
status_code=HTTPStatus(response.status_code),
46+
content=response.content,
47+
headers=response.headers,
48+
parsed=_parse_response(client=client, response=response),
49+
)
50+
51+
52+
def sync_detailed(
53+
document_id: str,
54+
*,
55+
client: Union[AuthenticatedClient, Client],
56+
) -> Response[List["Ingestion"]]:
57+
"""Deletes embeddings for a given documentId
58+
59+
Args:
60+
document_id (str):
61+
62+
Raises:
63+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
64+
httpx.TimeoutException: If the request takes longer than Client.timeout.
65+
66+
Returns:
67+
Response[List['Ingestion']]
68+
"""
69+
70+
kwargs = _get_kwargs(
71+
document_id=document_id,
72+
)
73+
74+
response = client.get_httpx_client().request(
75+
**kwargs,
76+
)
77+
78+
return _build_response(client=client, response=response)
79+
80+
81+
def sync(
82+
document_id: str,
83+
*,
84+
client: Union[AuthenticatedClient, Client],
85+
) -> Optional[List["Ingestion"]]:
86+
"""Deletes embeddings for a given documentId
87+
88+
Args:
89+
document_id (str):
90+
91+
Raises:
92+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
93+
httpx.TimeoutException: If the request takes longer than Client.timeout.
94+
95+
Returns:
96+
List['Ingestion']
97+
"""
98+
99+
return sync_detailed(
100+
document_id=document_id,
101+
client=client,
102+
).parsed
103+
104+
105+
async def asyncio_detailed(
106+
document_id: str,
107+
*,
108+
client: Union[AuthenticatedClient, Client],
109+
) -> Response[List["Ingestion"]]:
110+
"""Deletes embeddings for a given documentId
111+
112+
Args:
113+
document_id (str):
114+
115+
Raises:
116+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
117+
httpx.TimeoutException: If the request takes longer than Client.timeout.
118+
119+
Returns:
120+
Response[List['Ingestion']]
121+
"""
122+
123+
kwargs = _get_kwargs(
124+
document_id=document_id,
125+
)
126+
127+
response = await client.get_async_httpx_client().request(**kwargs)
128+
129+
return _build_response(client=client, response=response)
130+
131+
132+
async def asyncio(
133+
document_id: str,
134+
*,
135+
client: Union[AuthenticatedClient, Client],
136+
) -> Optional[List["Ingestion"]]:
137+
"""Deletes embeddings for a given documentId
138+
139+
Args:
140+
document_id (str):
141+
142+
Raises:
143+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
144+
httpx.TimeoutException: If the request takes longer than Client.timeout.
145+
146+
Returns:
147+
List['Ingestion']
148+
"""
149+
150+
return (
151+
await asyncio_detailed(
152+
document_id=document_id,
153+
client=client,
154+
)
155+
).parsed

0 commit comments

Comments
 (0)