{"id":47788491,"url":"https://github.com/acebot712/promptguard-python","last_synced_at":"2026-04-06T17:01:17.862Z","repository":{"id":341182045,"uuid":"1169221822","full_name":"acebot712/promptguard-python","owner":"acebot712","description":"PromptGuard Python SDK — Drop-in security for AI applications","archived":false,"fork":false,"pushed_at":"2026-03-25T12:27:25.000Z","size":77,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-03T17:47:38.982Z","etag":null,"topics":["ai-firewall","ai-safety","llm","prompt-injection","python","sdk","security"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/acebot712.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-28T11:03:31.000Z","updated_at":"2026-03-25T12:27:29.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/acebot712/promptguard-python","commit_stats":null,"previous_names":["acebot712/promptguard-python"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/acebot712/promptguard-python","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/acebot712%2Fpromptguard-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/acebot712%2Fpromptguard-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/acebot712%2Fpromptguard-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/acebot712%2Fpromptguard-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/acebot712","download_url":"https://codeload.github.com/acebot712/promptguard-python/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/acebot712%2Fpromptguard-python/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31481238,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-06T14:34:32.243Z","status":"ssl_error","status_checked_at":"2026-04-06T14:34:31.723Z","response_time":112,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-firewall","ai-safety","llm","prompt-injection","python","sdk","security"],"created_at":"2026-04-03T15:09:57.992Z","updated_at":"2026-04-06T17:01:17.853Z","avatar_url":"https://github.com/acebot712.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PromptGuard Python SDK\n\nDrop-in security for AI applications. No code changes required.\n\n## Installation\n\n```bash\npip install promptguard-sdk\n```\n\n## Two Ways to Secure Your App\n\n### Option 1: Auto-Instrumentation (Recommended for Frameworks)\n\nOne line secures **every LLM call** in your application, regardless of which framework you use (LangChain, CrewAI, AutoGen, LlamaIndex, Haystack, Semantic Kernel, or direct SDK usage):\n\n```python\nimport promptguard\npromptguard.init(api_key=\"pg_xxx\")\n\n# That's it. Every LLM call is now secured.\n# Works with ANY framework built on openai, anthropic, google-generativeai, cohere, or boto3.\n\nfrom openai import OpenAI\nclient = OpenAI()\nresponse = client.chat.completions.create(\n    model=\"gpt-4o\",\n    messages=[{\"role\": \"user\", \"content\": \"Hello!\"}]\n)\n# ^^ Scanned by PromptGuard before reaching OpenAI\n```\n\n**Supported SDKs** (auto-detected and patched):\n\n| SDK | Frameworks Covered |\n|-----|-------------------|\n| `openai` | LangChain, CrewAI, AutoGen, Semantic Kernel, direct usage |\n| `anthropic` | LangChain (ChatAnthropic), direct usage |\n| `google-generativeai` | LangChain, LlamaIndex, direct usage |\n| `cohere` | Haystack, LangChain, direct usage |\n| `boto3` (Bedrock) | AWS-native apps (Claude, Titan, Llama on Bedrock) |\n\n**Modes:**\n\n```python\n# Enforce mode (default) - blocks threats\npromptguard.init(api_key=\"pg_xxx\", mode=\"enforce\")\n\n# Monitor mode - logs threats without blocking (shadow mode)\npromptguard.init(api_key=\"pg_xxx\", mode=\"monitor\")\n\n# Scan responses too\npromptguard.init(api_key=\"pg_xxx\", scan_responses=True)\n\n# Fail-closed (block if Guard API is unreachable)\npromptguard.init(api_key=\"pg_xxx\", fail_open=False)\n```\n\n**Shutdown:**\n\n```python\npromptguard.shutdown()  # Removes all patches, closes connections\n```\n\n### Option 2: Proxy Mode (Drop-in Replacement)\n\nIf you prefer the proxy approach, just swap your client:\n\n```python\n# Before\nfrom openai import OpenAI\nclient = OpenAI()\n\n# After\nfrom promptguard import PromptGuard\nclient = PromptGuard(api_key=\"pg_xxx\")\n\n# Your existing code works unchanged!\n```\n\n## Framework-Specific Integrations\n\nFor deeper integration with richer context (chain names, tool calls, agent steps), use framework-specific callbacks alongside or instead of auto-instrumentation:\n\n### LangChain\n\n```python\nfrom promptguard.integrations.langchain import PromptGuardCallbackHandler\n\nhandler = PromptGuardCallbackHandler(api_key=\"pg_xxx\")\n\n# Attach to an LLM\nfrom langchain_openai import ChatOpenAI\nllm = ChatOpenAI(model=\"gpt-4o\", callbacks=[handler])\n\n# Or use globally with any chain\nchain.invoke({\"input\": \"...\"}, config={\"callbacks\": [handler]})\n```\n\nThe handler scans:\n- `on_llm_start` / `on_chat_model_start` - prompts before the LLM call\n- `on_llm_end` - responses after the LLM call\n- `on_tool_start` - tool inputs for injection attempts\n- `on_chain_start/end` - tracks chain context\n\n### CrewAI\n\n```python\nfrom crewai import Crew, Agent, Task\nfrom promptguard.integrations.crewai import PromptGuardGuardrail\n\npg = PromptGuardGuardrail(api_key=\"pg_xxx\")\n\ncrew = Crew(\n    agents=[...],\n    tasks=[...],\n    before_kickoff=pg.before_kickoff,\n    after_kickoff=pg.after_kickoff,\n)\n\ncrew.kickoff(inputs={\"topic\": \"AI safety\"})\n```\n\nYou can also wrap individual tools:\n\n```python\nfrom promptguard.integrations.crewai import secure_tool\nfrom crewai.tools import BaseTool\n\n@secure_tool(api_key=\"pg_xxx\")\nclass SearchTool(BaseTool):\n    name = \"search\"\n    description = \"Search the web\"\n\n    def _run(self, query: str) -\u003e str:\n        ...\n```\n\n### LlamaIndex\n\n```python\nfrom promptguard.integrations.llamaindex import PromptGuardCallbackHandler\nfrom llama_index.core.callbacks import CallbackManager\nfrom llama_index.core import Settings\n\npg_handler = PromptGuardCallbackHandler(api_key=\"pg_xxx\")\nSettings.callback_manager = CallbackManager([pg_handler])\n\n# All LlamaIndex queries are now scanned\n```\n\n## Standalone Guard API\n\nFor any language or framework, call the Guard API directly:\n\n```python\nfrom promptguard import GuardClient\n\nguard = GuardClient(api_key=\"pg_xxx\")\n\n# Scan before sending to LLM\ndecision = guard.scan(\n    messages=[{\"role\": \"user\", \"content\": \"Hello!\"}],\n    direction=\"input\",\n    model=\"gpt-4o\",\n)\n\nif decision.blocked:\n    print(f\"Blocked: {decision.threat_type}\")\nelif decision.redacted:\n    # Use decision.redacted_messages instead of original\n    print(\"Content was redacted\")\nelse:\n    # Safe to proceed\n    pass\n```\n\nOr via HTTP directly (any language):\n\n```bash\ncurl -X POST https://api.promptguard.co/api/v1/guard \\\n  -H \"Authorization: Bearer pg_xxx\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"messages\": [{\"role\": \"user\", \"content\": \"Hello!\"}],\n    \"direction\": \"input\",\n    \"model\": \"gpt-4o\"\n  }'\n```\n\n## Security Scanning\n\n```python\nfrom promptguard import PromptGuard\n\npg = PromptGuard(api_key=\"pg_xxx\")\n\n# Scan content for threats\nresult = pg.security.scan(\"Ignore previous instructions...\")\nif result[\"blocked\"]:\n    print(f\"Threat detected: {result['reason']}\")\n```\n\n## PII Redaction\n\n```python\nresult = pg.security.redact(\n    \"My email is john@example.com and SSN is 123-45-6789\"\n)\nprint(result[\"redacted\"])\n# Output: \"My email is [EMAIL] and SSN is [SSN]\"\n```\n\n## Red Team Testing\n\n```python\nfrom promptguard import PromptGuard\n\npg = PromptGuard(api_key=\"pg_xxx\")\n\n# Run the autonomous red team agent (LLM-powered mutation)\nreport = pg.redteam.run_autonomous(\n    budget=200,\n    target_preset=\"support_bot:strict\",\n)\nprint(f\"Grade: {report['grade']}, Bypass rate: {report['bypass_rate']:.0%}\")\n\n# Get Attack Intelligence stats\nstats = pg.redteam.intelligence_stats()\nprint(f\"Total patterns: {stats['total_patterns']}\")\n```\n\nThe async client mirrors the same methods:\n\n```python\nasync with PromptGuardAsync(api_key=\"pg_xxx\") as pg:\n    report = await pg.redteam.run_autonomous(budget=200)\n    stats = await pg.redteam.intelligence_stats()\n```\n\n## Async Support\n\nThe `PromptGuardAsync` client provides a fully asynchronous interface for non-blocking usage in async applications:\n\n```python\nfrom promptguard import PromptGuardAsync\n\nasync with PromptGuardAsync(api_key=\"pg_xxx\") as pg:\n    response = await pg.chat.completions.create(\n        model=\"gpt-4\",\n        messages=[{\"role\": \"user\", \"content\": \"Hello!\"}]\n    )\n\n    # Async security scanning\n    result = await pg.security.scan(\"Check this content\")\n\n    # Async PII redaction\n    redacted = await pg.security.redact(\"My email is john@example.com\")\n```\n\nThe async client mirrors the synchronous API - every method available on `PromptGuard` has an `await`-able counterpart on `PromptGuardAsync`.\n\n## Retry Logic\n\nBoth `PromptGuard` and `PromptGuardAsync` support configurable retry behavior for transient failures:\n\n```python\nfrom promptguard import PromptGuard\n\npg = PromptGuard(\n    api_key=\"pg_xxx\",\n    max_retries=3,        # Number of retry attempts (default: 2)\n    retry_delay=0.5,      # Base delay in seconds between retries (default: 0.25)\n)\n```\n\nRetries use exponential backoff starting from `retry_delay`. Only transient errors (network timeouts, 5xx responses) are retried; client errors (4xx) fail immediately.\n\n## Embeddings\n\nScan and secure embedding requests through the proxy:\n\n```python\nfrom promptguard import PromptGuard\n\npg = PromptGuard(api_key=\"pg_xxx\")\n\nresponse = pg.embeddings.create(\n    model=\"text-embedding-3-small\",\n    input=\"The quick brown fox jumps over the lazy dog\",\n)\nprint(response.data[0].embedding[:5])\n```\n\nBatch embedding requests are also supported:\n\n```python\nresponse = pg.embeddings.create(\n    model=\"text-embedding-3-small\",\n    input=[\"First document\", \"Second document\", \"Third document\"],\n)\nfor item in response.data:\n    print(f\"Index {item.index}: {len(item.embedding)} dimensions\")\n```\n\n## Configuration\n\n```python\nfrom promptguard import PromptGuard, Config\n\nconfig = Config(\n    api_key=\"pg_xxx\",\n    base_url=\"https://api.promptguard.co/api/v1/proxy\",\n    timeout=30.0,\n)\n\npg = PromptGuard(config=config)\n```\n\n## Environment Variables\n\n```bash\nexport PROMPTGUARD_API_KEY=\"pg_xxx\"\nexport PROMPTGUARD_BASE_URL=\"https://api.promptguard.co/api/v1\"\n```\n\n## Error Handling\n\n```python\nfrom promptguard import PromptGuard, PromptGuardBlockedError\n\n# Auto-instrumentation\nimport promptguard\npromptguard.init(api_key=\"pg_xxx\")\n\ntry:\n    response = client.chat.completions.create(...)\nexcept PromptGuardBlockedError as e:\n    print(f\"Blocked: {e.decision.threat_type}\")\n    print(f\"Event ID: {e.decision.event_id}\")\n```\n\n## Links\n\n- [Documentation](https://docs.promptguard.co)\n- [SDK Reference](https://docs.promptguard.co/sdks/python)\n- [Support](mailto:support@promptguard.co)\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Facebot712%2Fpromptguard-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Facebot712%2Fpromptguard-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Facebot712%2Fpromptguard-python/lists"}