{"_id":"@coralogix/cx-guardrails","_rev":"3-1729c115169ad7455228e6cf09c9b6ad","name":"@coralogix/cx-guardrails","dist-tags":{"latest":"1.0.1"},"versions":{"1.0.0":{"name":"@coralogix/cx-guardrails","version":"1.0.0","keywords":["coralogix","guardrails","llm","ai","opentelemetry","tracing","pii","prompt-injection","toxicity"],"author":{"name":"Coralogix Ltd.","email":"info@coralogix.com"},"license":"Apache-2.0","_id":"@coralogix/cx-guardrails@1.0.0","maintainers":[{"name":"coralogixnpm","email":"npm@coralogix.com"},{"name":"cx-shaharkazaz","email":"shahar.kazaz@coralogix.com"}],"homepage":"https://github.com/coralogix/guardrails-ts#readme","bugs":{"url":"https://github.com/coralogix/guardrails-ts/issues"},"dist":{"shasum":"c96072e102d9efae26bb6dd376f426d4b2df2ba7","tarball":"https://registry.npmjs.org/@coralogix/cx-guardrails/-/cx-guardrails-1.0.0.tgz","fileCount":9,"integrity":"sha512-RyZKd5sUFocKXqfGQnA9nfwm3jAJ2nsB42+43xkFUdQvvnx2s2YtBesMVdRuMpTOHqr15MiUevQybbJeC/H0PA==","signatures":[{"sig":"MEYCIQDXgDDsqG7vE/k83FpWvPiz8/uTAQtDWdGltLgQKMkHPgIhAPPTWhYe9fFFhFbVi5NSES5P0aejZtrMQ1savVKS8kty","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":180452},"main":"./dist/index.cjs","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"import":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"require":{"types":"./dist/index.d.cts","default":"./dist/index.cjs"}}},"gitHead":"df15cfee753b17488087522501b6855cb5e811df","scripts":{"lint":"eslint src/ tests/","test":"vitest run","build":"tsup","format":"prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"","typecheck":"tsc --noEmit","test:watch":"vitest","prepublishOnly":"npm run build"},"_npmUser":{"name":"coralogixnpm","email":"npm@coralogix.com"},"repository":{"url":"git+https://github.com/coralogix/guardrails-ts.git","type":"git"},"_npmVersion":"11.6.2","description":"TypeScript SDK for protecting your LLM applications with Coralogix Guardrails content evaluation.","directories":{},"_nodeVersion":"24.13.0","dependencies":{"zod":"^4.4.3","@grpc/grpc-js":"^1.14.4","@opentelemetry/resources":"^2.7.1","@opentelemetry/sdk-trace-base":"^2.7.1","@opentelemetry/context-async-hooks":"^2.7.1","@opentelemetry/semantic-conventions":"^1.28.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.218.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.22.3","tsup":"^8.3.0","eslint":"^9.0.0","vitest":"^3.0.0","prettier":"^3.4.0","typescript":"^5.7.0","@opentelemetry/api":"^1.9.0","@typescript-eslint/parser":"^8.0.0","@typescript-eslint/eslint-plugin":"^8.0.0"},"peerDependencies":{"@opentelemetry/api":"^1.4.0"},"_npmOperationalInternal":{"tmp":"tmp/cx-guardrails_1.0.0_1781772879399_0.8632309251854995","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@coralogix/cx-guardrails","version":"1.0.1","keywords":["coralogix","guardrails","llm","ai","opentelemetry","tracing","pii","prompt-injection","toxicity"],"author":{"name":"Coralogix Ltd.","email":"info@coralogix.com"},"license":"Apache-2.0","_id":"@coralogix/cx-guardrails@1.0.1","maintainers":[{"name":"coralogixnpm","email":"npm@coralogix.com"},{"name":"cx-shaharkazaz","email":"shahar.kazaz@coralogix.com"}],"homepage":"https://github.com/coralogix/guardrails-ts#readme","bugs":{"url":"https://github.com/coralogix/guardrails-ts/issues"},"dist":{"shasum":"b67a218ce4adefbbf86b13b8b3d94acf5e17246a","tarball":"https://registry.npmjs.org/@coralogix/cx-guardrails/-/cx-guardrails-1.0.1.tgz","fileCount":9,"integrity":"sha512-hltDZgDlr9R3LgzkpjNAF6/com0GhVSo9o68EfNKtBXvnzVEKS3QtWU5UAtGDCr8FMx4Jk6KIhRS6BEbHXCSDA==","signatures":[{"sig":"MEYCIQDb2i69IOkgMTkPNlhVTPSMDgjJzDb8vNW/5e3cun3TnAIhAJyLl0q3wnNlcS2ucjggovVBqJ4X1krpnfYNSNRKFhCm","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":181486},"main":"./dist/index.cjs","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"import":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"require":{"types":"./dist/index.d.cts","default":"./dist/index.cjs"}}},"gitHead":"81e5e8c65057341335f714a2d0dd023fd3c22b72","scripts":{"lint":"eslint src/ tests/","test":"vitest run","build":"tsup","format":"prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"","typecheck":"tsc --noEmit","test:watch":"vitest","prepublishOnly":"npm run build"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:1cf8a523-41fc-46b8-b18d-d8ba252667de"}},"repository":{"url":"git+https://github.com/coralogix/guardrails-ts.git","type":"git"},"_npmVersion":"11.13.0","description":"TypeScript SDK for protecting your LLM applications with Coralogix Guardrails content evaluation.","directories":{},"_nodeVersion":"24.16.0","dependencies":{"zod":"^4.4.3","@grpc/grpc-js":"^1.14.4","@opentelemetry/resources":"^2.7.1","@opentelemetry/sdk-trace-base":"^2.7.1","@opentelemetry/context-async-hooks":"^2.7.1","@opentelemetry/semantic-conventions":"^1.28.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.218.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.22.3","tsup":"^8.3.0","eslint":"^9.0.0","vitest":"^3.0.0","prettier":"^3.4.0","typescript":"^5.7.0","@opentelemetry/api":"^1.9.0","@typescript-eslint/parser":"^8.0.0","@typescript-eslint/eslint-plugin":"^8.0.0"},"peerDependencies":{"@opentelemetry/api":"^1.4.0"},"_npmOperationalInternal":{"tmp":"tmp/cx-guardrails_1.0.1_1781782646677_0.6912424053136754","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2026-06-18T08:54:39.188Z","modified":"2026-06-29T13:51:03.570Z","1.0.0":"2026-06-18T08:54:39.540Z","1.0.1":"2026-06-18T11:37:26.837Z"},"bugs":{"url":"https://github.com/coralogix/guardrails-ts/issues"},"author":{"name":"Coralogix Ltd.","email":"info@coralogix.com"},"license":"Apache-2.0","homepage":"https://github.com/coralogix/guardrails-ts#readme","keywords":["coralogix","guardrails","llm","ai","opentelemetry","tracing","pii","prompt-injection","toxicity"],"repository":{"url":"git+https://github.com/coralogix/guardrails-ts.git","type":"git"},"description":"TypeScript SDK for protecting your LLM applications with Coralogix Guardrails content evaluation.","maintainers":[{"email":"npm@coralogix.com","name":"coralogixnpm"},{"email":"ashley.hunter@coralogix.com","name":"ashley-hunter-cx"},{"email":"shahar.kazaz@coralogix.com","name":"cx-shaharkazaz"}],"readme":"# Coralogix Guardrails\n\nTypeScript SDK for protecting your LLM applications with content evaluation.\n\nCoralogix Guardrails lets you evaluate prompts and LLM responses against configurable checks — PII, prompt injection, toxicity, and your own custom criteria — before they reach an LLM or your users. When a guardrail is triggered the SDK throws (or returns the results, if you prefer), and every check is emitted as an OpenTelemetry span so you can observe and audit guardrail activity in Coralogix. Use it to add a safety and compliance layer around any LLM-powered feature.\n\n## Installation\n\n```bash\nnpm install @coralogix/cx-guardrails @opentelemetry/api\n```\n\n> **Note:** `@opentelemetry/api` is a required peer dependency (the SDK creates OpenTelemetry spans), so install it alongside the SDK.\n\n## Getting Started\n\n| Method | Use Case | Input |\n|--------|----------|-------|\n| `guardPrompt()` | Guard user input before LLM call | `prompt` |\n| `guardResponse()` | Guard LLM output after generation | `response`, `prompt` (optional) |\n| `guard()` | Full control over message history | List of messages |\n\n## Available Guardrails\n\n| Guardrail | Description | Usage |\n|-----------|-------------|-------|\n| **PII Detection** | Detects personally identifiable information | `pii()` |\n| **Prompt Injection** | Detects attempts to manipulate LLM behavior | `promptInjection()` |\n| **Toxicity** | Detects toxic, harmful, or offensive content | `toxicity()` |\n| **Custom** | Define your own evaluation criteria | `custom({ name, instructions, ... })` |\n\n```typescript\nimport {\n  Guardrails,\n  pii,\n  promptInjection,\n  GuardrailsTriggered,\n  setupExportToCoralogix,\n} from \"@coralogix/cx-guardrails\";\n\nconst tracing = setupExportToCoralogix({ serviceName: \"my-service\" });\n\nconst guardrails = new Guardrails();\n\nasync function main() {\n  await guardrails.guardedSession(async () => {\n    try {\n      await guardrails.guardPrompt([pii(), promptInjection()], \"User input here\");\n\n      const response = \"...\";\n\n      await guardrails.guardResponse([pii(), promptInjection()], response);\n    } catch (e) {\n      if (e instanceof GuardrailsTriggered) {\n        for (const v of e.triggered) {\n          console.log(`Blocked: ${v.guardrailType}`);\n        }\n      }\n    }\n  });\n\n  await tracing.shutdown();\n}\n\nmain();\n```\n\n### PII Detection\n\n```typescript\nimport { pii, PIICategory } from \"@coralogix/cx-guardrails\";\n\npii(); // All categories, default threshold 0.7\npii({ categories: [PIICategory.EMAIL_ADDRESS, PIICategory.PHONE_NUMBER], threshold: 0.8 });\n```\n\n**Categories:** `email_address`, `phone_number`, `credit_card`, `iban_code`, `us_ssn`\n\n### Prompt Injection Detection\n\n```typescript\nimport { promptInjection } from \"@coralogix/cx-guardrails\";\n\npromptInjection(); // Default threshold 0.7\npromptInjection({ threshold: 0.8 });\n```\n\n### Toxicity Detection\n\n```typescript\nimport { toxicity } from \"@coralogix/cx-guardrails\";\n\ntoxicity(); // Default threshold 0.7\ntoxicity({ threshold: 0.8 });\n```\n\n### Custom Guardrails\n\nDefine your own evaluation criteria to detect specific content patterns:\n\n```typescript\nimport { custom } from \"@coralogix/cx-guardrails\";\n\ncustom({\n  name: \"financial_advice_detector\",\n  instructions:\n    \"Analyze the {response} and the {prompt} for any financial advice or investment recommendations.\",\n  violates: \"Response contains specific financial advice or investment recommendations.\",\n  safe: \"Response provides general information without specific investment advice.\",\n  threshold: 0.7,\n  examples: [\n    {\n      conversation: \"User: Should I buy Tesla stock?\\nAssistant: Yes, buy it now!\",\n      score: 1, // 1 = violates\n    },\n    {\n      conversation:\n        \"User: What is a stock?\\nAssistant: A stock represents ownership in a company.\",\n      score: 0, // 0 = safe\n    },\n  ],\n});\n```\n\n**Required fields:**\n- `name`: The guardrail's name\n- `instructions`: Evaluation instructions (must contain `{prompt}`, `{response}`, or `{history}`)\n- `violates`: Description of what constitutes a violation\n- `safe`: Description of what constitutes safe content\n\n**Optional fields:**\n- `threshold`: Detection threshold (default: 0.7)\n- `examples`: List of example conversations with expected scores\n- `shouldIncludeSystemPrompt`: Include system prompt in evaluation (default: false)\n- `category`: `\"security\"` or `\"quality\"` (default: `\"quality\"`)\n\n#### Magic Words\n\nUse placeholder tags in your `instructions` to reference conversation content. At least one magic word is required.\n\n| Magic Word | Description | Replaced With | Evaluation Target |\n|------------|-------------|---------------|-------------------|\n| `{prompt}` | User's input | The last user message | Prompt |\n| `{response}` | Assistant's output | The last assistant response | Response |\n| `{history}` | Full conversation | All messages in the conversation | Response |\n\n## Using `guard()` for Full Control\n\n```typescript\nimport { GuardrailsTarget, pii } from \"@coralogix/cx-guardrails\";\n\nconst messages = [\n  { role: \"user\", content: \"Hello\" },\n  { role: \"assistant\", content: \"Hi there!\" },\n];\n\nawait guardrails.guard([pii()], messages, GuardrailsTarget.RESPONSE);\n```\n\n### With Tool Calls\n\n```typescript\nconst messages = [\n  { role: \"user\", content: \"What's the weather in Paris?\" },\n  {\n    role: \"assistant\",\n    content: JSON.stringify({\n      tool_calls: [\n        {\n          id: \"call_123\",\n          type: \"function\",\n          function: { name: \"get_weather\", arguments: '{\"location\": \"Paris\"}' },\n        },\n      ],\n    }),\n  },\n  { role: \"tool\", content: \"The weather in Paris is 22C and sunny.\" },\n  { role: \"assistant\", content: \"The weather in Paris is 22C and sunny.\" },\n];\n\nawait guardrails.guard([pii()], messages, GuardrailsTarget.RESPONSE);\n```\n\n## Configuration\n\n### Environment Variables\n\n```bash\nexport CX_GUARDRAILS_TOKEN=\"your-guardrails-api-key\"\nexport CX_GUARDRAILS_ENDPOINT=\"https://your-domain.coralogix.com/api/v1/guardrails/guard\"\nexport CX_TOKEN=\"your-coralogix-api-key\"\nexport CX_ENDPOINT=\"https://your-domain.coralogix.com\"\nexport CX_APPLICATION_NAME=\"my-app\"      # Optional, default \"Unknown\"\nexport CX_SUBSYSTEM_NAME=\"my-subsystem\"  # Optional, default \"Unknown\"\n```\n\n### Client Configuration\n\n```typescript\nconst guardrails = new Guardrails({\n  apiKey: \"your-api-key\",\n  cxGuardrailsEndpoint: \"https://your-domain.coralogix.com/api/v1/guardrails/guard\",\n  timeout: 2,      // Timeout in seconds (default: 10)\n  maxRetries: 3,   // Retry attempts on timeout/connection errors (default: 3)\n});\n```\n\n### Testing Connectivity\n\nUse `testConnection()` to verify the SDK can reach the Guardrails API — useful on startup or in a health check. It returns the API response on success and throws on failure:\n\n```typescript\nconst guardrails = new Guardrails();\n\ntry {\n  await guardrails.testConnection();\n  console.log(\"Guardrails API is reachable\");\n} catch (e) {\n  console.error(\"Guardrails API is unreachable\", e);\n}\n```\n\n### Suppress Exceptions\n\nTo return results instead of throwing `GuardrailsTriggered`:\n\n```bash\nexport DISABLE_GUARDRAILS_TRIGGERED_EXCEPTION=true\n```\n\n## Error Handling\n\n```typescript\nimport {\n  GuardrailsTriggered,\n  GuardrailsConfigError,\n  GuardrailsAPITimeoutError,\n  GuardrailsAPIConnectionError,\n  GuardrailsAPIResponseError,\n} from \"@coralogix/cx-guardrails\";\n\ntry {\n  await guardrails.guardPrompt([pii()], \"test\");\n} catch (e) {\n  if (e instanceof GuardrailsTriggered) {\n    for (const v of e.triggered) {\n      console.log(`${v.guardrailType}`);\n    }\n  } else if (e instanceof GuardrailsConfigError) {\n    // Invalid configuration or input (e.g. missing endpoint, invalid role)\n  } else if (e instanceof GuardrailsAPITimeoutError) {\n    // Request timed out (retried up to maxRetries before throwing)\n  } else if (e instanceof GuardrailsAPIConnectionError) {\n    // Network error (retried up to maxRetries before throwing)\n  } else if (e instanceof GuardrailsAPIResponseError) {\n    console.log(`HTTP ${e.statusCode}`);\n  }\n}\n```\n\n## OpenTelemetry Tracing\n\nThe SDK automatically creates OpenTelemetry spans for each guardrail check. Call `setupExportToCoralogix()` to export spans to Coralogix:\n\n```typescript\nconst tracing = setupExportToCoralogix({\n  serviceName: \"my-llm-app\",\n  applicationName: \"my-app\",       // Falls back to CX_APPLICATION_NAME\n  subsystemName: \"my-subsystem\",   // Falls back to CX_SUBSYSTEM_NAME\n  coralogixToken: \"...\",           // Falls back to CX_TOKEN\n  coralogixEndpoint: \"...\",        // Falls back to CX_ENDPOINT\n  useBatchProcessor: true,         // Use BatchSpanProcessor (default: true)\n});\n\n// ... run guardrail checks ...\n\n// Flush spans before process exit\nawait tracing.shutdown();\n```\n\n| Span Name | Kind | When |\n|-----------|------|------|\n| `cx.guardrails.session` | Internal | `guardedSession()` |\n| `guardrails.prompt` | Client | `guardPrompt()` / `guard(..., PROMPT)` |\n| `guardrails.response` | Client | `guardResponse()` / `guard(..., RESPONSE)` |\n| `cx.guardrails.test` | Client | `testConnection()` |\n\n### Span Attributes\n\n- `cx.application.name` - Application name\n- `cx.subsystem.name` - Subsystem name\n- `guardrails.triggered` - Whether any guardrail was triggered\n- `guardrails.prompt.{n}` - Evaluated prompt text\n- `guardrails.response.{n}` - Evaluated response text\n- `gen_ai.{target}.guardrails.{type}.score` - Guardrail score\n- `gen_ai.{target}.guardrails.{type}.threshold` - Guardrail threshold\n- `gen_ai.{target}.guardrails.{type}.triggered` - Whether score exceeded threshold\n\n## License\n\nApache 2.0 - See [LICENSE](./LICENSE.md) for details.\n","readmeFilename":"README.md"}