Examples
Complete Safeguard AI SDK examples: a Node script, a Python script, a Go program and a CI job that runs one with the key from a secret.
Examples
Each script reads the question from its arguments, asks Safeguard AI and prints the answer. They exit with code 2 when no question is given and code 1 on a Safeguard error, so a CI job fails clearly. Set SAFEGUARD_API_KEY first.
A Node script
npm install @safeguard-sh/sdk
node ask-cli.mjs "In one sentence, what is an SBOM?"// ask-cli.mjs: print Safeguard AI's answer to the question given as arguments.
// Usage: SAFEGUARD_API_KEY=sg_sk_... node ask-cli.mjs "In one sentence, what is an SBOM?"
import { Safeguard, SafeguardError } from "@safeguard-sh/sdk";
const prompt = process.argv.slice(2).join(" ").trim();
if (!prompt) {
console.error("usage: node ask-cli.mjs <question>");
process.exit(2);
}
try {
const client = new Safeguard();
const result = await client.query(prompt);
console.log(result.answer);
} catch (e) {
if (e instanceof SafeguardError) {
console.error(`Safeguard error ${e.status} ${e.code}: ${e.message}`);
process.exit(1);
}
throw e;
}A Python script
pip install safeguard-sdk --index-url https://registry.safeguard.sh/pypi/simple/
python ask_cli.py "In one sentence, what is an SBOM?""""ask_cli.py: print Safeguard AI's answer to the question given as arguments.
Usage: SAFEGUARD_API_KEY=sg_sk_... python ask_cli.py "In one sentence, what is an SBOM?"
"""
import sys
from safeguard_sdk import Safeguard, SafeguardError
prompt = " ".join(sys.argv[1:]).strip()
if not prompt:
sys.exit("usage: python ask_cli.py <question>")
try:
with Safeguard() as client:
print(client.query(prompt).answer)
except SafeguardError as e:
sys.exit(f"Safeguard error {e.status} {e.code}: {e.message}")An async Python script
import asyncio
from safeguard_sdk import AsyncSafeguard, Final
async def main() -> None:
async with AsyncSafeguard() as client: # reads SAFEGUARD_API_KEY
result = await client.query("In one sentence, what is an SBOM?")
print(result.answer)
async with client.stream("In one sentence, what is a CVE?") as events:
async for event in events:
if isinstance(event, Final):
print(event.answer)
asyncio.run(main())A Go program
go get safeguard.sh/sdk@v0.1.0
go run . "In one sentence, what is an SBOM?"// askcli prints Safeguard AI's answer to the question given as arguments.
//
// Usage: SAFEGUARD_API_KEY=sg_sk_... go run . "In one sentence, what is an SBOM?"
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
safeguard "safeguard.sh/sdk"
)
func main() {
prompt := strings.TrimSpace(strings.Join(os.Args[1:], " "))
if prompt == "" {
fmt.Fprintln(os.Stderr, "usage: askcli <question>")
os.Exit(2)
}
client, err := safeguard.NewClient()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
res, err := client.Query(ctx, prompt, nil)
var apiErr *safeguard.APIError
if errors.As(err, &apiErr) {
fmt.Fprintf(os.Stderr, "Safeguard error %d %s: %s\n", apiErr.Status, apiErr.Code, apiErr.Message)
os.Exit(1)
} else if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(res.Answer)
}Example output of any of the three (shortened):
An SBOM (Software Bill of Materials) is a machine-readable inventory of all the components ...A CI job
Store the key in your CI system's secret store as SAFEGUARD_API_KEY and run a script with it. Never write the key into the pipeline file.
GitHub Actions, running the Node script:
name: ask-safeguard
on: workflow_dispatch
jobs:
ask:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm install @safeguard-sh/sdk
- run: node ask-cli.mjs "In one sentence, what is an SBOM?"
env:
SAFEGUARD_API_KEY: ${{ secrets.SAFEGUARD_API_KEY }}Bitbucket Pipelines, running the Python script:
pipelines:
custom:
ask-safeguard:
- step:
image: python:3.12-slim
script:
- pip install safeguard-sdk --index-url https://registry.safeguard.sh/pypi/simple/
- python ask_cli.py "In one sentence, what is an SBOM?"In Bitbucket, add SAFEGUARD_API_KEY as a secured repository or deployment variable.
These two pipeline files were not run in a real CI system. The script bodies they call, ask-cli.mjs and ask_cli.py, were run against the live API with the key supplied through the environment, exactly as the secret is supplied in CI.