safe-genai
A Python library that wraps Google Gemini with a mandatory generate → format → validate pipeline, so every response is structured and semantically checked before you receive it.
How it works
Every call to SafeAgent.run() executes three steps in sequence:
- Generate — calls Gemini (with Google Search grounding) using your system prompt
- Format — coerces the raw text into your Pydantic schema via a second LLM call
- Validate — verifies the output fulfills the original prompt requirements, rejecting evasive non-answers (skippable via
skip_validation=True)
If validation fails, the pipeline retries from the top (configurable via max_retries). On final failure it raises SafeGenAIValidationError.
Installation
pip install safe-genai
Requires a Google Gemini API key or Vertex AI project:
export GEMINI_API_KEY="your-key-here"
Quickstart
from pydantic import BaseModel
from safe_genai import SafeAgent
class LatestRelease(BaseModel):
version: str
release_date: str
notable_changes: list[str]
agent = SafeAgent(
output_schema=LatestRelease,
system_prompt=(
"You are a software research assistant. "
"Use Google Search to find the most recent release information. "
"Always return the latest published version, never guess."
),
)
result = agent.run("What is the latest stable release of Python?")
print(result.output.version)
print(result.output.release_date)
Async usage
result = await agent.run_async("What is 2 + 2?")
Configuration
from safe_genai import SafeAgent, AgentConfig
agent = SafeAgent(
output_schema=Answer,
system_prompt="You are a helpful assistant.",
additional_formatter_instructions="Always express numbers as digits, not words.",
additional_validator_instructions="Reject answers with confidence below 0.8.",
max_retries=2,
config=AgentConfig(
generator_model="gemini-3.1-pro-preview",
formatter_model="gemini-3-flash-preview",
validator_model="gemini-3-flash-preview",
api_key="your-key", # or set GEMINI_API_KEY env var
),
)
Vertex AI (gcloud ADC)
If you're already authenticated with gcloud auth application-default login, you can use Vertex AI instead of an API key:
from safe_genai import SafeAgent, AgentConfig
agent = SafeAgent(
output_schema=Answer,
system_prompt="You are a helpful assistant.",
config=AgentConfig(
vertexai=True,
vertex_project="my-gcp-project", # or set GOOGLE_CLOUD_PROJECT env var
vertex_location="us-central1", # default
),
)
No GEMINI_API_KEY is needed — the client uses your ambient gcloud credentials.
Error handling
from safe_genai import SafeGenAIValidationError, SafeGenAIFormatterError
try:
result = agent.run("some prompt")
except SafeGenAIValidationError as e:
print(f"Validation failed after {e.attempts} attempt(s): {e.feedback}")
print(e.output) # last Pydantic model produced
print(e.raw_response) # raw text from the generator
except SafeGenAIFormatterError as e:
print(f"Could not coerce output into {e.schema_name}: {e.cause}")
Token usage
Every result includes a breakdown of token usage by pipeline step, accumulated across all retry attempts:
result = agent.run("What is the latest stable release of Python?")
print(result.usage.generator) # Usage(input_tokens=..., output_tokens=...)
print(result.usage.formatter) # Usage(input_tokens=..., output_tokens=...)
print(result.usage.validator) # Usage(input_tokens=..., output_tokens=...)
print(result.usage.total) # Usage(input_tokens=..., output_tokens=...) ← sum of all three
Usage is a plain dataclass with two fields: input_tokens and output_tokens.
Development
uv sync --extra dev
uv run pytest
uv build
License
MIT — see LICENSE.
Metadata
Release files for safe-genai 0.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| safe_genai-0.4.1.tar.gz | 63.7 kB | With provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| safe_genai-0.4.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 77.2 kB
Release files / safe_genai-0.4.1.tar.gz
| Download URL | safe_genai-0.4.1.tar.gz |
|---|---|
| Size | 63.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
604d36418a3b5bc72fa2082ff4fef5d13fd3af9370c53dd841e41c533d2abb96
|
|
BLAKE2b-256 checksum How to use checksums |
ca0731b3bccc02c991dc364aa2238d0a8ab4b1a6db26486d8abf1ce0116fd61f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 22, 2026.
Transparency logRelease files / safe_genai-0.4.1-py3-none-any.whl
| Download URL | safe_genai-0.4.1-py3-none-any.whl |
|---|---|
| Size | 13.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7dd9ec715a779da019f6c2966f54441640059b046f71820729898d35863c1e7f
|
|
BLAKE2b-256 checksum How to use checksums |
97b186e13a34c5b8d91517d439c477f0da4d309f41e503765141e1c9131ce3a8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 22, 2026.
Transparency logSecurity for safe-genai 0.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 2 files in this release have been uploaded with provenance metadata.
Attestation for safe_genai-0.4.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 22, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.