-
Notifications
You must be signed in to change notification settings - Fork 488
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
feat: add mistral as a new guardrail provider #756
Open
b4s36t4
wants to merge
11
commits into
Portkey-AI:main
Choose a base branch
from
b4s36t4:feat/mistral-guardrail
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 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e1919bf
feat: add mistral as a new guardrail provider
b4s36t4 7a7f324
Merge branch 'main' into feat/mistral-guardrail
b4s36t4 a9f6b11
fix: add test cases for mistral
b4s36t4 fda464f
Merge branch 'feat/mistral-guardrail' of github.com:b4s36t4/Rubeus in…
b4s36t4 34fa244
Merge branch 'main' of github.com:Portkey-AI/gateway into feat/mistra…
b4s36t4 3881aaa
chore: add extra test cases
b4s36t4 ae187bd
Merge branch 'main' into feat/mistral-guardrail
b4s36t4 b19d7c5
Merge branch 'main' into feat/mistral-guardrail
b4s36t4 8a1e01d
fix: review commits
b4s36t4 88930e0
Merge branch 'feat/mistral-guardrail' of github.com:b4s36t4/Rubeus in…
b4s36t4 08cd951
fix: mistral guardrails to moderations function
b4s36t4 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
This file contains 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
This file contains 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 @@ | ||
import { | ||
HookEventType, | ||
PluginContext, | ||
PluginHandler, | ||
PluginParameters, | ||
} from '../types'; | ||
import { getText, post } from '../utils'; | ||
|
||
interface MistralResponse { | ||
id: string; | ||
model: string; | ||
results: [ | ||
{ | ||
categories: { | ||
sexual: boolean; | ||
hate_and_discrimination: boolean; | ||
violence_and_threats: boolean; | ||
dangerous_and_criminal_content: boolean; | ||
selfharm: boolean; | ||
health: boolean; | ||
financial: boolean; | ||
law: boolean; | ||
pii: boolean; | ||
}; | ||
category_score: { | ||
sexual: number; | ||
hate_and_discrimination: number; | ||
violence_and_threats: number; | ||
dangerous_and_criminal_content: number; | ||
selfharm: number; | ||
health: number; | ||
financial: number; | ||
law: number; | ||
pii: number; | ||
}; | ||
}, | ||
]; | ||
} | ||
|
||
type GuardrailFunction = keyof MistralResponse['results'][0]['categories']; | ||
|
||
export const mistralGuardrailHandler: PluginHandler = async ( | ||
context: PluginContext, | ||
parameters: PluginParameters, | ||
eventType: HookEventType, | ||
_options, | ||
fn: string | ||
) => { | ||
let error = null; | ||
let verdict = true; | ||
let data = null; | ||
|
||
const creds = parameters.credentials as Record<string, string>; | ||
if (!creds.apiKey) { | ||
return { | ||
error: 'Mistral API key not provided.', | ||
verdict: false, | ||
data: null, | ||
}; | ||
} | ||
|
||
let model = 'mistral-moderation-latest'; | ||
|
||
if (parameters.model) { | ||
// Model can be passed dynamically | ||
model = parameters.model; | ||
} | ||
|
||
const guardrailFunction = fn as GuardrailFunction; | ||
|
||
const text = getText(context, eventType); | ||
const messages = | ||
eventType === 'beforeRequestHook' | ||
? context.request?.json?.messages | ||
: context.response?.json?.messages; | ||
|
||
// should contain text or should contain messages array | ||
if ( | ||
(!text && !Array.isArray(messages)) || | ||
(Array.isArray(messages) && messages.length === 0) | ||
) { | ||
return { | ||
error: 'Mistral: Invalid Request body', | ||
verdict: false, | ||
data: null, | ||
}; | ||
} | ||
|
||
// Use conversation guardrail if it's a chatcomplete and before hook | ||
const shouldUseConversation = | ||
eventType === 'beforeRequestHook' && context.requestType === 'chatComplete'; | ||
const url = shouldUseConversation | ||
? 'https://api.mistral.ai/v1/chat/moderations' | ||
: 'https://api.mistral.ai/v1/moderations'; | ||
|
||
try { | ||
const request = await post<MistralResponse>( | ||
url, | ||
{ | ||
model: model, | ||
...(!shouldUseConversation && { input: [text] }), | ||
...(shouldUseConversation && { input: [messages] }), | ||
}, | ||
{ | ||
headers: { | ||
Authorization: `Bearer ${creds.apiKey}`, | ||
'Content-Type': 'application/json', | ||
}, | ||
} | ||
); | ||
|
||
verdict = request.results?.[0]?.categories[guardrailFunction]; | ||
} catch (error) { | ||
error = error; | ||
verdict = false; | ||
} | ||
|
||
return { error, verdict, data }; | ||
}; |
This file contains 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,135 @@ | ||
{ | ||
"id": "mistral", | ||
"description": "Mistral Content Moderation classifier leverages the most relevant policy categories for effective guardrails and introduces a pragmatic approach to LLM safety by addressing model-generated harms such as unqualified advice and PII", | ||
"credentials": { | ||
VisargD marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"type": "object", | ||
"properties": { | ||
"apiKey": { | ||
"type": "string", | ||
"label": "API Key", | ||
"description": "Find your API key in the Mistral la-plateforme", | ||
"encrypted": true | ||
} | ||
}, | ||
"required": ["apiKey"] | ||
}, | ||
"functions": [ | ||
{ | ||
"name": "Detect PII", | ||
"id": "pii", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that requests, shares, or attempts to elicit personal identifying information such as full names, addresses, phone numbers, social security numbers, or financial account details." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Sexual Content", | ||
"id": "sexual", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Material that explicitly depicts, describes, or promotes sexual activities, nudity, or sexual services. This includes pornographic content, graphic descriptions of sexual acts, and solicitation for sexual purposes. Educational or medical content about sexual health presented in a non-explicit, informational context is generally exempted." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Hate & Discrimination", | ||
"id": "hate_and_discrimination", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that expresses prejudice, hostility, or advocates discrimination against individuals or groups based on protected characteristics such as race, ethnicity, religion, gender, sexual orientation, or disability. This includes slurs, dehumanizing language, calls for exclusion or harm targeted at specific groups, and persistent harassment or bullying of individuals based on these characteristics." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Violent & Thereat", | ||
"id": "violence_and_threats", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that describes, glorifies, incites, or threatens physical violence against individuals or groups. This includes graphic depictions of injury or death, explicit threats of harm, and instructions for carrying out violent acts. This category covers both targeted threats and general promotion or glorification of violence." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Dangerous & Criminal Content", | ||
"id": "dangerous_and_criminal_content", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that promotes or provides instructions for illegal activities or extremely hazardous behaviors that pose a significant risk of physical harm, death, or legal consequences. This includes guidance on creating weapons or explosives, encouragement of extreme risk-taking behaviors, and promotion of non-violent crimes such as fraud, theft, or drug trafficking." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Selfharm", | ||
"id": "selfharm", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that promotes, instructs, plans, or encourages deliberate self-injury, suicide, eating disorders, or other self-destructive behaviors. This includes detailed methods, glorification, statements of intent, dangerous challenges, and related slang terms" | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Health", | ||
"id": "health", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that contains or tries to elicit detailed or tailored medical advice." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Finance", | ||
"id": "financial", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that contains or tries to elicit detailed or tailored financial advice." | ||
} | ||
], | ||
"parameters": {} | ||
}, | ||
{ | ||
"name": "Detect Law", | ||
"id": "law", | ||
"supportedHooks": ["beforeRequestHook", "afterRequestHook"], | ||
"type": "guardrail", | ||
"description": [ | ||
{ | ||
"type": "subHeading", | ||
"text": "Content that contains or tries to elicit detailed or tailored legal advice." | ||
} | ||
], | ||
"parameters": {} | ||
} | ||
] | ||
} |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can convert this to a single plugin like portkey.moderateContent and accept all the required categories in it