-
Notifications
You must be signed in to change notification settings - Fork 350
Integrate GPT OSS Safeguard into ThreatExchange as chat command #1929
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
Open
ZhiyLiu
wants to merge
9
commits into
facebook:main
Choose a base branch
from
ZhiyLiu:integrate_gpt_oss_safeguard
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4746687
Integrate GPT OSS Safeguard into ThreatExchange as chat command
ZhiyLiu 0166517
Merge branch 'main' into integrate_gpt_oss_safeguard
ZhiyLiu 238ee6f
Integrate GPT OSS Safeguard into ThreatExchange as chat command
ZhiyLiu b3bfb9d
address the change request about classifier interface
ZhiyLiu 727b254
fix an issue of merging code
ZhiyLiu 7ae2fbf
1. removed the chat command
ZhiyLiu 4650acd
change the structure of folders
ZhiyLiu 5a326a0
revert changes in main.py
ZhiyLiu 580b1cd
Merge branch 'main' into integrate_gpt_oss_safeguard
ZhiyLiu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
119 changes: 119 additions & 0 deletions
119
python-threatexchange/threatexchange/classifier/safeguard/gpt_classifier.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Minimal client for running an OSS Safeguard policy via an OpenAI-compatible API.""" | ||
|
|
||
| import json | ||
| import os | ||
| import re | ||
| from dataclasses import dataclass | ||
| from typing import Any | ||
|
|
||
| from openai import BadRequestError, OpenAI | ||
| from threatexchange.classifier.classifier import Classifier | ||
|
|
||
| DEFAULT_OPENAI_POLICY_MODEL = "osb-120b-ev3" | ||
|
|
||
|
|
||
| def _strip_code_fences(text: str) -> str: | ||
| text = text.strip() | ||
| text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE) | ||
| text = re.sub(r"\s*```$", "", text) | ||
| return text.strip() | ||
|
|
||
|
|
||
| def _try_parse_json_object(text: str) -> dict[str, Any] | None: | ||
| text = _strip_code_fences(text) | ||
| try: | ||
| val = json.loads(text) | ||
| if isinstance(val, dict): | ||
| return val | ||
| except Exception: | ||
| pass | ||
|
|
||
| # Fallback: try to extract the first JSON object from a longer string. | ||
| start = text.find("{") | ||
| end = text.rfind("}") | ||
| if start == -1 or end == -1 or end <= start: | ||
| return None | ||
| candidate = text[start : end + 1] | ||
| try: | ||
| val = json.loads(candidate) | ||
| if isinstance(val, dict): | ||
| return val | ||
| except Exception: | ||
| return None | ||
| return None | ||
|
|
||
|
|
||
| def _maybe_raise_helpful_model_error(exc: BadRequestError, *, model: str) -> None: | ||
| body = getattr(exc, "body", None) | ||
| if not isinstance(body, dict): | ||
| return | ||
| err = body.get("error") | ||
| if not isinstance(err, dict): | ||
| return | ||
|
|
||
| code = err.get("code") | ||
| message = err.get("message") | ||
| if code != "model_not_found": | ||
| return | ||
|
|
||
| msg = str(message) if message else f"Model not found: {model!r}" | ||
| raise RuntimeError( | ||
| f"{msg}\n\n" | ||
| f"This repo assumes the hackathon-provided API model {DEFAULT_OPENAI_POLICY_MODEL!r}.\n" | ||
| "If you still see this error, confirm you have access to that model in your OpenAI project/org." | ||
| ) from exc | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class GPTClassifier(Classifier): | ||
| client: OpenAI | ||
| model: str | ||
|
|
||
| @classmethod | ||
| def from_env(cls) -> "GPTClassifier": | ||
| api_key = os.getenv("OPENAI_API_KEY") | ||
| if not api_key: | ||
| raise RuntimeError("Missing OPENAI_API_KEY") | ||
|
|
||
| model = DEFAULT_OPENAI_POLICY_MODEL | ||
|
|
||
| client = OpenAI( | ||
| api_key=api_key, | ||
| organization=os.getenv("OPENAI_ORG_ID") or None, | ||
| project=os.getenv("OPENAI_PROJECT_ID") or None, | ||
| ) | ||
| return cls(client=client, model=model) # type: ignore[arg-type] | ||
|
|
||
| def get_content_types(self) -> str: | ||
| return "text" | ||
|
|
||
| def classify(self, *, content: str, policy: str) -> dict[str, Any]: | ||
| """ | ||
| Returns: | ||
| { | ||
| "raw_text": "...", | ||
| "parsed": { ... } | null | ||
| } | ||
| """ | ||
| raw_text = self._classify_via_responses(content=content, policy=policy) | ||
|
|
||
| return { | ||
| "raw_text": raw_text, | ||
| "parsed": _try_parse_json_object(raw_text), | ||
| } | ||
|
|
||
| def _classify_via_responses(self, *, content: str, policy: str) -> str: | ||
| kwargs: dict[str, Any] = { | ||
| "model": self.model, | ||
| # Harmony-style message roles: policy in developer message, content in user message. | ||
| "input": [ | ||
| {"role": "developer", "content": policy}, | ||
| {"role": "user", "content": content}, | ||
| ], | ||
| } | ||
| try: | ||
| response = self.client.responses.create(**kwargs) | ||
| except BadRequestError as exc: | ||
| _maybe_raise_helpful_model_error(exc, model=self.model) | ||
| raise | ||
| return (response.output_text or "").strip() |
38 changes: 38 additions & 0 deletions
38
python-threatexchange/threatexchange/classifier/safeguard/policy/basic_policy.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| # Basic OSS Safeguard policy (hackathon starter) | ||
|
|
||
| Reasoning: medium | ||
|
|
||
| You are a content safety classifier. Apply this policy to the user-provided text and output a single JSON object. | ||
|
|
||
| ## Output schema (JSON only) | ||
|
|
||
| Return **only** a JSON object with: | ||
|
|
||
| - `label`: one of `"ALLOW"`, `"REVIEW"`, `"BLOCK"` | ||
| - `action`: one of `"allow"`, `"route"`, `"block"` | ||
| - `category`: one of `"none"`, `"self_harm"`, `"violence"`, `"sexual"`, `"hate_or_harassment"`, `"illicit"`, `"other"` | ||
| - `confidence`: number between `0` and `1` | ||
| - `rationale`: short, non-sensitive explanation (do not quote the policy) | ||
|
|
||
| ## Policy rules (high level) | ||
|
|
||
| ### BLOCK | ||
| Use `label="BLOCK"` and `action="block"` if the content includes: | ||
| - instructions or intent to do violence or severe wrongdoing | ||
| - explicit sexual content involving minors | ||
| - credible self-harm intent or encouragement | ||
|
|
||
| ### REVIEW | ||
| Use `label="REVIEW"` and `action="route"` if the content includes: | ||
| - ambiguous self-harm ideation without intent | ||
| - hateful or harassing language | ||
| - requests for wrongdoing (e.g., hacking) without concrete instructions | ||
| - sexual content that is suggestive but not explicit | ||
|
|
||
| ### ALLOW | ||
| Use `label="ALLOW"` and `action="allow"` otherwise. | ||
|
|
||
| ## Reminders | ||
|
|
||
| - Be conservative: if uncertain, choose `REVIEW`. | ||
| - Return JSON only (no markdown, no backticks). | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.