Skip to content

Add and document api_key and base_url to Guard.fetch_guard() #1245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/getting_started/guardrails_server.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,19 @@ A `guardrails` key is added to the response object, which includes the validatio
:::

### Advanced Client Usage
Advanced client usage is available in Python. You can point a Guard shim to the Guardrails server and use it as a normal Guard object.
Advanced client usage is available in Python. You can point a Guard shim to the Guardrails server and use it as a normal Guard object. Default values can be set in the environment variables `GUARDRAILS_BASE_URL` for the URL and `GUARDRAILS_API_KEY` for the API key.

```python
# Client code
from guardrails import Guard

name_guard = Guard.fetch_guard(name="gibberish_guard")
name_guard = Guard.fetch_guard(name="gibberish_guard", base_url="http://myserver.com", api_key="exampleKey")

validation_outcome = name_guard.validate("floofy doopy boopy")
```

#### Guardrails < v0.6.5
In older versions of Guardrails, you must set the URL and API key through the environment variables mentioned above.

#### Guardrails < v0.5.9
In older versions of Guardrails, you need to set the `use_server` var in settings to True.
Expand Down
23 changes: 16 additions & 7 deletions guardrails/guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ def __init__(
description: Optional[str] = None,
validators: Optional[List[ValidatorReference]] = None,
output_schema: Optional[Dict[str, Any]] = None,
base_url: Optional[str] = None,
api_key: Optional[str] = None,
):
"""Initialize the Guard with serialized validator references and an
output schema.
Expand Down Expand Up @@ -200,11 +202,16 @@ def __init__(
self._api_client: Optional[GuardrailsApiClient] = None
self._allow_metrics_collection: Optional[bool] = None
self._output_formatter: Optional[BaseFormatter] = None
self._api_key: Optional[str] = None
self._base_url: Optional[str] = None

# Gaurdrails As A Service Initialization
if settings.use_server:
api_key = os.environ.get("GUARDRAILS_API_KEY")
self._api_client = GuardrailsApiClient(api_key=api_key)
self._api_key = api_key
self._base_url = base_url
self._api_client = GuardrailsApiClient(
api_key=self._api_key, base_url=self._base_url
)
_loaded = False
if _try_to_load:
loaded_guard = self._api_client.fetch_guard(self.name)
Expand Down Expand Up @@ -1244,7 +1251,6 @@ def _call_server(
raise ValueError("Guard does not have an api client!")

def _save(self):
api_key = os.environ.get("GUARDRAILS_API_KEY")
if settings.use_server:
if self.name is None:
self.name = f"gr-{str(self.id)}"
Expand All @@ -1255,7 +1261,9 @@ def _save(self):
)
)
if not self._api_client:
self._api_client = GuardrailsApiClient(api_key=api_key)
self._api_client = GuardrailsApiClient(
api_key=self._api_key, base_url=self._base_url
)
self.upsert_guard()

def to_runnable(self) -> Runnable:
Expand Down Expand Up @@ -1332,17 +1340,18 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional["Guard"]:
@staticmethod
def fetch_guard(
name: Optional[str] = None,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
*args,
**kwargs,
):
if not name:
raise ValueError("Name must be specified to fetch a guard")

settings.use_server = True
api_key = os.environ.get("GUARDRAILS_API_KEY")
api_client = GuardrailsApiClient(api_key=api_key)
api_client = GuardrailsApiClient(api_key=api_key, base_url=base_url)
guard = api_client.fetch_guard(name)
if guard:
return Guard(name=name, *args, **kwargs)
return Guard(name=name, base_url=base_url, api_key=api_key, *args, **kwargs)

raise ValueError(f"Guard with name {name} not found")
Loading